@readium/shared 1.2.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/LICENSE +28 -0
- package/README.MD +27 -0
- package/dist/index.js +2536 -0
- package/dist/index.umd.cjs +2 -0
- package/package.json +73 -0
- package/src/fetcher/Fetcher.ts +37 -0
- package/src/fetcher/HttpFetcher.ts +122 -0
- package/src/fetcher/Resource.ts +37 -0
- package/src/fetcher/index.ts +2 -0
- package/src/index.ts +4 -0
- package/src/opds/Acquisition.ts +54 -0
- package/src/opds/Availability.ts +61 -0
- package/src/opds/Copies.ts +43 -0
- package/src/opds/Holds.ts +43 -0
- package/src/opds/Price.ts +51 -0
- package/src/opds/index.ts +5 -0
- package/src/publication/BelongsTo.ts +51 -0
- package/src/publication/Contributor.ts +129 -0
- package/src/publication/GuidedNavigation.ts +176 -0
- package/src/publication/Link.ts +332 -0
- package/src/publication/LocalizedString.ts +74 -0
- package/src/publication/Locator.ts +225 -0
- package/src/publication/LocatorCollection.ts +133 -0
- package/src/publication/Manifest.ts +256 -0
- package/src/publication/Metadata.ts +329 -0
- package/src/publication/Properties.ts +44 -0
- package/src/publication/Publication.ts +148 -0
- package/src/publication/PublicationCollection.ts +144 -0
- package/src/publication/ReadingProgression.ts +28 -0
- package/src/publication/Subject.ts +115 -0
- package/src/publication/encryption/Encryption.ts +68 -0
- package/src/publication/encryption/Properties.ts +20 -0
- package/src/publication/encryption/index.ts +2 -0
- package/src/publication/epub/EPUBLayout.ts +10 -0
- package/src/publication/epub/Presentation.ts +16 -0
- package/src/publication/epub/Properties.ts +28 -0
- package/src/publication/epub/Publication.ts +51 -0
- package/src/publication/epub/index.ts +4 -0
- package/src/publication/html/DomRange.ts +63 -0
- package/src/publication/html/DomRangePoint.ts +64 -0
- package/src/publication/html/Locations.ts +129 -0
- package/src/publication/html/index.ts +3 -0
- package/src/publication/index.ts +19 -0
- package/src/publication/opds/Properties.ts +84 -0
- package/src/publication/opds/Publication.ts +14 -0
- package/src/publication/opds/index.ts +2 -0
- package/src/publication/presentation/Metadata.ts +19 -0
- package/src/publication/presentation/Presentation.ts +155 -0
- package/src/publication/presentation/Properties.ts +70 -0
- package/src/publication/presentation/index.ts +3 -0
- package/src/publication/services/content/Content.ts +36 -0
- package/src/publication/services/content/ContentTokenizer.ts +62 -0
- package/src/publication/services/content/Iterator.ts +46 -0
- package/src/publication/services/content/element/attributes.ts +44 -0
- package/src/publication/services/content/element/element.ts +118 -0
- package/src/publication/services/content/element/index.ts +3 -0
- package/src/publication/services/content/element/text_role.ts +60 -0
- package/src/publication/services/content/index.ts +5 -0
- package/src/publication/services/content/iterators/HTMLResourceContentIterator.ts +571 -0
- package/src/publication/services/content/iterators/PDFTextContentIterator.ts +184 -0
- package/src/publication/services/content/iterators/PublicationContentIterator.ts +144 -0
- package/src/publication/services/content/iterators/helpers.ts +146 -0
- package/src/publication/services/content/iterators/index.ts +3 -0
- package/src/publication/services/index.ts +1 -0
- package/src/util/JSONParse.ts +31 -0
- package/src/util/Language.ts +5 -0
- package/src/util/URITemplate.ts +83 -0
- package/src/util/index.ts +5 -0
- package/src/util/mediatype/MediaType.ts +563 -0
- package/src/util/mediatype/index.ts +1 -0
- package/src/util/tokenizer/TextTokenizer.ts +126 -0
- package/src/util/tokenizer/Tokenizer.ts +8 -0
- package/src/util/tokenizer/index.ts +2 -0
- package/src/util/tokenizer/tokenize-english/README.md +7 -0
- package/src/util/tokenizer/tokenize-english/abbreviations.js +52 -0
- package/src/util/tokenizer/tokenize-english/index.d.ts +3 -0
- package/src/util/tokenizer/tokenize-english/index.js +243 -0
- package/src/util/tokenizer/tokenize-english/utils.js +16 -0
- package/src/util/tokenizer/tokenize-text/README.MD +6 -0
- package/src/util/tokenizer/tokenize-text/index.d.ts +52 -0
- package/src/util/tokenizer/tokenize-text/index.js +256 -0
- package/src/util/tokenizer/tokenize-text/tokens.js +100 -0
- package/types/src/fetcher/Fetcher.d.ts +27 -0
- package/types/src/fetcher/HttpFetcher.d.ts +28 -0
- package/types/src/fetcher/Resource.d.ts +15 -0
- package/types/src/fetcher/index.d.ts +2 -0
- package/types/src/index.d.ts +4 -0
- package/types/src/opds/Acquisition.d.ts +26 -0
- package/types/src/opds/Availability.d.ts +32 -0
- package/types/src/opds/Copies.d.ts +22 -0
- package/types/src/opds/Holds.d.ts +22 -0
- package/types/src/opds/Price.d.ts +29 -0
- package/types/src/opds/index.d.ts +5 -0
- package/types/src/publication/BelongsTo.d.ts +23 -0
- package/types/src/publication/Contributor.d.ts +60 -0
- package/types/src/publication/GuidedNavigation.d.ts +70 -0
- package/types/src/publication/Link.d.ts +128 -0
- package/types/src/publication/LocalizedString.d.ts +48 -0
- package/types/src/publication/Locator.d.ts +101 -0
- package/types/src/publication/LocatorCollection.d.ts +54 -0
- package/types/src/publication/Manifest.d.ts +59 -0
- package/types/src/publication/Metadata.d.ts +101 -0
- package/types/src/publication/Properties.d.ts +28 -0
- package/types/src/publication/Publication.d.ts +53 -0
- package/types/src/publication/PublicationCollection.d.ts +34 -0
- package/types/src/publication/ReadingProgression.d.ts +9 -0
- package/types/src/publication/Subject.d.ts +56 -0
- package/types/src/publication/encryption/Encryption.d.ts +33 -0
- package/types/src/publication/encryption/Properties.d.ts +10 -0
- package/types/src/publication/encryption/index.d.ts +2 -0
- package/types/src/publication/epub/EPUBLayout.d.ts +5 -0
- package/types/src/publication/epub/Presentation.d.ts +7 -0
- package/types/src/publication/epub/Properties.d.ts +14 -0
- package/types/src/publication/epub/Publication.d.ts +19 -0
- package/types/src/publication/epub/index.d.ts +4 -0
- package/types/src/publication/html/DomRange.d.ts +40 -0
- package/types/src/publication/html/DomRangePoint.d.ts +36 -0
- package/types/src/publication/html/Locations.d.ts +45 -0
- package/types/src/publication/html/index.d.ts +3 -0
- package/types/src/publication/index.d.ts +19 -0
- package/types/src/publication/opds/Properties.d.ts +38 -0
- package/types/src/publication/opds/Publication.d.ts +6 -0
- package/types/src/publication/opds/index.d.ts +2 -0
- package/types/src/publication/presentation/Metadata.d.ts +6 -0
- package/types/src/publication/presentation/Presentation.d.ts +95 -0
- package/types/src/publication/presentation/Properties.d.ts +32 -0
- package/types/src/publication/presentation/index.d.ts +3 -0
- package/types/src/publication/services/content/Content.d.ts +20 -0
- package/types/src/publication/services/content/ContentTokenizer.d.ts +19 -0
- package/types/src/publication/services/content/Iterator.d.ts +38 -0
- package/types/src/publication/services/content/element/attributes.d.ts +31 -0
- package/types/src/publication/services/content/element/element.d.ts +107 -0
- package/types/src/publication/services/content/element/index.d.ts +3 -0
- package/types/src/publication/services/content/element/text_role.d.ts +53 -0
- package/types/src/publication/services/content/index.d.ts +5 -0
- package/types/src/publication/services/content/iterators/HTMLResourceContentIterator.d.ts +30 -0
- package/types/src/publication/services/content/iterators/PDFTextContentIterator.d.ts +60 -0
- package/types/src/publication/services/content/iterators/PublicationContentIterator.d.ts +59 -0
- package/types/src/publication/services/content/iterators/helpers.d.ts +10 -0
- package/types/src/publication/services/content/iterators/index.d.ts +3 -0
- package/types/src/publication/services/index.d.ts +1 -0
- package/types/src/util/JSONParse.d.ts +11 -0
- package/types/src/util/Language.d.ts +1 -0
- package/types/src/util/URITemplate.d.ts +24 -0
- package/types/src/util/index.d.ts +5 -0
- package/types/src/util/mediatype/MediaType.d.ts +148 -0
- package/types/src/util/mediatype/index.d.ts +1 -0
- package/types/src/util/tokenizer/TextTokenizer.d.ts +39 -0
- package/types/src/util/tokenizer/Tokenizer.d.ts +6 -0
- package/types/src/util/tokenizer/index.d.ts +2 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
(function(o,N){typeof exports=="object"&&typeof module<"u"?N(exports):typeof define=="function"&&define.amd?define(["exports"],N):(o=typeof globalThis<"u"?globalThis:o||self,N(o.shared={}))})(this,function(o){"use strict";class N{close(){}links(){return[]}get(t){throw Error("This is an empty fetcher")}}class St{constructor(t,e){this.client=t||window.fetch.bind(window),this.baseUrl=e}links(){return[]}get(t){const e=t.toURL(this.baseUrl);if(e===void 0)throw Error(`Invalid HREF: ${t.href}`);return new ut(this.client,t,e)}close(){}}class ut{constructor(t,e,i){this.client=t||window.fetch.bind(window),this._link=e,this.url=i}async headResponse(){if(this._headResponse)return this._headResponse;const t=await this.client(this.url,{method:"HEAD"});if(!t.ok)throw new Error(`http HEAD request for ${this.url} failed with HTTP status code ${t.status}`);return this._headResponse=t,t}close(){}async link(){return this._link}async read(t){if(t)throw new Error("http read range not implemented!");const e=await this.client(this.url);if(!e.ok)throw new Error(`http GET request for ${this.url} failed with HTTP status code ${e.status}`);return new Uint8Array(await e.arrayBuffer())}async length(){const e=(await this.headResponse()).headers.get("content-length");if(e===null||e==="")throw new Error("length for resource unavailable");return parseInt(e)}async readAsJSON(){const t=await this.client(this.url);if(!t.ok)throw new Error(`http GET request for ${this.url} failed with HTTP status code ${t.status}`);return await t.json()}async readAsString(){const t=await this.client(this.url);if(!t.ok)throw new Error(`http GET request for ${this.url} failed with HTTP status code ${t.status}`);return await t.text()}async readAsXML(){const t=await this.client(this.url);if(!t.ok)throw new Error(`http GET request for ${this.url} failed with HTTP status code ${t.status}`);return new DOMParser().parseFromString(await t.text(),"application/xml")}}class M{constructor(t){this.algorithm=t.algorithm,this.compression=t.compression,this.originalLength=t.originalLength,this.profile=t.profile,this.scheme=t.scheme}static deserialize(t){if(t&&t.algorithm)return new M({algorithm:t.algorithm,compression:t.compression,originalLength:t.originalLength,profile:t.profile,scheme:t.scheme})}serialize(){const t={algorithm:this.algorithm};return this.compression!==void 0&&(t.compression=this.compression),this.originalLength!==void 0&&(t.originalLength=this.originalLength),this.profile!==void 0&&(t.profile=this.profile),this.scheme!==void 0&&(t.scheme=this.scheme),t}}class g{constructor(t){this.otherProperties=t}static deserialize(t){if(t)return new g(t)}serialize(){return this.otherProperties}add(t){const e=Object.assign({},this.otherProperties);for(const i in t)e[i]=t[i];return new g(e)}}Object.defineProperty(g.prototype,"encryption",{get:function(){return M.deserialize(this.otherProperties.encrypted)}});var rt=(r=>(r.fixed="fixed",r.reflowable="reflowable",r))(rt||{}),dt=(r=>(r.auto="auto",r.landscape="landscape",r.portrait="portrait",r))(dt||{}),pt=(r=>(r.auto="auto",r.clipped="clipped",r.paginated="paginated",r.scrolled="scrolled",r))(pt||{}),U=(r=>(r.left="left",r.right="right",r.center="center",r))(U||{}),gt=(r=>(r.auto="auto",r.both="both",r.none="none",r.landscape="landscape",r))(gt||{}),mt=(r=>(r.contain="contain",r.cover="cover",r.width="width",r.height="height",r))(mt||{});class W{constructor(t){this.clipped=t.clipped,this.fit=t.fit,this.orientation=t.orientation,this.spread=t.spread,this.layout=t.layout,this.continuous=t.continuous,this.overflow=t.overflow}static deserialize(t){if(t)return new W({clipped:t.clipped,continuous:t.continuous,fit:t.fit,orientation:t.orientation,overflow:t.overflow,spread:t.spread,layout:t.layout})}serialize(){const t={};return this.clipped!==void 0&&(t.clipped=this.clipped),this.continuous!==void 0&&(t.continuous=this.continuous),this.fit!==void 0&&(t.fit=this.fit),this.orientation!==void 0&&(t.orientation=this.orientation),this.overflow!==void 0&&(t.overflow=this.overflow),this.spread!==void 0&&(t.spread=this.spread),this.layout!==void 0&&(t.layout=this.layout),t}}W.prototype.layoutOf=function(r){var t;return((t=r.properties)==null?void 0:t.getLayout())||this.layout||rt.reflowable},g.prototype.getContains=function(){return new Set(this.otherProperties.contains||[])},g.prototype.getLayout=function(){return this.otherProperties.layout};class n{constructor(t){let e,i,s=t.mediaType.replace(/\s/g,"").split(";");const a=s[0].split("/");if(a.length===2){if(e=a[0].toLowerCase().trim(),i=a[1].toLowerCase().trim(),e.length===0||i.length===0)throw new Error("Invalid media type")}else throw new Error("Invalid media type");const l={};for(let f=1;f<s.length;f++){const m=s[f].split("=");if(m.length===2){const T=m[0].toLocaleLowerCase(),Z=T==="charset"?m[1].toUpperCase():m[1];l[T]=Z}}const h={},c=Object.keys(l);c.sort((f,m)=>f.localeCompare(m)),c.forEach(f=>h[f]=l[f]);let p="";for(const f in h){const m=h[f];p+=`;${f}=${m}`}const u=`${e}/${i}${p}`,d=h.encoding;this.string=u,this.type=e,this.subtype=i,this.parameters=h,this.encoding=d,this.name=t.name,this.fileExtension=t.fileExtension}static parse(t){return new n(t)}get structuredSyntaxSuffix(){const t=this.subtype.split("+");return t.length>1?`+${t[t.length-1]}`:void 0}get charset(){return this.parameters.charset}contains(t){const e=typeof t=="string"?n.parse({mediaType:t}):t;if(!((this.type==="*"||this.type===e.type)&&(this.subtype==="*"||this.subtype===e.subtype)))return!1;const i=new Set(Object.entries(this.parameters).map(([a,l])=>`${a}=${l}`)),s=new Set(Object.entries(e.parameters).map(([a,l])=>`${a}=${l}`));for(const a of Array.from(i.values()))if(!s.has(a))return!1;return!0}matches(t){const e=typeof t=="string"?n.parse({mediaType:t}):t;return this.contains(e)||e.contains(this)}matchesAny(...t){for(const e of t)if(this.matches(e))return!0;return!1}equals(t){return this.string===t.string}get isZIP(){return this.matchesAny(n.ZIP,n.LCP_PROTECTED_AUDIOBOOK,n.LCP_PROTECTED_PDF)||this.structuredSyntaxSuffix==="+zip"}get isJSON(){return this.matchesAny(n.JSON)||this.structuredSyntaxSuffix==="+json"}get isOPDS(){return this.matchesAny(n.OPDS1,n.OPDS1_ENTRY,n.OPDS2,n.OPDS2_PUBLICATION,n.OPDS_AUTHENTICATION)||this.structuredSyntaxSuffix==="+json"}get isHTML(){return this.matchesAny(n.HTML,n.XHTML)}get isBitmap(){return this.matchesAny(n.BMP,n.GIF,n.JPEG,n.PNG,n.TIFF,n.WEBP)}get isAudio(){return this.type==="audio"}get isVideo(){return this.type==="video"}get isRWPM(){return this.matchesAny(n.READIUM_AUDIOBOOK_MANIFEST,n.DIVINA_MANIFEST,n.READIUM_WEBPUB_MANIFEST)}get isPublication(){return this.matchesAny(n.READIUM_AUDIOBOOK,n.READIUM_AUDIOBOOK_MANIFEST,n.CBZ,n.DIVINA,n.DIVINA_MANIFEST,n.EPUB,n.LCP_PROTECTED_AUDIOBOOK,n.LCP_PROTECTED_PDF,n.LPF,n.PDF,n.W3C_WPUB_MANIFEST,n.READIUM_WEBPUB,n.READIUM_WEBPUB_MANIFEST,n.ZAB)}static get AAC(){return n.parse({mediaType:"audio/aac",fileExtension:"aac"})}static get ACSM(){return n.parse({mediaType:"application/vnd.adobe.adept+xml",name:"Adobe Content Server Message",fileExtension:"acsm"})}static get AIFF(){return n.parse({mediaType:"audio/aiff",fileExtension:"aiff"})}static get AVI(){return n.parse({mediaType:"video/x-msvideo",fileExtension:"avi"})}static get BINARY(){return n.parse({mediaType:"application/octet-stream"})}static get BMP(){return n.parse({mediaType:"image/bmp",fileExtension:"bmp"})}static get CBZ(){return n.parse({mediaType:"application/vnd.comicbook+zip",name:"Comic Book Archive",fileExtension:"cbz"})}static get CSS(){return n.parse({mediaType:"text/css",fileExtension:"css"})}static get DIVINA(){return n.parse({mediaType:"application/divina+zip",name:"Digital Visual Narratives",fileExtension:"divina"})}static get DIVINA_MANIFEST(){return n.parse({mediaType:"application/divina+json",name:"Digital Visual Narratives",fileExtension:"json"})}static get EPUB(){return n.parse({mediaType:"application/epub+zip",name:"EPUB",fileExtension:"epub"})}static get GIF(){return n.parse({mediaType:"image/gif",fileExtension:"gif"})}static get GZ(){return n.parse({mediaType:"application/gzip",fileExtension:"gz"})}static get HTML(){return n.parse({mediaType:"text/html",fileExtension:"html"})}static get JAVASCRIPT(){return n.parse({mediaType:"text/javascript",fileExtension:"js"})}static get JPEG(){return n.parse({mediaType:"image/jpeg",fileExtension:"jpeg"})}static get JSON(){return n.parse({mediaType:"application/json"})}static get LCP_LICENSE_DOCUMENT(){return n.parse({mediaType:"application/vnd.readium.lcp.license.v1.0+json",name:"LCP License",fileExtension:"lcpl"})}static get LCP_PROTECTED_AUDIOBOOK(){return n.parse({mediaType:"application/audiobook+lcp",name:"LCP Protected Audiobook",fileExtension:"lcpa"})}static get LCP_PROTECTED_PDF(){return n.parse({mediaType:"application/pdf+lcp",name:"LCP Protected PDF",fileExtension:"lcpdf"})}static get LCP_STATUS_DOCUMENT(){return n.parse({mediaType:"application/vnd.readium.license.status.v1.0+json"})}static get LPF(){return n.parse({mediaType:"application/lpf+zip",fileExtension:"lpf"})}static get MP3(){return n.parse({mediaType:"audio/mpeg",fileExtension:"mp3"})}static get MPEG(){return n.parse({mediaType:"video/mpeg",fileExtension:"mpeg"})}static get NCX(){return n.parse({mediaType:"application/x-dtbncx+xml",fileExtension:"ncx"})}static get OGG(){return n.parse({mediaType:"audio/ogg",fileExtension:"oga"})}static get OGV(){return n.parse({mediaType:"video/ogg",fileExtension:"ogv"})}static get OPDS1(){return n.parse({mediaType:"application/atom+xml;profile=opds-catalog"})}static get OPDS1_ENTRY(){return n.parse({mediaType:"application/atom+xml;type=entry;profile=opds-catalog"})}static get OPDS2(){return n.parse({mediaType:"application/opds+json"})}static get OPDS2_PUBLICATION(){return n.parse({mediaType:"application/opds-publication+json"})}static get OPDS_AUTHENTICATION(){return n.parse({mediaType:"application/opds-authentication+json"})}static get OPUS(){return n.parse({mediaType:"audio/opus",fileExtension:"opus"})}static get OTF(){return n.parse({mediaType:"font/otf",fileExtension:"otf"})}static get PDF(){return n.parse({mediaType:"application/pdf",name:"PDF",fileExtension:"pdf"})}static get PNG(){return n.parse({mediaType:"image/png",fileExtension:"png"})}static get READIUM_AUDIOBOOK(){return n.parse({mediaType:"application/audiobook+zip",name:"Readium Audiobook",fileExtension:"audiobook"})}static get READIUM_AUDIOBOOK_MANIFEST(){return n.parse({mediaType:"application/audiobook+json",name:"Readium Audiobook",fileExtension:"json"})}static get READIUM_CONTENT_DOCUMENT(){return n.parse({mediaType:"application/vnd.readium.content+json",name:"Readium Content Document",fileExtension:"json"})}static get READIUM_GUIDED_NAVIGATION_DOCUMENT(){return n.parse({mediaType:"application/guided-navigation+json",name:"Readium Guided Navigation Document",fileExtension:"json"})}static get READIUM_POSITION_LIST(){return n.parse({mediaType:"application/vnd.readium.position-list+json",name:"Readium Position List",fileExtension:"json"})}static get READIUM_WEBPUB(){return n.parse({mediaType:"application/webpub+zip",name:"Readium Web Publication",fileExtension:"webpub"})}static get READIUM_WEBPUB_MANIFEST(){return n.parse({mediaType:"application/webpub+json",name:"Readium Web Publication",fileExtension:"json"})}static get SMIL(){return n.parse({mediaType:"application/smil+xml",fileExtension:"smil"})}static get SVG(){return n.parse({mediaType:"image/svg+xml",fileExtension:"svg"})}static get TEXT(){return n.parse({mediaType:"text/plain",fileExtension:"txt"})}static get TIFF(){return n.parse({mediaType:"image/tiff",fileExtension:"tiff"})}static get TTF(){return n.parse({mediaType:"font/ttf",fileExtension:"ttf"})}static get W3C_WPUB_MANIFEST(){return n.parse({mediaType:"application/x.readium.w3c.wpub+json",name:"Web Publication",fileExtension:"json"})}static get WAV(){return n.parse({mediaType:"audio/wav",fileExtension:"wav"})}static get WEBM_AUDIO(){return n.parse({mediaType:"audio/webm",fileExtension:"webm"})}static get WEBM_VIDEO(){return n.parse({mediaType:"video/webm",fileExtension:"webm"})}static get WEBP(){return n.parse({mediaType:"image/webp",fileExtension:"webp"})}static get WOFF(){return n.parse({mediaType:"font/woff",fileExtension:"woff"})}static get WOFF2(){return n.parse({mediaType:"font/woff2",fileExtension:"woff2"})}static get XHTML(){return n.parse({mediaType:"application/xhtml+xml",fileExtension:"xhtml"})}static get XML(){return n.parse({mediaType:"application/xml",fileExtension:"xml"})}static get ZAB(){return n.parse({mediaType:"application/x.readium.zab+zip",name:"Zipped Audio Book",fileExtension:"zab"})}static get ZIP(){return n.parse({mediaType:"application/zip",fileExtension:"zip"})}}class B{constructor(t){this.uri=t,this.parameters=this.getParameters(t)}getParameters(t){const e=/\{\??([^}]+)\}/g,i=t.match(e);return i?new Set(i.join(",").replace(e,"$1").split(",").map(s=>s.trim())):new Set}expand(t){const e=s=>s.split(",").map(a=>{const l=t[a];return l?encodeURIComponent(l):""}).join(","),i=s=>"?"+s.split(",").map(a=>{const l=a.split("=")[0],h=t[l];return h?`${l}=${encodeURIComponent(h)}`:""}).join("&");return this.uri.replace(/\{(\??)([^}]+)\}/g,(...s)=>s[1]?i(s[2]):e(s[2]))}}function zt(r){return r&&r instanceof Array?r:void 0}function I(r){return r&&typeof r=="string"?[r]:zt(r)}function F(r){return typeof r=="string"?new Date(r):void 0}function k(r){return isNaN(r)?void 0:r}function y(r){return k(r)!==void 0&&Math.sign(r)>=0?r:void 0}function q(r){const t=new Array;return r.forEach(e=>t.push(e)),t}class b{constructor(t){this.fragments=t.fragments?t.fragments:new Array,this.progression=t.progression,this.totalProgression=t.totalProgression,this.position=t.position,this.otherLocations=t.otherLocations}static deserialize(t){if(!t)return;const e=k(t.progression),i=k(t.totalProgression),s=k(t.position),a=new Map,l=new Set(["fragment","fragments","progression","totalProgression","position"]);return Object.entries(t).forEach(([h,c])=>{l.has(h)||a.set(h,c)}),new b({fragments:I(t.fragments||t.fragment),progression:e!==void 0&&e>=0&&e<=1?e:void 0,totalProgression:i!==void 0&&i>=0&&i<=1?i:void 0,position:s!==void 0&&s>0?s:void 0,otherLocations:a.size===0?void 0:a})}serialize(){const t={};return this.fragments&&(t.fragments=this.fragments),this.progression!==void 0&&(t.progression=this.progression),this.totalProgression!==void 0&&(t.totalProgression=this.totalProgression),this.position!==void 0&&(t.position=this.position),this.otherLocations&&this.otherLocations.forEach((e,i)=>t[i]=e),t}}class K{constructor(t){this.after=t.after,this.before=t.before,this.highlight=t.highlight}static deserialize(t){if(t)return new K({after:t.after,before:t.before,highlight:t.highlight})}serialize(){const t={};return this.after!==void 0&&(t.after=this.after),this.before!==void 0&&(t.before=this.before),this.highlight!==void 0&&(t.highlight=this.highlight),t}}class S{constructor(t){this.href=t.href,this.type=t.type,this.title=t.title,this.locations=t.locations?t.locations:new b({}),this.text=t.text}static deserialize(t){if(t&&t.href&&t.type)return new S({href:t.href,type:t.type,title:t.title,locations:b.deserialize(t.locations),text:K.deserialize(t.text)})}serialize(){const t={href:this.href,type:this.type};return this.title!==void 0&&(t.title=this.title),this.locations&&(t.locations=this.locations.serialize()),this.text&&(t.text=this.text.serialize()),t}copyWithLocations(t){return new S({href:this.href,type:this.type,title:this.title,text:this.text,locations:new b({...this.locations,...t})})}}class A{constructor(t){this.href=t.href,this.templated=t.templated,this.type=t.type,this.title=t.title,this.rels=t.rels,this.properties=t.properties,this.height=t.height,this.width=t.width,this.duration=t.duration,this.bitrate=t.bitrate,this.languages=t.languages,this.alternates=t.alternates,this.children=t.children}static deserialize(t){if(t&&t.href&&typeof t.href=="string")return new A({href:t.href,templated:t.templated,type:t.type,title:t.title,rels:t.rel?t.rel instanceof Array?new Set(t.rel):new Set([t.rel]):void 0,properties:g.deserialize(t.properties),height:y(t.height),width:y(t.width),duration:y(t.duration),bitrate:y(t.bitrate),languages:I(t.language),alternates:v.deserialize(t.alternate),children:v.deserialize(t.children)})}serialize(){const t={href:this.href};return this.templated!==void 0&&(t.templated=this.templated),this.type!==void 0&&(t.type=this.type),this.title!==void 0&&(t.title=this.title),this.rels&&(t.rel=q(this.rels)),this.properties&&(t.properties=this.properties.serialize()),this.height!==void 0&&(t.height=this.height),this.width!==void 0&&(t.width=this.width),this.duration!==void 0&&(t.duration=this.duration),this.bitrate!==void 0&&(t.bitrate=this.bitrate),this.languages&&(t.language=this.languages),this.alternates&&(t.alternate=this.alternates.serialize()),this.children&&(t.children=this.children.serialize()),t}get mediaType(){return this.type!==void 0?n.parse({mediaType:this.type}):n.BINARY}toURL(t){const e=this.href.replace(/^(\/)/,"");if(e.length===0)return;let i=t||"/";return i.startsWith("/")&&(i="file://"+i),new URL(e,i).href.replace(/^(file:\/\/)/,"")}get templateParameters(){return this.templated?new B(this.href).parameters:new Set}expandTemplate(t){return new A({href:new B(this.href).expand(t),templated:!1})}addProperties(t){var i;const e=A.deserialize(this.serialize());return e.properties=e.properties?(i=e.properties)==null?void 0:i.add(t):new g(t),e}get locator(){let t=this.href.split("#");return new S({href:t.length>0&&t[0]!==void 0?t[0]:this.href,type:this.type??"",title:this.title,locations:new b({fragments:t.length>1&&t[1]!==void 0?[t[1]]:[]})})}}class v{constructor(t){this.items=t}static deserialize(t){if(t&&t instanceof Array)return new v(t.map(e=>A.deserialize(e)).filter(e=>e!==void 0))}serialize(){return this.items.map(t=>t.serialize())}findWithRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.find(e)}filterByRel(t){const e=i=>i.rels&&i.rels.has(t);return this.items.filter(e)}findWithHref(t){const e=i=>i.href===t;return this.items.find(e)}findIndexWithHref(t){const e=i=>i.href===t;return this.items.findIndex(e)}findWithMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.find(e)}filterByMediaType(t){const e=i=>i.mediaType.matches(t);return this.items.filter(e)}filterByMediaTypes(t){const e=i=>{for(const s of t)if(i.mediaType.matches(s))return!0;return!1};return this.items.filter(e)}everyIsAudio(){const t=e=>e.mediaType.isAudio;return this.items.length>0&&this.items.every(t)}everyIsBitmap(){const t=e=>e.mediaType.isBitmap;return this.items.length>0&&this.items.every(t)}everyIsHTML(){const t=e=>e.mediaType.isHTML;return this.items.length>0&&this.items.every(t)}everyIsVideo(){const t=e=>e.mediaType.isVideo;return this.items.length>0&&this.items.every(t)}everyMatchesMediaType(t){return Array.isArray(t)?this.items.length>0&&this.items.every(e=>{for(const i of t)return e.mediaType.matches(i);return!1}):this.items.length>0&&this.items.every(e=>e.mediaType.matches(t))}filterLinksHasType(){return this.items.filter(t=>t.type)}}class X{constructor(t){this.links=t.links,this.guided=t.guided}static deserialize(t){if(t)return new X({links:v.deserialize(t.links),guided:L.deserializeArray(t.guided)})}serialize(){const t={};return this.links!==void 0&&(t.links=this.links.serialize()),this.guided!==void 0&&(t.guided=this.guided.map(e=>e.serialize())),t}}class L{constructor(t){this.audioref=t.audioref,this.children=t.children,this.imgref=t.imgref,this.role=t.role,this.text=t.text,this.textref=t.textref}static deserialize(t){if(t)return new L({audioref:t.audioref,children:L.deserializeArray(t.children),imgref:t.imgref,role:t.role?new Set(I(t.role)):void 0,text:t.text,textref:t.textref})}static deserializeArray(t){if(t instanceof Array)return t.map(e=>L.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={};return this.audioref!==void 0&&(t.audioref=this.audioref),this.children!==void 0&&(t.children=this.children.map(e=>e.serialize())),this.imgref!==void 0&&(t.imgref=this.imgref),this.role!==void 0&&(t.role=q(this.role)),this.text!==void 0&&(t.text=this.text),this.textref!==void 0&&(t.textref=this.textref),t}get audioFile(){var t;return(t=this.audioref)==null?void 0:t.split("#")[0]}get audioTime(){var t;if((t=this.audioref)!=null&&t.includes("#"))return this.audioref.split("#",2)[1]}get textFile(){var t;return(t=this.textref)==null?void 0:t.split("#")[0]}get fragmentId(){var t;if((t=this.textref)!=null&&t.includes("#"))return this.textref.split("#",2)[1]}get clip(){const t=this.audioFile;if(!t)return;const e=this.audioTime,i={audioResource:t,fragmentId:this.fragmentId};if(!e)return i;const s=this.parseTimer(e);return i.start=s[0],i.end=s[1],i}parseTimer(t){if(!t||!t.startsWith("t="))return[void 0,void 0];const e=t.substring(2).split(",").map(i=>parseFloat(i));return e.length===1?[isNaN(e[0])?void 0:e[0],void 0]:e.length>2?[void 0,void 0]:[isNaN(e[0])?void 0:e[0],isNaN(e[1])?void 0:e[1]]}}function xt(r,t){return t.length>1?t.indexOf(r.slice(-1))>-1:r.slice(-1)===t}function Tt(r,t){return r.slice(r.length-t.length)===t}const st={endsWith:Tt,endsWithChar:xt},It=["ie","eg","ext","Fig","fig","Figs","figs","et al","Co","Corp","Ave","Inc","Ex","Viz","vs","Vs","repr","Rep","Dem","trans","Vol","pp","rev","est","Ref","Refs","Eq","Eqs","Ch","Sec","Secs","mi","Dept","Univ","Nos","No","Mol","Cell","Miss","Mrs","Mr","Ms","Prof","Dr","Sgt","Col","Gen","Rep","Sen","Gov","Lt","Maj","Capt","St","Sr","Jr","jr","Rev","PhD","MD","BA","MA","MM","BSc","MSc","Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Sept","Oct","Nov","Dec","Sun","Mon","Tu","Tue","Tues","Wed","Th","Thu","Thur","Thurs","Fri","Sat"];function yt(r){return/^[A-Z][a-z].*/.test(r)||nt(r)}function kt(r){return yt(r)||/``|"|'/.test(r.substring(0,2))}function Nt(r){return~It.indexOf(r.replace(/\W+/g,""))}function Lt(r,t){if(r==="a.m."||r==="p.m."){var e=t.replace(/\W+/g,"").slice(-3).toLowerCase();if(e==="day")return!0}return!1}function bt(r){var t=r.replace(/[\(\)\[\]\{\}]/g,"").match(/(.\.)*/);return t&&t[0].length>0}function vt(r){return r.length<=3?!0:yt(r)}function nt(r,t){return t&&(r=r.slice(t-1,t+2)),!isNaN(Number(r))}function Ct(r){return r.match(/^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/)}function Rt(r){return r.match(/[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/)}function Dt(r){var t=0;if((t=r.indexOf("."))>-1||(t=r.indexOf("!"))>-1||(t=r.indexOf("?"))>-1){var e=r.charAt(t+1);if(e.match(/[a-zA-Z].*/))return[r.slice(0,t),r.charAt(t),r.slice(t+1)]}return!1}function Ut(r){return r==="."||r==="!"||r==="?"}function Wt(r,t){t=Object.assign(t||{},{newlineBoundary:t&&t.newlineBoundary||!0});var e=/\s/;return r.serie(r.re(e,{split:!0}),r.splitAndMerge(function(i,s,a,l,h,c){var p,u=[i,null],d=i,f=c.slice(h+1).find(function(T){return!e.test(T.value)});if(i===`
|
|
2
|
+
`&&t.newlineBoundary||Ut(i)||st.endsWithChar(i,"?!"))return u;if(st.endsWithChar(i,".")){if(f){if(i.length===2&&isNaN(i.charAt(0))&&i.match(/[a-zA-Z]/)||Nt(i))return d;if(kt(f.value)){if(Lt(i,f.value)||nt(f.value)&&vt(i))return d}else if(st.endsWith(i,"..")||bt(i)||vt(i))return d}return u}let m;return(m=i.indexOf("."))>-1&&(nt(i,m)||bt(i)||Rt(i)||Ct(i))?d:(p=Dt(i))?[p[0]+p[1],null,p[2]]:d}),r.filter(function(i){return i.trim()!=""}))}const Bt=(r,...t)=>(...e)=>r(...t,...e);function Ft(r){return{sentences:Bt(Wt,r)}}function Gt(r,t){return t?r.reduce(function(e,i){var s=[i.index,i.offset,i.value].join("-");return[e,s].join(":")},t):null}function Ht(r){const{index:t,offset:e,value:i,...s}=r;return s}function $t(r,t){var e=0;return Array.isArray(t)||(t=[t]),t.map(function(i){return i===null?null:(typeof i=="string"&&(i={value:i,index:e,offset:i.length}),typeof i=="object"&&(i.index=i.index||0,e=e+i.index+i.offset,i.index=r.index+i.index,i.offset=i.offset||i.value.length),i)})}function Vt(r,t){var a;if(r.length==0)return null;var e="",i=0,s=(a=r[0])==null?void 0:a.index;return r.forEach(function(l,h){var c=r[h-1];r[h+1];var p=c?l.index+1-(c.index+c.offset):0;e=e+new Array(p).join(t)+l.value;var u=l.index-s+l.offset;u>i&&(i=u)}),{index:s,value:e,offset:Math.max(i,e.length)}}const G={tokensId:Gt,normalize:$t,properties:Ht,merge:Vt};var Jt=' \r\n !"#$%&()*+,-.\\/:;<=>?@[\\]^_`{|}~',Zt=new RegExp("([^"+Jt+"]+)");function E(r){if(!(this instanceof E))return new E(r);this.opts=Object.assign({cacheGet:function(t){return null},cacheSet:function(t,e){}},r)}E.prototype.split=function(t,e={}){var i=this;return e=Object.assign({preserveProperties:!0,cache:()=>null},e),function(s,a){if(arguments.length===6)return t.apply(null,arguments);var l,h,c;if(s===void 0)return[];if(typeof s=="string"?s=[{value:s,index:0,offset:s.length}]:Array.isArray(s)||(s=[s]),h=G.tokensId(s,e.cache()),h&&(c=i.opts.cacheGet(h),c))return c;var p=s.map(function(u,d){var f=s[d+1],m=t(u.value,Object.assign({},u),l?Object.assign({},l):null,f?Object.assign({},f):null,d,s)||[];if(m=G.normalize(u,m),e.preserveProperties){var T=G.properties(u);m=m.map(function(Z){return Object.assign({},Z,T)})}return l=u,m}).filter(Boolean).flat();return h&&i.opts.cacheSet(h,p),p}},E.prototype.re=function(t,e={}){return e=Object.assign({split:!1},e),this.split(function(i,s){for(var a=i,l=[],h,c=0;h=t.exec(i);){var p=h.index,u=c+p,d=h[0]||"",f=d.length;if(e.split&&c<u){var m=a.slice(c,u);l.push({value:m,index:c,offset:m.length})}l.push({value:d,index:u,offset:f,match:h}),i=i.slice(p+f),c=u+f}return e.split&&i&&l.push({value:i,index:c,offset:i.length}),l},{cache:function(){return t.toString()}})},E.prototype.splitAndMerge=function(t,e={}){var i=this;return e=Object.assign({mergeWith:""},e),function(s){var a=[],l=[];function h(){if(l.length!=0){var c=G.merge(l,e.mergeWith);a.push(c),l=[]}}return i.split(function(c,p){var u=t.apply(null,arguments);u=G.normalize(p,u),u.forEach(function(d){d===null?h():l.push(d)})})(s),h(),a}},E.prototype.filter=function(t){return this.split(function(e,i){if(t.apply(null,arguments))return{value:i.value,index:0,offset:i.offset}})},E.prototype.extend=function(t){return this.split(function(e,i){var s=typeof t=="function"?t.apply(null,arguments):t;return Object.assign({value:i.value,index:0,offset:i.offset},s)})},E.prototype.ifthen=function(r,t){return this.split(function(e,i){if(r.apply(null,arguments))return t.apply(null,arguments);const{index:s,...a}=i;return a})},E.prototype.test=function(t){return this.filter(function(e,i){return t.test(e)},{cache:t.toString()})},E.prototype.flow=function(...t){const e=t.reduce((i,s)=>(...a)=>s(i(...a)));return this.split(e)},E.prototype.serie=function(...t){return t.reduce((e,i)=>(...s)=>i(e(...s)))},E.prototype.merge=function(){return this.splitAndMerge(r=>[r])},E.prototype.sections=function(){return this.re(/([^\n\.,;!?]+)/i,{split:!1})},E.prototype.words=function(){return this.re(Zt)},E.prototype.characters=function(){return this.re(/[^\s]/)};var Et=(r=>(r.Word="word",r.Sentence="sentence",r.Paragraph="paragraph",r))(Et||{});const Mt=(r,t)=>"Segmenter"in Intl?new At(r,t):new wt(r,t);class At{constructor(t,e){if(this.unit=e,t=t??(navigator==null?void 0:navigator.language),!("Segmenter"in Intl))throw new Error("Intl.Segmenter is not supported in this environment");if(e==="paragraph")throw new Error("IntlTextTokenizer does not handle TextUnit.Paragraph");this.segmenter=new Intl.Segmenter(t,{granularity:e})}tokenize(t){const e=this.segmenter.segment(t),i=[];for(let s of e){if(this.unit==="word"&&s.isWordLike===!1)continue;const a=at(s.segment);a!==null&&i.push([s.index,s.index+a.length])}return i}}class wt{constructor(t,e){if(this.unit=e,t=t??(navigator==null?void 0:navigator.language),this.isEnglish=t.toLowerCase().split("-")[0]==="en",e==="paragraph")throw new Error("NaiveTextTokenizer does not handle TextUnit.Paragraph");this.tokenizer=new E}tokenize(t){let e=[];switch(this.unit){case"word":e=this.tokenizer.words()(t);break;case"sentence":this.isEnglish?e=Ft(this.tokenizer).sentences()(t):e=this.tokenizer.sections()(t);break;default:e=[]}if(!e)return[];const i=[];return e.forEach(s=>{if(s.value.length===0)return;const a=at(s.value);a!==null&&i.push([s.index,s.index+a.length])}),i}}const qt=new RegExp("[\\p{L}\\p{N}]+","u"),at=r=>{const t=r.trimEnd();return t.length===0||t.match(qt)===null?null:t};class x{constructor(t){this.fetcher=new N,t.fetcher&&(this.fetcher=t.fetcher),this.manifest=t.manifest,this.context=t.manifest.context,this.metadata=t.manifest.metadata,this.links=t.manifest.links,this.readingOrder=t.manifest.readingOrder,this.resources=t.manifest.resources,this.tableOfContents=t.manifest.tableOfContents,this.subcollections=t.manifest.subcollections}get baseURL(){return this.manifest.baseURL}linkWithHref(t){return this.manifest.linkWithHref(t)}linksWithRole(t){var i;const e=(i=this.subcollections)==null?void 0:i.get(t);return e&&e.length>0?e[0].links:void 0}linksWithRel(t){return this.manifest.linksWithRel(t)}linkWithRel(t){return this.manifest.linkWithRel(t)}async positionsFromManifest(){const t=this.manifest.links.findWithMediaType("application/vnd.readium.position-list+json");if(t===void 0)return[];const e=await this.get(t).readAsJSON();return e.total?e.positions.map(i=>S.deserialize(i)).filter(i=>i!==void 0):[]}async guideForLink(t){const e=l=>{var h;return(h=l.alternates)==null?void 0:h.findWithMediaType("application/guided-navigation+json")};let i=e(t);if(!i){const l=this.linkWithHref(t.href);l!==void 0&&(i=e(l))}if(i||(i=this.manifest.links.findWithMediaType("application/guided-navigation+json")),!i)return;let s=i.href;if(i.templated){const l=new B(s),h={};l.parameters.has("ref")&&(h.ref=t.href),s=new B(s).expand(h)}const a=await this.get(new A({href:s})).readAsJSON();return X.deserialize(a)}get(t){return this.fetcher.get(t)}}x.prototype.getPageList=function(){return this.linksWithRole("pageList")},x.prototype.getLandmarks=function(){return this.linksWithRole("landmarks")},x.prototype.getListOfAudioClips=function(){return this.linksWithRole("loa")},x.prototype.getListOfIllustrations=function(){return this.linksWithRole("loi")},x.prototype.getListOfTables=function(){return this.linksWithRole("lot")},x.prototype.getListOfVideoClips=function(){return this.linksWithRole("lov")};class H{constructor(t){this.cssSelector=t.cssSelector,this.textNodeIndex=t.textNodeIndex,this.charOffset=t.charOffset}static deserialize(t){if(!(t&&t.cssSelector))return;let e=y(t.textNodeIndex);if(e===void 0)return;let i=y(t.charOffset);return i===void 0&&(i=y(t.offset)),new H({cssSelector:t.cssSelector,textNodeIndex:e,charOffset:i})}serialize(){const t={cssSelector:this.cssSelector,textNodeIndex:this.textNodeIndex};return this.charOffset!==void 0&&(t.charOffset=this.charOffset),t}}class Y{constructor(t){this.start=t.start,this.end=t.end}static deserialize(t){if(!t)return;let e=H.deserialize(t.start);if(e)return new Y({start:e,end:H.deserialize(t.end)})}serialize(){const t={start:this.start.serialize()};return this.end&&(t.end=this.end.serialize()),t}}b.prototype.getCssSelector=function(){var r;return(r=this.otherLocations)==null?void 0:r.get("cssSelector")},b.prototype.getPartialCfi=function(){var r;return(r=this.otherLocations)==null?void 0:r.get("partialCfi")},b.prototype.getDomRange=function(){var r;return Y.deserialize((r=this.otherLocations)==null?void 0:r.get("domRange"))},b.prototype.fragmentParameters=function(){return new Map(this.fragments.map(r=>r.startsWith("#")?r.slice(1):r).join("&").split("&").filter(r=>!r.startsWith("#")).map(r=>r.split("=")).filter(r=>r.length===2).map(r=>[r[0].trim().toLowerCase(),r[1].trim()]))},b.prototype.htmlId=function(){if(!this.fragments.length)return;let r=this.fragments.find(t=>t.length&&!t.includes("="));if(!r){const t=this.fragmentParameters();t.has("id")?r=t.get("id"):t.has("name")&&(r=t.get("name"))}return r!=null&&r.startsWith("#")?r.slice(1):r},b.prototype.page=function(){const r=parseInt(this.fragmentParameters().get("page"));if(!isNaN(r)&&r>=0)return r},b.prototype.time=function(){const r=parseInt(this.fragmentParameters().get("t"));if(!isNaN(r))return r},b.prototype.space=function(){const r=this.fragmentParameters();if(!r.has("xywh"))return;const t=r.get("xywh").split(",").map(e=>parseInt(e));if(t.length===4&&!t.some(isNaN))return t};class Q{constructor(t){this.currency=t.currency,this.value=t.value}static deserialize(t){if(!t)return;let e=t.currency;if(!(e&&typeof e=="string"&&e.length>0))return;let i=y(t.value);if(i!==void 0)return new Q({currency:e,value:i})}serialize(){return{currency:this.currency,value:this.value}}}class C{constructor(t){this.type=t.type,this.children=t.children}static deserialize(t){if(t&&t.type)return new C({type:t.type,children:C.deserializeArray(t.children)})}static deserializeArray(t){if(t instanceof Array)return t.map(e=>C.deserialize(e)).filter(e=>e!==void 0)}serialize(){const t={type:this.type};return this.children&&(t.children=this.children.map(e=>e.serialize())),t}}class _{constructor(t){this.total=t.total,this.position=t.position}static deserialize(t){if(t)return new _({total:y(t.total),position:y(t.position)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.position!==void 0&&(t.position=this.position),t}}class j{constructor(t){this.total=t.total,this.available=t.available}static deserialize(t){if(t)return new j({total:y(t.total),available:y(t.available)})}serialize(){const t={};return this.total!==void 0&&(t.total=this.total),this.available!==void 0&&(t.available=this.available),t}}var Ot=(r=>(r.available="available",r.reserved="reserved",r.ready="ready",r))(Ot||{});class tt{constructor(t){this.state=t.state,this.since=t.since,this.until=t.until}static deserialize(t){if(t&&t.state)return new tt({state:t.state,since:F(t.since),until:F(t.until)})}serialize(){const t={state:this.state};return this.since!==void 0&&(t.since=this.since.toISOString()),this.until!==void 0&&(t.until=this.until.toISOString()),t}}g.prototype.getNumberOfItems=function(){return y(this.otherProperties.numberOfItems)},g.prototype.getPrice=function(){return Q.deserialize(this.otherProperties.price)},g.prototype.getIndirectAcquisitions=function(){const r=this.otherProperties.indirectAcquisition;if(r&&r instanceof Array)return r.map(t=>C.deserialize(t)).filter(t=>t!==void 0)},g.prototype.getHolds=function(){return _.deserialize(this.otherProperties.holds)},g.prototype.getCopies=function(){return j.deserialize(this.otherProperties.copies)},g.prototype.getAvailability=function(){return tt.deserialize(this.otherProperties.availability)},g.prototype.getAuthenticate=function(){return A.deserialize(this.otherProperties.authenticate)},x.prototype.getImages=function(){return this.linksWithRole("images")};const ot=class D{constructor(t){this.translations=typeof t=="string"?{[D.UNDEFINED_LANGUAGE]:t}:t}static deserialize(t){if(t&&(typeof t=="string"||t.constructor===Object))return new D(t)}serialize(){return this.translations}getTranslation(t){return this.translations[t||D.UNDEFINED_LANGUAGE]||this.translations[D.UNDEFINED_LANGUAGE]||this.translations[D.LANGUAGE_EN]||(Object.values(this.translations).length===0?"":Object.values(this.translations)[0])}};ot.UNDEFINED_LANGUAGE="undefined",ot.LANGUAGE_EN="en";let w=ot;class ${constructor(t){this.name=t.name,this.sortAs=t.sortAs,this.identifier=t.identifier,this.roles=t.roles,this.links=t.links,this.position=t.position}static deserialize(t){if(t)return typeof t=="string"?new $({name:w.deserialize(t)}):t.name?new $({name:w.deserialize(t.name),sortAs:t.sortAs,identifier:t.identifier,roles:t.role?new Set(I(t.role)):void 0,links:v.deserialize(t.links),position:k(t.position)}):void 0}serialize(){const t={name:this.name.serialize()};return this.sortAs!==void 0&&(t.sortAs=this.sortAs),this.identifier!==void 0&&(t.identifier=this.identifier),this.roles&&(t.role=q(this.roles)),this.links&&(t.links=this.links.serialize()),this.position!==void 0&&(t.position=this.position),t}}class z{constructor(t){this.items=t}static deserialize(t){if(!t)return;const e=t instanceof Array?t:[t];return new z(e.map(i=>$.deserialize(i)).filter(i=>i!==void 0))}serialize(){return this.items.map(t=>t.serialize())}}class R{constructor(t){this.items=t&&t.items?t.items:new Map}static deserialize(t){if(!(t&&t instanceof Object))return;const e=new Map;return Object.entries(t).forEach(([i,s])=>{const a=z.deserialize(s);a&&a.items.length>0&&e.set(i,a)}),new R({items:e})}serialize(){const t={};return this.items.forEach((e,i)=>t[i]=e.serialize()),t}}var O=(r=>(r.auto="auto",r.btt="btt",r.ltr="ltr",r.rtl="rtl",r.ttb="ttb",r))(O||{});function Kt(r){switch(r){case"auto":case"ttb":case"ltr":return U.left;case"rtl":case"btt":return U.right;default:return U.left}}class V{constructor(t){this.name=t.name,this.sortAs=t.sortAs,this.code=t.code,this.scheme=t.scheme,this.links=t.links}static deserialize(t){if(t)return typeof t=="string"?new V({name:w.deserialize(t)}):t.name?new V({name:w.deserialize(t.name),sortAs:t.sortAs,code:t.code,scheme:t.scheme,links:v.deserialize(t.links)}):void 0}serialize(){const t={name:this.name.serialize()};return this.sortAs!==void 0&&(t.sortAs=this.sortAs),this.code!==void 0&&(t.code=this.code),this.scheme!==void 0&&(t.scheme=this.scheme),this.links&&(t.links=this.links.serialize()),t}}class et{constructor(t){this.items=t}static deserialize(t){if(!t)return;const e=t instanceof Array?t:[t];return new et(e.map(i=>V.deserialize(i)).filter(i=>i!==void 0))}serialize(){return this.items.map(t=>t.serialize())}}const Pt=class ft{constructor(t){this.title=t.title,this.typeUri=t.typeUri,this.identifier=t.identifier,this.subtitle=t.subtitle,this.sortAs=t.sortAs,this.artists=t.artists,this.authors=t.authors,this.colorists=t.colorists,this.contributors=t.contributors,this.editors=t.editors,this.illustrators=t.illustrators,this.inkers=t.inkers,this.letterers=t.letterers,this.narrators=t.narrators,this.pencilers=t.pencilers,this.translators=t.translators,this.languages=t.languages,this.description=t.description,this.publishers=t.publishers,this.imprints=t.imprints,this.published=t.published,this.modified=t.modified,this.subjects=t.subjects,this.belongsTo=t.belongsTo,this.belongsToCollections=t.belongsToCollections,this.belongsToSeries=t.belongsToSeries,this.belongsToCollections&&this.belongsToCollections.items.length>0&&(this.belongsTo||(this.belongsTo=new R),this.belongsTo.items.set("collection",this.belongsToCollections)),this.belongsToSeries&&this.belongsToSeries.items.length>0&&(this.belongsTo||(this.belongsTo=new R),this.belongsTo.items.set("series",this.belongsToSeries)),this.readingProgression=t.readingProgression,this.duration=t.duration,this.numberOfPages=t.numberOfPages,this.otherMetadata=t.otherMetadata}static deserialize(t){if(!(t&&t.title))return;const e=w.deserialize(t.title),i=t["@type"],s=t.identifier,a=w.deserialize(t.subtitle),l=w.deserialize(t.sortAs),h=z.deserialize(t.artist),c=z.deserialize(t.author),p=z.deserialize(t.colorist),u=z.deserialize(t.contributor),d=z.deserialize(t.editor),f=z.deserialize(t.illustrator),m=z.deserialize(t.inker),T=z.deserialize(t.letterer),Z=z.deserialize(t.narrator),Xt=z.deserialize(t.penciler),Yt=z.deserialize(t.translator),Qt=I(t.language),_t=t.description,jt=z.deserialize(t.publisher),te=z.deserialize(t.imprint),ee=F(t.published),ie=F(t.modified),re=et.deserialize(t.subject),se=R.deserialize(t.belongsTo),ne=t.readingProgression,ae=y(t.duration),oe=y(t.numberOfPages);let it=Object.assign({},t);return ft.mappedProperties.forEach(le=>delete it[le]),Object.keys(it).length===0&&(it=void 0),new ft({title:e,typeUri:i,identifier:s,subtitle:a,sortAs:l,artists:h,authors:c,colorists:p,contributors:u,editors:d,illustrators:f,inkers:m,letterers:T,narrators:Z,pencilers:Xt,translators:Yt,languages:Qt,description:_t,publishers:jt,imprints:te,published:ee,modified:ie,subjects:re,belongsTo:se,readingProgression:ne,duration:ae,numberOfPages:oe,otherMetadata:it})}serialize(){const t={title:this.title.serialize()};if(this.typeUri!==void 0&&(t["@type"]=this.typeUri),this.identifier!==void 0&&(t.identifier=this.identifier),this.subtitle&&(t.subtitle=this.subtitle.serialize()),this.sortAs&&(t.sortAs=this.sortAs.serialize()),this.editors&&(t.editor=this.editors.serialize()),this.artists&&(t.artist=this.artists.serialize()),this.authors&&(t.author=this.authors.serialize()),this.colorists&&(t.colorist=this.colorists.serialize()),this.contributors&&(t.contributor=this.contributors.serialize()),this.illustrators&&(t.illustrator=this.illustrators.serialize()),this.letterers&&(t.letterer=this.letterers.serialize()),this.narrators&&(t.narrator=this.narrators.serialize()),this.pencilers&&(t.penciler=this.pencilers.serialize()),this.translators&&(t.translator=this.translators.serialize()),this.inkers&&(t.inker=this.inkers.serialize()),this.languages&&(t.language=this.languages),this.description!==void 0&&(t.description=this.description),this.publishers&&(t.publisher=this.publishers.serialize()),this.imprints&&(t.imprint=this.imprints.serialize()),this.published!==void 0&&(t.published=this.published.toISOString()),this.modified!==void 0&&(t.modified=this.modified.toISOString()),this.subjects&&(t.subject=this.subjects.serialize()),this.belongsTo&&(t.belongsTo=this.belongsTo.serialize()),this.readingProgression&&(t.readingProgression=this.readingProgression),this.duration!==void 0&&(t.duration=this.duration),this.numberOfPages!==void 0&&(t.numberOfPages=this.numberOfPages),this.otherMetadata){const e=this.otherMetadata;Object.keys(e).forEach(i=>t[i]=e[i])}return t}get effectiveReadingProgression(){var i;if(this.readingProgression&&this.readingProgression!==O.auto)return this.readingProgression;if(((i=this.languages)==null?void 0:i.length)!==1)return O.ltr;const t=this.languages[0].toLowerCase();if(t==="zh-hant"||t==="zh-tw")return O.rtl;switch(t.split("-")[0]){case"ar":return O.rtl;case"fa":return O.rtl;case"he":return O.rtl;default:return O.ltr}}};Pt.mappedProperties=["title","@type","identifier","subtitle","sortAs","artist","author","colorist","contributor","editor","illustrator","inker","letterer","narrator","penciler","translator","language","description","publisher","imprint","published","modified","subject","belongsTo","readingProgression","duration","numberOfPages"];let lt=Pt;lt.prototype.getPresentation=function(){var t,e;const r=((t=this.otherMetadata)==null?void 0:t.presentation)||((e=this.otherMetadata)==null?void 0:e.rendition);if(r)return W.deserialize(r)},g.prototype.getClipped=function(){return this.otherProperties.clipped},g.prototype.getFit=function(){return this.otherProperties.fit},g.prototype.getOrientation=function(){return this.otherProperties.orientation},g.prototype.getOverflow=function(){return this.otherProperties.overflow},g.prototype.getPage=function(){return this.otherProperties.page||void 0},g.prototype.getSpread=function(){return this.otherProperties.spread||void 0};class J{constructor(t){this.title=t.title,this.numberOfItems=t.numberOfItems,this.otherMetadata=t.otherMetadata}static deserialize(t){if(!t)return;const e=new Map,i=new Set(["title","numberOfItems"]);return Object.entries(t).forEach(([s,a])=>{i.has(s)||e.set(s,a)}),new J({title:w.deserialize(t.title),numberOfItems:k(t.numberOfItems),otherMetadata:e.size===0?void 0:e})}serialize(){const t={};return this.title&&(t.title=this.title.serialize()),this.numberOfItems!==void 0&&(t.numberOfItems=this.numberOfItems),this.otherMetadata&&this.otherMetadata.forEach((e,i)=>t[i]=e),t}}class ht{constructor(t){this.metadata=t.metadata??new J({}),this.links=t.links??new v([]),this.locators=t.locators??[]}static deserialize(t){if(!t)return;let e,i=t.locators;return i&&i instanceof Array&&(e=i.map(s=>S.deserialize(s)).filter(s=>s!==void 0)),new ht({metadata:J.deserialize(t.metadata),links:v.deserialize(t.links),locators:e})}serialize(){const t={};if(this.metadata){let e=this.metadata.serialize();e&&Object.keys(e).length>0&&(t.metadata=e)}return this.links&&this.links.items.length>0&&(t.links=this.links.serialize()),this.locators&&(t.locators=this.locators.map(e=>e.serialize())),t}}class P{constructor(t){this.metadata=t.metadata,this.links=t.links,this.subcollections=t.subcollections}static deserialize(t){if(!t)return;let e,i,s;if(t instanceof Array)e=v.deserialize(t);else if(t instanceof Object)e=v.deserialize(t.links),i=new Map,t.metadata&&Object.entries(t.metadata).forEach(([a,l])=>{i==null||i.set(a,l)}),s=P.deserializeCollections(t);else return;if(!(!e||e.items.length===0))return new P({metadata:i!=null&&i.size?i:void 0,links:e,subcollections:s!=null&&s.size?s:void 0})}static deserializeCollections(t){if(!t)return;const e=new Map;return Object.entries(t).forEach(([i,s])=>{if(i!=="links"&&i!=="metadata"){const a=P.deserialize(s);if(a){const l=new Array;l.push(a),e.set(i,l)}else if(s instanceof Array){const l=s.map(h=>P.deserialize(h)).filter(h=>h!==void 0);e.set(i,l)}}}),e.size?e:void 0}serialize(){const t={};return this.metadata&&(t.metadata={},this.metadata.forEach((e,i)=>t.metadata[i]=e)),this.links.items.length&&(t.links=this.links.serialize()),P.serializeCollection(t,this.subcollections),t}static serializeCollection(t,e){e&&e.size>0&&e.forEach((i,s)=>{i.length===1?t[s]=i[0].serialize():t[s]=i.map(a=>a.serialize())})}}class ct{constructor(t){this.context=t.context,this.metadata=t.metadata,this.links=t.links,this.readingOrder=t.readingOrder,this.resources=t.resources,this.tableOfContents=t.tableOfContents,this.subcollections=t.subcollections}static deserialize(t){if(!t)return;const e=lt.deserialize(t.metadata);if(!e)return;const i=v.deserialize(t.links);if(!i)return;const s=v.deserialize(t.readingOrder?t.readingOrder:t.spine);if(s)return new ct({context:I(t["@context"]),metadata:e,links:i,readingOrder:s,resources:v.deserialize(t.resources),tableOfContents:v.deserialize(t.toc),subcollections:P.deserializeCollections({sub:t.sub})})}serialize(){const t={};return this.context!==void 0&&(t["@context"]=this.context),t.metadata=this.metadata.serialize(),t.links=this.links.serialize(),t.readingOrder=this.readingOrder.serialize(),this.resources&&(t.resources=this.resources.serialize()),this.tableOfContents&&(t.toc=this.tableOfContents.serialize()),P.serializeCollection(t,this.subcollections),t}linkWithRel(t){const e=new Array;e.push(this.readingOrder),this.resources&&e.push(this.resources),e.push(this.links);let i;for(const s of e)if(i=s.findWithRel(t),i!==void 0)return i;return i}linksWithRel(t){const e=[];return e.push(this.readingOrder.filterByRel(t)),this.resources&&e.push(this.resources.filterByRel(t)),e.push(this.links.filterByRel(t)),e.reduce((i,s)=>i.concat(s),[])}locatorFromLink(t){const e=t.href.split("#"),i=e.length==2?e[0]:t.href,s=this.linkWithHref(i);if(!s)return;const a=s.type;if(!a)return;const l=e.length==2?e[1]:void 0;return new S({href:i,type:a,title:s.title??t.title,locations:new b({fragments:l?[l]:void 0,progression:l?void 0:0})})}linkWithHref(t){const e=h=>{let c;for(const u of h)if(c=u.findWithHref(t),c!==void 0)return c;const p=new Array;return h.forEach(u=>{const d=[];for(const f of u.items)f.alternates&&d.push(f.alternates),f.children&&d.push(f.children);p.push(...d)}),p.length>0&&(c=e(p)),c},i=[];i.push(this.readingOrder),this.resources&&i.push(this.resources),i.push(this.links);const s=e(i);if(s!==void 0)return s;const a=t.split(/[#]/);if(a.length<2)return;const l=a[0];return this.linkWithHref(l)}get baseURL(){const t=this.links.items.find(e=>e.rels&&e.rels.has("self"));if(t){let e=t.href;if(e){const i=e.lastIndexOf("/"),s=i===-1?void 0:e.substring(i+1);e=e.replace(new RegExp("/?$query$"),""),e=e.replace(new RegExp("//$"),""),s&&(e=e.replace(new RegExp(s+"$"),""))}return e}}setSelfLink(t){this.links.items=this.links.items.filter(e=>{var i;return e.rels===void 0||!((i=e.rels)!=null&&i.has("self"))}),this.links.items.push(new A({href:t,type:n.READIUM_WEBPUB_MANIFEST.string,rels:new Set(["self"])}))}}o.Acquisition=C,o.Availability=tt,o.AvailabilityStatus=Ot,o.BelongsTo=R,o.Contributor=$,o.Contributors=z,o.Copies=j,o.DefaultTextContentTokenizer=Mt,o.DomRange=Y,o.DomRangePoint=H,o.EPUBLayout=rt,o.EmptyFetcher=N,o.Encryption=M,o.Fit=mt,o.GuidedNavigationDocument=X,o.GuidedNavigationObject=L,o.Holds=_,o.HttpFetcher=St,o.HttpResource=ut,o.IntlTextTokenizer=At,o.Link=A,o.Links=v,o.LocalizedString=w,o.Locator=S,o.LocatorCollection=ht,o.LocatorCollectionMetadata=J,o.LocatorLocations=b,o.LocatorText=K,o.Manifest=ct,o.MediaType=n,o.Metadata=lt,o.NaiveTextTokenizer=wt,o.Orientation=dt,o.Overflow=pt,o.Page=U,o.Presentation=W,o.Price=Q,o.Properties=g,o.Publication=x,o.PublicationCollection=P,o.ReadingProgression=O,o.Spread=gt,o.Subject=V,o.Subjects=et,o.TextUnit=Et,o.URITemplate=B,o.arrayfromJSON=zt,o.arrayfromJSONorString=I,o.datefromJSON=F,o.leadingPage=Kt,o.numberfromJSON=k,o.positiveNumberfromJSON=y,o.setToArray=q,o.speakableToken=at,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@readium/shared",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Shared models to be used across other Readium projects and implementations in Typescript",
|
|
6
|
+
"author": "readium",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/readium/ts-toolkit.git",
|
|
10
|
+
"directory": "shared"
|
|
11
|
+
},
|
|
12
|
+
"license": "BSD-3-Clause",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/readium/ts-toolkit/issues"
|
|
15
|
+
},
|
|
16
|
+
"homepage": "https://github.com/readium/ts-toolkit",
|
|
17
|
+
"keywords": [
|
|
18
|
+
"readium",
|
|
19
|
+
"epub",
|
|
20
|
+
"webpub",
|
|
21
|
+
"divina",
|
|
22
|
+
"reflowable",
|
|
23
|
+
"fixed-layout",
|
|
24
|
+
"publication",
|
|
25
|
+
"ebook",
|
|
26
|
+
"parser",
|
|
27
|
+
"tts"
|
|
28
|
+
],
|
|
29
|
+
"main": "./dist/index.umd.cjs",
|
|
30
|
+
"module": "./dist/index.js",
|
|
31
|
+
"types": "./types/src/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"import": "./dist/index.js",
|
|
35
|
+
"require": "./dist/index.umd.cjs",
|
|
36
|
+
"types": "./types/src/index.d.ts"
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"dist",
|
|
41
|
+
"src",
|
|
42
|
+
"types"
|
|
43
|
+
],
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=18"
|
|
46
|
+
},
|
|
47
|
+
"size-limit": [
|
|
48
|
+
{
|
|
49
|
+
"path": "dist/index.js",
|
|
50
|
+
"limit": "50 KB"
|
|
51
|
+
}
|
|
52
|
+
],
|
|
53
|
+
"devDependencies": {
|
|
54
|
+
"@babel/core": "^7.25.2",
|
|
55
|
+
"@babel/preset-env": "^7.25.4",
|
|
56
|
+
"@babel/preset-typescript": "^7.22.5",
|
|
57
|
+
"@size-limit/file": "^11.1.4",
|
|
58
|
+
"@types/jest": "^27.5.2",
|
|
59
|
+
"babel-jest": "^28.1.3",
|
|
60
|
+
"css-selector-generator": "^3.6.4",
|
|
61
|
+
"jest": "^29.7.0",
|
|
62
|
+
"size-limit": "^11.1.4",
|
|
63
|
+
"tslib": "^2.6.2",
|
|
64
|
+
"typescript": "^5.4.5",
|
|
65
|
+
"vite": "^4.4.9"
|
|
66
|
+
},
|
|
67
|
+
"scripts": {
|
|
68
|
+
"dev": "vite",
|
|
69
|
+
"build": "tsc && vite build",
|
|
70
|
+
"test": "jest",
|
|
71
|
+
"size": "size-limit"
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Link } from '../publication/Link';
|
|
2
|
+
import { Resource } from './Resource';
|
|
3
|
+
|
|
4
|
+
/** Provides access to a [Resource] from a [Link]. */
|
|
5
|
+
export interface Fetcher {
|
|
6
|
+
/**
|
|
7
|
+
* Known resources available in the medium, such as file paths on the file system
|
|
8
|
+
* or entries in a ZIP archive. This list is not exhaustive, and additional
|
|
9
|
+
* unknown resources might be reachable.
|
|
10
|
+
*
|
|
11
|
+
* If the medium has an inherent resource order, it should be followed.
|
|
12
|
+
* Otherwise, HREFs are sorted alphabetically.
|
|
13
|
+
*/
|
|
14
|
+
links(): Link[];
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Returns the [Resource] at the given [link]'s HREF.
|
|
18
|
+
*
|
|
19
|
+
* A [Resource] is always returned, since for some cases we can't know if it exists before
|
|
20
|
+
* actually fetching it, such as HTTP. Therefore, errors are handled at the Resource level.
|
|
21
|
+
*/
|
|
22
|
+
get(link: Link): Resource;
|
|
23
|
+
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class EmptyFetcher implements Fetcher {
|
|
28
|
+
close() {}
|
|
29
|
+
|
|
30
|
+
links(): Link[] {
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
get(_link: Link): Resource {
|
|
35
|
+
throw Error('This is an empty fetcher'); // TODO FailureResource
|
|
36
|
+
}
|
|
37
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { Link } from '../publication/Link';
|
|
2
|
+
import { Fetcher } from './Fetcher';
|
|
3
|
+
import { NumberRange, Resource } from './Resource';
|
|
4
|
+
|
|
5
|
+
export type FetchImplementation = (
|
|
6
|
+
input: RequestInfo | URL,
|
|
7
|
+
init?: RequestInit | undefined
|
|
8
|
+
) => Promise<Response>;
|
|
9
|
+
|
|
10
|
+
// Fetches remote resources through HTTP.
|
|
11
|
+
export class HttpFetcher implements Fetcher {
|
|
12
|
+
private readonly baseUrl?: string;
|
|
13
|
+
private readonly client: FetchImplementation;
|
|
14
|
+
|
|
15
|
+
constructor(client?: FetchImplementation, baseUrl?: string) {
|
|
16
|
+
this.client = client || window.fetch.bind(window);
|
|
17
|
+
this.baseUrl = baseUrl;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
links(): Link[] {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get(link: Link): Resource {
|
|
25
|
+
const url = link.toURL(this.baseUrl);
|
|
26
|
+
if (url === undefined) {
|
|
27
|
+
// TODO FailureResource
|
|
28
|
+
throw Error(`Invalid HREF: ${link.href}`);
|
|
29
|
+
}
|
|
30
|
+
return new HttpResource(this.client, link, url);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
close() {
|
|
34
|
+
// Nada
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export class HttpResource implements Resource {
|
|
39
|
+
private readonly _link: Link; // "link" conflicts with inteface function
|
|
40
|
+
private readonly url: string;
|
|
41
|
+
private readonly client: FetchImplementation;
|
|
42
|
+
private _headResponse?: Response;
|
|
43
|
+
|
|
44
|
+
constructor(client: FetchImplementation, link: Link, url: string) {
|
|
45
|
+
this.client = client || window.fetch.bind(window);
|
|
46
|
+
this._link = link;
|
|
47
|
+
this.url = url;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Cached HEAD response to get the expected content length and other metadata. */
|
|
51
|
+
private async headResponse(): Promise<Response> {
|
|
52
|
+
if (this._headResponse) return this._headResponse;
|
|
53
|
+
const resp = await this.client(this.url, {
|
|
54
|
+
method: 'HEAD',
|
|
55
|
+
});
|
|
56
|
+
if (!resp.ok)
|
|
57
|
+
throw new Error(
|
|
58
|
+
`http HEAD request for ${this.url} failed with HTTP status code ${resp.status}`
|
|
59
|
+
); // TODO
|
|
60
|
+
this._headResponse = resp;
|
|
61
|
+
return resp;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
close() {
|
|
65
|
+
// Nada
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async link() {
|
|
69
|
+
/*const resp = await this.headResponse();
|
|
70
|
+
const newLink = Link.deserialize(this._link.serialize()); // This is a hack to deep copy the link
|
|
71
|
+
newLink.type = resp.headers.get("")*/
|
|
72
|
+
return this._link; // TODO mediatype alteration. Need http response mediatype sniffer stuff
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async read(range?: NumberRange): Promise<Uint8Array | undefined> {
|
|
76
|
+
if (range) throw new Error('http read range not implemented!'); // TODO
|
|
77
|
+
const resp = await this.client(this.url);
|
|
78
|
+
if (!resp.ok)
|
|
79
|
+
throw new Error(
|
|
80
|
+
`http GET request for ${this.url} failed with HTTP status code ${resp.status}`
|
|
81
|
+
); // TODO
|
|
82
|
+
return new Uint8Array(await resp.arrayBuffer());
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async length(): Promise<number> {
|
|
86
|
+
const resp = await this.headResponse();
|
|
87
|
+
const contentLength = resp.headers.get('content-length');
|
|
88
|
+
if (contentLength === null || contentLength === '')
|
|
89
|
+
throw new Error('length for resource unavailable'); // TODO
|
|
90
|
+
return parseInt(contentLength);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async readAsJSON(): Promise<unknown> {
|
|
94
|
+
const resp = await this.client(this.url);
|
|
95
|
+
if (!resp.ok)
|
|
96
|
+
throw new Error(
|
|
97
|
+
`http GET request for ${this.url} failed with HTTP status code ${resp.status}`
|
|
98
|
+
); // TODO
|
|
99
|
+
return await resp.json();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async readAsString(): Promise<string> {
|
|
103
|
+
const resp = await this.client(this.url);
|
|
104
|
+
if (!resp.ok)
|
|
105
|
+
throw new Error(
|
|
106
|
+
`http GET request for ${this.url} failed with HTTP status code ${resp.status}`
|
|
107
|
+
); // TODO
|
|
108
|
+
return await resp.text();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async readAsXML(): Promise<XMLDocument> {
|
|
112
|
+
const resp = await this.client(this.url);
|
|
113
|
+
if (!resp.ok)
|
|
114
|
+
throw new Error(
|
|
115
|
+
`http GET request for ${this.url} failed with HTTP status code ${resp.status}`
|
|
116
|
+
); // TODO
|
|
117
|
+
return new DOMParser().parseFromString(
|
|
118
|
+
await resp.text(),
|
|
119
|
+
'application/xml'
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Link } from '../publication/Link';
|
|
2
|
+
|
|
3
|
+
export class NumberRange {
|
|
4
|
+
// TODO move to utils
|
|
5
|
+
public readonly start: number;
|
|
6
|
+
public readonly endInclusive: number;
|
|
7
|
+
|
|
8
|
+
constructor(start: number, endInclusive: number) {
|
|
9
|
+
this.start = start;
|
|
10
|
+
this.endInclusive = endInclusive;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export abstract class Resource {
|
|
15
|
+
abstract link(): Promise<Link>;
|
|
16
|
+
abstract length(): Promise<number | undefined>; // TODO make try?
|
|
17
|
+
abstract read(range?: NumberRange): Promise<Uint8Array | undefined>;
|
|
18
|
+
readAsString(): Promise<string | undefined> {
|
|
19
|
+
return this.read().then(bytes => {
|
|
20
|
+
if (bytes === undefined) return bytes;
|
|
21
|
+
return new TextDecoder().decode(bytes);
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
readAsJSON(): Promise<unknown | undefined> {
|
|
25
|
+
return this.readAsString().then(str => {
|
|
26
|
+
if (str === undefined) return str;
|
|
27
|
+
return JSON.parse(str);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
readAsXML(): Promise<XMLDocument | undefined> {
|
|
31
|
+
return this.readAsString().then(str => {
|
|
32
|
+
if (str === undefined) return str;
|
|
33
|
+
return new DOMParser().parseFromString(str, 'text/xml');
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
abstract close(): void;
|
|
37
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/* Copyright 2021 Readium Foundation. All rights reserved.
|
|
2
|
+
* Use of this source code is governed by a BSD-style license,
|
|
3
|
+
* available in the LICENSE file present in the Github repository of the project.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* OPDS Acquisition Object.
|
|
8
|
+
*
|
|
9
|
+
* https://drafts.opds.io/schema/acquisition-object.schema.json
|
|
10
|
+
*/
|
|
11
|
+
export class Acquisition {
|
|
12
|
+
/** Currency for the price, eg. EUR. */
|
|
13
|
+
public type: string;
|
|
14
|
+
|
|
15
|
+
/** Price value, should only be used for display purposes, because of precision issues
|
|
16
|
+
* inherent with Double and the JSON parsing. */
|
|
17
|
+
public children?: Array<Acquisition>;
|
|
18
|
+
|
|
19
|
+
/** Creates a [Acquisition]. */
|
|
20
|
+
constructor(values: { type: string; children?: Array<Acquisition> }) {
|
|
21
|
+
this.type = values.type;
|
|
22
|
+
this.children = values.children;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Parses a [Acquisition] from its RWPM JSON representation.
|
|
27
|
+
*/
|
|
28
|
+
public static deserialize(json: any): Acquisition | undefined {
|
|
29
|
+
if (!(json && json.type)) return;
|
|
30
|
+
|
|
31
|
+
return new Acquisition({
|
|
32
|
+
type: json.type,
|
|
33
|
+
children: Acquisition.deserializeArray(json.children),
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
public static deserializeArray(json: any): Array<Acquisition> | undefined {
|
|
38
|
+
if (!(json instanceof Array)) return;
|
|
39
|
+
return json
|
|
40
|
+
.map<Acquisition>(item => Acquisition.deserialize(item) as Acquisition)
|
|
41
|
+
.filter(x => x !== undefined);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Serializes a [Acquisition] to its RWPM JSON representation.
|
|
46
|
+
*/
|
|
47
|
+
public serialize(): any {
|
|
48
|
+
const json: any = { type: this.type };
|
|
49
|
+
if (this.children) {
|
|
50
|
+
json.children = this.children.map(x => x.serialize());
|
|
51
|
+
}
|
|
52
|
+
return json;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/* Copyright 2021 Readium Foundation. All rights reserved.
|
|
2
|
+
* Use of this source code is governed by a BSD-style license,
|
|
3
|
+
* available in the LICENSE file present in the Github repository of the project.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { datefromJSON } from '../util/JSONParse';
|
|
7
|
+
|
|
8
|
+
export enum AvailabilityStatus {
|
|
9
|
+
available = 'available',
|
|
10
|
+
reserved = 'reserved',
|
|
11
|
+
ready = 'ready',
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Indicated the availability of a given resource.
|
|
16
|
+
*
|
|
17
|
+
* https://drafts.opds.io/schema/properties.schema.json
|
|
18
|
+
*
|
|
19
|
+
*/
|
|
20
|
+
export class Availability {
|
|
21
|
+
/**Timestamp for the previous state change. */
|
|
22
|
+
public since?: Date;
|
|
23
|
+
|
|
24
|
+
/**Timestamp for the next state change. */
|
|
25
|
+
public until?: Date;
|
|
26
|
+
|
|
27
|
+
public state: AvailabilityStatus;
|
|
28
|
+
|
|
29
|
+
/** Creates a [Availability]. */
|
|
30
|
+
constructor(values: {
|
|
31
|
+
state: AvailabilityStatus;
|
|
32
|
+
since?: Date;
|
|
33
|
+
until?: Date;
|
|
34
|
+
}) {
|
|
35
|
+
this.state = values.state;
|
|
36
|
+
this.since = values.since;
|
|
37
|
+
this.until = values.until;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parses a [Availability] from its RWPM JSON representation.
|
|
42
|
+
*/
|
|
43
|
+
public static deserialize(json: any): Availability | undefined {
|
|
44
|
+
if (!(json && json.state)) return;
|
|
45
|
+
return new Availability({
|
|
46
|
+
state: json.state,
|
|
47
|
+
since: datefromJSON(json.since),
|
|
48
|
+
until: datefromJSON(json.until),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Serializes a [Availability] to its RWPM JSON representation.
|
|
54
|
+
*/
|
|
55
|
+
public serialize(): any {
|
|
56
|
+
const json: any = { state: this.state };
|
|
57
|
+
if (this.since !== undefined) json.since = this.since.toISOString();
|
|
58
|
+
if (this.until !== undefined) json.until = this.until.toISOString();
|
|
59
|
+
return json;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/* Copyright 2021 Readium Foundation. All rights reserved.
|
|
2
|
+
* Use of this source code is governed by a BSD-style license,
|
|
3
|
+
* available in the LICENSE file present in the Github repository of the project.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { positiveNumberfromJSON } from '../util/JSONParse';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Library-specific feature that contains information about the copies that a library has acquired.
|
|
10
|
+
*
|
|
11
|
+
* https://drafts.opds.io/schema/properties.schema.json
|
|
12
|
+
*/
|
|
13
|
+
export class Copies {
|
|
14
|
+
public total?: number;
|
|
15
|
+
public available?: number;
|
|
16
|
+
|
|
17
|
+
/** Creates a [Copies]. */
|
|
18
|
+
constructor(values: { total?: number; available?: number }) {
|
|
19
|
+
this.total = values.total;
|
|
20
|
+
this.available = values.available;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Parses a [Copies] from its RWPM JSON representation.
|
|
25
|
+
*/
|
|
26
|
+
public static deserialize(json: any): Copies | undefined {
|
|
27
|
+
if (!json) return;
|
|
28
|
+
return new Copies({
|
|
29
|
+
total: positiveNumberfromJSON(json.total),
|
|
30
|
+
available: positiveNumberfromJSON(json.available),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Serializes a [Copies] to its RWPM JSON representation.
|
|
36
|
+
*/
|
|
37
|
+
public serialize(): any {
|
|
38
|
+
const json: any = {};
|
|
39
|
+
if (this.total !== undefined) json.total = this.total;
|
|
40
|
+
if (this.available !== undefined) json.available = this.available;
|
|
41
|
+
return json;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/* Copyright 2021 Readium Foundation. All rights reserved.
|
|
2
|
+
* Use of this source code is governed by a BSD-style license,
|
|
3
|
+
* available in the LICENSE file present in the Github repository of the project.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { positiveNumberfromJSON } from '../util/JSONParse';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Library-specific features when a specific book is unavailable but provides a hold list.
|
|
10
|
+
*
|
|
11
|
+
* https://drafts.opds.io/schema/properties.schema.json
|
|
12
|
+
*/
|
|
13
|
+
export class Holds {
|
|
14
|
+
public total?: number;
|
|
15
|
+
public position?: number;
|
|
16
|
+
|
|
17
|
+
/** Creates a [Price]. */
|
|
18
|
+
constructor(values: { total?: number; position?: number }) {
|
|
19
|
+
this.total = values.total;
|
|
20
|
+
this.position = values.position;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Parses a [Holds] from its RWPM JSON representation.
|
|
25
|
+
*/
|
|
26
|
+
public static deserialize(json: any): Holds | undefined {
|
|
27
|
+
if (!json) return;
|
|
28
|
+
return new Holds({
|
|
29
|
+
total: positiveNumberfromJSON(json.total),
|
|
30
|
+
position: positiveNumberfromJSON(json.position),
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Serializes a [Holds] to its RWPM JSON representation.
|
|
36
|
+
*/
|
|
37
|
+
public serialize(): any {
|
|
38
|
+
const json: any = {};
|
|
39
|
+
if (this.total !== undefined) json.total = this.total;
|
|
40
|
+
if (this.position !== undefined) json.position = this.position;
|
|
41
|
+
return json;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/* Copyright 2021 Readium Foundation. All rights reserved.
|
|
2
|
+
* Use of this source code is governed by a BSD-style license,
|
|
3
|
+
* available in the LICENSE file present in the Github repository of the project.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { positiveNumberfromJSON } from '../util/JSONParse';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The price of a publication in an OPDS link.
|
|
10
|
+
*
|
|
11
|
+
* https://drafts.opds.io/schema/properties.schema.json
|
|
12
|
+
*
|
|
13
|
+
* currency Currency for the price, eg. EUR.
|
|
14
|
+
* value Price value, should only be used for display purposes, because of precision issues
|
|
15
|
+
* inherent with Double and the JSON parsing.
|
|
16
|
+
*/
|
|
17
|
+
export class Price {
|
|
18
|
+
/** Currency for the price, eg. EUR. */
|
|
19
|
+
public currency: string;
|
|
20
|
+
|
|
21
|
+
/** Price value, should only be used for display purposes, because of precision issues
|
|
22
|
+
* inherent with Double and the JSON parsing. */
|
|
23
|
+
public value: number;
|
|
24
|
+
|
|
25
|
+
/** Creates a [Price]. */
|
|
26
|
+
constructor(values: { currency: string; value: number }) {
|
|
27
|
+
this.currency = values.currency;
|
|
28
|
+
this.value = values.value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Parses a [Price] from its RWPM JSON representation.
|
|
33
|
+
*/
|
|
34
|
+
public static deserialize(json: any): Price | undefined {
|
|
35
|
+
if (!json) return;
|
|
36
|
+
let currency = json.currency;
|
|
37
|
+
if (!(currency && typeof currency === 'string' && currency.length > 0))
|
|
38
|
+
return;
|
|
39
|
+
let value = positiveNumberfromJSON(json.value);
|
|
40
|
+
if (value === undefined) return;
|
|
41
|
+
return new Price({ currency, value });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Serializes a [Price] to its RWPM JSON representation.
|
|
46
|
+
*/
|
|
47
|
+
public serialize(): any {
|
|
48
|
+
const json: any = { currency: this.currency, value: this.value };
|
|
49
|
+
return json;
|
|
50
|
+
}
|
|
51
|
+
}
|