metapatcher
Version:
HTML document head management library with convenient api. Manage social media tags, icons, device specific tags and event structured data with html meta tags and JSONLD documents.
3 lines (2 loc) • 16.4 kB
JavaScript
import e from"@babel/runtime-corejs3/helpers/esm/objectWithoutProperties";import t from"@babel/runtime-corejs3/helpers/esm/defineProperty";const i=["src"],s=["href"];class n{constructor(){t(this,"features",[]),t(this,"idPrefix","metapatcher"),t(this,"idCounters",{preload:0,prefetch:0,preconnect:0,dnsPrefetch:0}),t(this,"isDomAvailable","undefined"!=typeof document),t(this,"memory",[]),t(this,"htmlVoidElements",["base","link","meta"]),t(this,"mimeTypesByExtension",{svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",ico:"image/x-icon",gif:"image/gif",webp:"image/webp",bmp:"image/bmp"}),t(this,"reImageSizeFromStr",/[0-9]{2,3}x[0-9]{2,3}/g),t(this,"appleTouchIconSizes",["120x120","180x180","152x152","167x167","1024x1024"]),t(this,"webAppManifestIconSizes",["72x72","96x96","128x128","144x144","152x152","192x192","384x384","512x512"]),t(this,"msTilesNamingMap",{"70x70":"msapplication-square70x70logo","150x150":"msapplication-square150x150logo","310x310":"msapplication-square310x310logo","310x150":"msapplication-wide310x150logo"}),this.features=["structuredData","msTags","appleTags","openGraphTags","twitterTags","webAppManifest"],this.setMsApplicationConfig("none")}configure(e,t){if(null!=t&&t.idPrefix&&(this.idPrefix=t.idPrefix),e&&(this.features=e),this.features.includes("appleTags")){const e=this.idPrefix+"-apple-mobile-web-app-capable";this.set("meta",{id:e,name:"apple-mobile-web-app-capable",content:"yes"})}if(this.features.includes("twitterTags")){const e=this.idPrefix+"-twitter-card";this.set("meta",{id:e,name:"twitter:card",content:"summary"})}}setIcons(e){const t=Object.keys(this.msTilesNamingMap);for(const i of e){const e=this.findMimeType(i),s=i.match(this.reImageSizeFromStr),n=s&&s.length>0?s[0]:void 0;if(n&&e){if(this.features.includes("webAppManifest")&&this.webAppManifestIconSizes.includes(n)){const t=this.idPrefix+"-icon-"+n+"-wam";this.removeOne("link",{id:t}),this.set("link",{id:t,rel:"icon",href:i,sizes:n,type:e})}if(this.features.includes("appleTags")&&this.appleTouchIconSizes.includes(n)){const e=this.idPrefix+"-icon-"+n+"-apple";this.removeOne("link",{id:e}),this.set("link",{id:e,rel:"apple-touch-icon",href:i,sizes:n})}if(this.features.includes("msTags")&&t.includes(n)){const e=this.idPrefix+"-icon-"+n+"-ms";this.removeOne("meta",{id:e}),this.set("meta",{id:e,name:this.msTilesNamingMap[n],content:i})}}}return this}setPageDetails(e){var t;return e.title&&this.setPageTitle(e.title),e.description&&this.setPageDescription(e.description),e.path&&this.setPageUrl(e.path),e.image&&this.setPageImage(e.image),e.robots&&this.setRobots(e.robots),e.locale&&this.setPageLocale(e.locale),e.canonical&&this.setCanonical(e.canonical),e.localVersions&&this.setLocalVersions(e.localVersions,null!==(t=e.locale)&&void 0!==t?t:""),e.breadcrumb&&this.setBreadcrumb(e.breadcrumb),this}setPageTitle(e){if(this.setDocumentTitle(e),this.features.includes("openGraphTags")){const t=this.idPrefix+"og-title";this.removeOne("meta",{id:t}),this.set("meta",{id:t,property:"og:title",content:e})}if(this.features.includes("twitterTags")){const t=this.idPrefix+"tw-title";this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"twitter:title",content:e})}return this}setPageDescription(e){const t=this.idPrefix+"-description";if(this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"description",content:e}),this.features.includes("openGraphTags")){const t=this.idPrefix+"-description-og";this.removeOne("meta",{id:t}),this.set("meta",{id:t,property:"og:description",content:e})}if(this.features.includes("twitterTags")){const t=this.idPrefix+"-description-tw";this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"twitter:description",content:e})}return this}setPageUrl(e){if(this.features.includes("openGraphTags")){const t=this.idPrefix+"-url-og";this.removeOne("meta",{id:t}),this.set("meta",{id:t,property:"og:url",content:e})}return this}setPageImage(e){const t="string"==typeof e?{path:e}:e;if(this.features.includes("openGraphTags")){const e=this.idPrefix+"-image-og";this.removeOne("meta",{id:e}),this.set("meta",{id:e,property:"og:image",content:t.path});const i=this.idPrefix+"-image-w-og";this.removeOne("meta",{id:i}),t.width&&this.set("meta",{id:i,property:"og:image:width",content:t.width.toString()});const s=this.idPrefix+"-image-h-og";this.removeOne("meta",{id:s}),t.height&&this.set("meta",{id:s,property:"og:image:height",content:t.height.toString()})}if(this.features.includes("twitterTags")){const e=this.idPrefix+"-image-tw";this.removeOne("meta",{id:e}),this.set("meta",{id:e,property:"twitter:image",content:t.path})}return this}setPageLocale(e){if(e=e.replace("_","-"),this.isDomAvailable&&document.documentElement.setAttribute("lang",e),this.features.includes("openGraphTags")){const t=this.idPrefix+"-locale-og";this.removeOne("meta",{id:t}),this.set("meta",{id:t,property:"og:locale",content:e})}}setProjectDetails(e){if(e.favicon&&this.setFavicon(e.favicon),e.name&&this.setProjectName(e.name),e.url&&this.setProjectUrl(e.url),e.robots&&this.setRobots(e.robots),e.themeColor&&this.setThemeColor(e.themeColor),e.twitterSite&&this.setTwitterSite(e.twitterSite),e.safariPinnedTab&&this.setSafariPinnedTab(e.safariPinnedTab),e.icons&&this.setIcons(e.icons),this.features.includes("structuredData")){const t=this.idPrefix+"-project-org",i={"@context":"https://schema.org","@type":"Organization"};e.logo&&(i.logo=e.logo),e.url&&(i.url=e.url),e.name&&(i.name=e.name),e.email&&(i.email=e.email),e.phone&&(i.telephone=e.phone),e.description&&(i.description=e.description),e.image&&(i.image=e.image),e.legalName&&(i.legalName=e.legalName),e.address&&(i.address={"@type":"PostalAddress"},e.address.country&&(i.address.addressCountry=e.address.country),e.address.region&&(i.address.addressRegion=e.address.region),e.address.city&&(i.address.addressLocality=e.address.city),e.address.postalCode&&(i.address.postalCode=e.address.postalCode),e.address.street&&(i.address.streetAddress=e.address.street));const s=JSON.stringify(i);this.removeOne("script",{id:t}),this.isDomAvailable?this.setJsonLdDom(t,s):this.setJsonLdMemory(t,s)}return this}setProjectName(e){const t=this.idPrefix+"-project-name";if(this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"application-name",content:e}),this.features.includes("openGraphTags")){const t=this.idPrefix+"-project-name-og";this.removeOne("meta",{id:t}),this.set("meta",{id:t,property:"og:site_name",content:e})}else if(this.features.includes("appleTags")){const t=this.idPrefix+"-project-name-apple";this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"apple-mobile-web-app-title",content:e})}return this}setProjectUrl(e){if(this.features.includes("msTags")){const t=this.idPrefix+"-project-url";this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"msapplication-starturl",content:e})}return this}setThemeColor(e){const t=this.idPrefix+"-theme-color";if(this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"theme-color",content:e}),this.features.includes("msTags")){const t=this.idPrefix+"-theme-color-ms";this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"msapplication-TileColor",content:e})}return this}setTwitterSite(e){const t=this.idPrefix+"-twitter-site";return this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"twitter:site",content:e}),this}addDnsPrefetch(e){const t=this.idPrefix+"-dns-prefetch-"+this.idCounters.dnsPrefetch.toString();this.idCounters.dnsPrefetch+=1;const i="string"==typeof e?{id:t,rel:"dns-prefetch",href:e}:Object.assign({},e,{id:t,rel:"dns-prefetch"});return this.removeOne("link",{rel:"dns-prefetch",href:i.href}),this.set("link",i),this}addPreconnect(e){const t=this.idPrefix+"-preconnect-"+this.idCounters.preconnect.toString();this.idCounters.preconnect+=1;const i="string"==typeof e?{id:t,rel:"preconnect",href:e}:Object.assign({},e,{id:t,rel:"preconnect"});return this.removeOne("link",{rel:"preconnect",href:i.href}),this.set("link",i),this}addPrefetch(e){const t=this.idPrefix+"-prefetch-"+this.idCounters.prefetch.toString();this.idCounters.prefetch+=1;const i="string"==typeof e?{id:t,rel:"prefetch",href:e}:Object.assign({},e,{id:t,rel:"prefetch"});return this.removeOne("link",{rel:"prefetch",href:i.href}),this.set("link",i),this}addPreload(e){const t=this.idPrefix+"-preload-"+this.idCounters.preload.toString();this.idCounters.preload+=1;const i="string"==typeof e?{id:t,rel:"preload",href:e}:Object.assign({},e,{id:t,rel:"preload"});return this.removeOne("link",{rel:"preload",href:i.href}),this.set("link",i),this}setRobots(e){const t=this.idPrefix+"-robots",i="string"==typeof e?{id:t,name:"robots",content:e}:Object.assign({},e,{id:t,name:"robots"});return this.removeOne("meta",{id:t}),this.set("meta",i),this}setDocumentTitle(e){if(this.isDomAvailable)document.title=e;else{const t=e=>e.includes("<title>")&&e.includes("</title>");this.memory.some(t)?this.memory=this.memory.map((i=>t(i)?"<title>".concat(e,"</title>"):i)):this.memory.push("<title>".concat(e,"</title>"))}return this}setFavicon(e){if(!this.findMimeType("string"==typeof e?e:e.href))return this;const t=this.idPrefix+"-favicon",i="string"==typeof e?{id:t,rel:"shortcut icon",href:e}:Object.assign({},e,{id:t,rel:"shortcut icon"});return this.removeOne("link",{id:t}),this.set("link",i),this}setMsApplicationConfig(e){const t=this.idPrefix+"-msapplication-config",i="string"==typeof e?{id:t,name:"msapplication-config",content:e}:Object.assign({},e,{id:t,name:"msapplication-config"});return this.removeOne("meta",{id:t}),this.set("meta",i),this}setSafariPinnedTab(e){const t=this.idPrefix+"-safari-pinned-tab",i=Object.assign({},e,{id:t,rel:"mask-icon"});return this.removeOne("link",{id:t}),this.set("link",i),this}setAppleStatusBarStyle(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"default";const t=this.idPrefix+"-apple-status-bar-style";return this.removeOne("meta",{id:t}),this.set("meta",{id:t,name:"apple-mobile-web-app-status-bar-style",content:e}),this}setBreadcrumb(e){if(!this.features.includes("structuredData"))return"";const t=this.idPrefix+"-breadcrumb",i={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:e.map(((e,t)=>{let{title:i,url:s}=e;return{"@type":"ListItem",position:t+1,name:i,item:s}}))},s=JSON.stringify(i);return this.removeOne("script",{id:t}),this.isDomAvailable?this.setJsonLdDom(t,s):this.setJsonLdMemory(t,s)}setJsonLdDom(e,t){const i=document.createElement("script");return i.id=e,i.type="application/ld+json",i.text=t,document.head.insertBefore(i,null),i}setJsonLdMemory(e,t){const i='<script id="'.concat(e,'" type="application/ld+json">').concat(t,"<\/script>");return this.memory.push(i),i}setCanonical(e){const t=this.idPrefix+"-canonical",i="string"==typeof e?{id:t,rel:"canonical",href:e}:Object.assign({},e,{id:t,rel:"canonical"});return this.removeOne("link",{id:t}),this.set("link",i),this}setMeta(e,t){return this.removeOne("meta",{name:e}),this.set("meta",{name:e,content:t}),this}setMobileVariant(e){const t=this.idPrefix+"-mobile-variant",i="string"==typeof e?{id:t,rel:"alternate",href:e,media:"only screen and (max-width: 640px)"}:Object.assign({},e,{id:t,rel:"alternate"});return this.removeOne("link",{id:t}),this.set("link",i),this}setLocalVersions(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";this.removeMany("link",{rel:"alternate",hreflang:!0}),this.features.includes("openGraphTags")&&(t=t.replace("_","-"),this.removeMany("meta",{property:"og:locale:alternate"}),this.removeOne("meta",{property:"og:locale"}));for(const i of e){const e=this.idPrefix+"-local-version-"+i.hreflang;i.hreflang=i.hreflang.replace("_","-");const s=Object.assign({},i,{id:e,rel:"alternate"});if(this.set("link",s),this.features.includes("openGraphTags")){const e={id:this.idPrefix+"-local-version-og-"+i.hreflang,property:"og:locale"+(t===i.hreflang?"":":alternate"),content:i.hreflang.replace("-","_")};this.set("meta",e)}}return this}setJsonLd(e,t){const i=JSON.stringify(t);return this.removeOne("script",{id:e}),this.isDomAvailable?this.setJsonLdDom(e,i):this.setJsonLdMemory(e,i)}removeOne(e,t){if(!this.isDomAvailable){const i=["<".concat(e)].concat(Object.keys(t).map((e=>"".concat(e,'="').concat(t[e],'"'))));return this.memory=this.memory.filter((e=>!i.every((t=>e.includes(t))))),this}const i=Object.keys(t).reduce(((e,i)=>e+="[".concat(i,'="').concat(t[i],'"]')),""),s="".concat(e).concat(i),n=document.head.querySelector(s);return n&&n.parentNode.removeChild(n),this}removeMany(e,t){if(!this.isDomAvailable){const i=["<".concat(e)].concat(Object.keys(t).map((e=>"boolean"==typeof t[e]?"".concat(e):"".concat(e,'="').concat(t[e],'"'))));return this.memory=this.memory.filter((e=>!i.every((t=>e.includes(t))))),this}const i=Object.keys(t).reduce(((e,i)=>e+="boolean"==typeof t[i]?"[".concat(i,"]"):"[".concat(i,'="').concat(t[i],'"]')),""),s="".concat(e).concat(i),n=document.head.querySelectorAll(s);return n&&n.length>0&&n.forEach((e=>{e.parentNode.removeChild(e)})),this}dump(){return this.isDomAvailable?"":this.memory.join("\n")}flushMemory(){return this.memory=[],this}set(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;e=e.toLowerCase();const s=i&&Object.hasOwn(i,"void")?i.void:this.htmlVoidElements.includes(e);return this.isDomAvailable?this.setDom(e,t,{void:s}):this.setMemory(e,t,{void:s})}setDom(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=document.createElement(e);return this.setElementAttrs(i,t),document.head.insertBefore(i,null),i}setMemory(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=(arguments.length>2?arguments[2]:void 0).void?" />":"></".concat(e,">"),s="<".concat(e).concat(this.serializeAttrs(t)).concat(i);return this.memory.push(s),s}setElementAttrs(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(const i of Object.keys(t)){const s=t[i];"string"==typeof s?e.setAttribute(i,s):!0===s&&e.setAttribute(i,"")}}async setScript(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t=Object.assign({},{type:"text/javascript"},t),s=Object.assign({},{location:"headEnd",waitForLoad:"",timeout:1e4},s),new Promise(((n,r)=>{if(!this.isDomAvailable)return n(this.setMemory("script",t,{void:this.htmlVoidElements.includes("script")}));const o=setTimeout((()=>{r(new Error("Timeout."))}),s.timeout),a=document.createElement("script"),{src:c}=t,l=e(t,i);this.setElementAttrs(a,l),a.addEventListener("load",(function(){if(clearTimeout(o),0===s.waitForLoad.length)return n(a);{const e=setInterval((()=>{if(Object.hasOwn(window,s.waitForLoad))return clearInterval(e),n(a)}),100)}})),a.addEventListener("error",(function(e){clearTimeout(o),r(new Error("Error loading resource"))})),a.src=c,"headEnd"===s.location?document.head.insertBefore(a,null):"bodyEnd"===s.location?document.body.insertBefore(a,null):"bodyStart"===s.location?document.body.insertBefore(a,document.body.firstChild):document.body.insertBefore(a,null)}))}async setStylesheet(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return t=Object.assign({},{rel:"stylesheet"},t),i=Object.assign({},{location:"headEnd",timeout:1e4},i),new Promise(((n,r)=>{if(!this.isDomAvailable)return n(this.setMemory("link",t,{void:this.htmlVoidElements.includes("link")}));const o=setTimeout((()=>{r(new Error("Timeout."))}),i.timeout),a=document.createElement("link"),{href:c}=t,l=e(t,s);this.setElementAttrs(a,Object.assign({},l,{media:"only x"})),a.addEventListener("load",(function(){var e;return a.media=null!==(e=t.media)&&void 0!==e?e:"all",clearTimeout(o),n(a)})),a.addEventListener("error",(function(e){return clearTimeout(o),r(new Error("Error loading resource"))})),a.href=c,"headEnd"===i.location?document.head.insertBefore(a,null):"bodyEnd"===i.location?document.body.insertBefore(a,null):"bodyStart"===i.location?document.body.insertBefore(a,document.body.firstChild):document.body.insertBefore(a,null)}))}serializeAttrs(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Object.keys(e).reduce(((t,i)=>t+=" ".concat(i,'="').concat(e[i],'"')),"")}findMimeType(e){const t=e.lastIndexOf(".");if(t<1)return;const i=e.slice(t+1);return i&&Object.hasOwn(this.mimeTypesByExtension,i)?this.mimeTypesByExtension[i]:void 0}}const r=new n;export{n as Metapatcher,r as metapatcher};
//# sourceMappingURL=metapatcher.es.js.map