likec4 1.6.1-next → 1.6.1-next.2

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.
@@ -20,7 +20,7 @@ export { isLikeC4ViewId }
20
20
 
21
21
  export type LikeC4ViewProps = LikeC4ViewBaseProps<LikeC4ViewId>
22
22
 
23
- export const LikeC4View = memo<LikeC4ViewProps>(function LikeC4ViewComponent({
23
+ export const LikeC4View = /* @__PURE__ */ memo<LikeC4ViewProps>(function LikeC4ViewComponent({
24
24
  viewId,
25
25
  interactive = true,
26
26
  colorScheme,
@@ -72,3 +72,4 @@ export const LikeC4View = memo<LikeC4ViewProps>(function LikeC4ViewComponent({
72
72
  </>
73
73
  )
74
74
  })
75
+ LikeC4View.displayName = 'LikeC4View'
@@ -0,0 +1 @@
1
+ import{d2Source}from"virtual:likec4/d2-sources";import{dotSource,svgSource}from"virtual:likec4/dot-sources";import{mmdSource}from"virtual:likec4/mmd-sources";export{d2Source,dotSource,mmdSource,svgSource};
@@ -8,6 +8,6 @@ if (!BASE.endsWith('/')) {
8
8
  BASE = BASE + '/'
9
9
  }
10
10
 
11
- export const useHasHistory = __USE_HASH_HISTORY__
11
+ export const useHashHistory = __USE_HASH_HISTORY__
12
12
 
13
- export const basepath = useHasHistory ? '/' : BASE
13
+ export const basepath = useHashHistory ? '/' : BASE
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Ugly hack to make Vite HMR work with the virtual module HMR.
3
+ * (I don't know, but virtual module IDs in my case can't be used to subscribe to HMR updates)
4
+ */
5
+ import { LikeC4Views } from 'virtual:likec4/views'
6
+
7
+ export { LikeC4Views }
@@ -0,0 +1,5 @@
1
+ export {
2
+ $views,
3
+ useLikeC4View,
4
+ useLikeC4Views
5
+ } from './store'
@@ -0,0 +1,41 @@
1
+ import { type DiagramView } from '@likec4/core'
2
+ import { useStore } from '@nanostores/react'
3
+ import { map } from 'nanostores'
4
+ import { LikeC4Views } from './_hmr'
5
+
6
+ let keys = new Set(Object.keys(LikeC4Views))
7
+ export const $views = map(LikeC4Views as unknown as Record<string, DiagramView>)
8
+
9
+ export function useLikeC4Views() {
10
+ return useStore($views)
11
+ }
12
+
13
+ export function useLikeC4View(id: string) {
14
+ const views = useStore($views, {
15
+ keys: [id]
16
+ })
17
+ return views[id] ?? null
18
+ }
19
+
20
+ if (import.meta.env.DEV) {
21
+ import.meta.hot?.accept('./_hmr', md => {
22
+ const update = md?.LikeC4Views as Record<string, DiagramView>
23
+ if (update) {
24
+ const currents = $views.get()
25
+ let newKeys = new Set<string>()
26
+ for (const [id, view] of Object.entries(update)) {
27
+ newKeys.add(id)
28
+ $views.setKey(id, view)
29
+ }
30
+ for (const key of keys) {
31
+ if (!newKeys.has(key)) {
32
+ // @ts-ignore
33
+ $views.setKey(key, undefined)
34
+ }
35
+ }
36
+ keys = newKeys
37
+ } else {
38
+ import.meta.hot?.invalidate()
39
+ }
40
+ })
41
+ }
@@ -0,0 +1,6 @@
1
+ <svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <path d="M152.266 152.674V14H29.2171C24.1477 14 20 18.3487 20 23.6637V153.158H152.266V152.674Z" fill="#5E98AF"/>
3
+ <path d="M170.237 152.673H236.6V92.7575C236.6 87.4424 232.452 83.0938 227.383 83.0938H170.237V152.673Z" fill="#5E98AF"/>
4
+ <path d="M152.267 171.515H86.3647V231.43C86.3647 236.745 90.5125 241.094 95.5819 241.094H152.728V171.515H152.267Z" fill="#5E98AF"/>
5
+ <path d="M170.237 171.515V241.094H227.383C232.452 241.094 236.6 236.745 236.6 231.43V171.515H170.237Z" fill="#5E98AF"/>
6
+ </svg>
@@ -0,0 +1,2 @@
1
+ function resolveUrl(url,baseUrl){if(url.match(/^[a-z]+:\/\//i))return url;if(url.match(/^\/\//))return window.location.protocol+url;if(url.match(/^[a-z]+:/i))return url;const doc=document.implementation.createHTMLDocument(),base=doc.createElement("base"),a=doc.createElement("a");return doc.head.appendChild(base),doc.body.appendChild(a),baseUrl&&(base.href=baseUrl),a.href=url,a.href}const uuid=(()=>{let counter=0;const random=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(counter+=1,`u${random()}${counter}`)})();function toArray(arrayLike){const arr=[];for(let i=0,l=arrayLike.length;i<l;i++)arr.push(arrayLike[i]);return arr}function px(node,styleProperty){const val=(node.ownerDocument.defaultView||window).getComputedStyle(node).getPropertyValue(styleProperty);return val?parseFloat(val.replace("px","")):0}function getNodeWidth(node){const leftBorder=px(node,"border-left-width"),rightBorder=px(node,"border-right-width");return node.clientWidth+leftBorder+rightBorder}function getNodeHeight(node){const topBorder=px(node,"border-top-width"),bottomBorder=px(node,"border-bottom-width");return node.clientHeight+topBorder+bottomBorder}function getImageSize(targetNode,options={}){const width=options.width||getNodeWidth(targetNode),height=options.height||getNodeHeight(targetNode);return{width,height}}function getPixelRatio(){let ratio,FINAL_PROCESS;try{FINAL_PROCESS=process}catch{}const val=FINAL_PROCESS&&FINAL_PROCESS.env?FINAL_PROCESS.env.devicePixelRatio:null;return val&&(ratio=parseInt(val,10),Number.isNaN(ratio)&&(ratio=1)),ratio||window.devicePixelRatio||1}const canvasDimensionLimit=16384;function checkCanvasDimensions(canvas){(canvas.width>canvasDimensionLimit||canvas.height>canvasDimensionLimit)&&(canvas.width>canvasDimensionLimit&&canvas.height>canvasDimensionLimit?canvas.width>canvas.height?(canvas.height*=canvasDimensionLimit/canvas.width,canvas.width=canvasDimensionLimit):(canvas.width*=canvasDimensionLimit/canvas.height,canvas.height=canvasDimensionLimit):canvas.width>canvasDimensionLimit?(canvas.height*=canvasDimensionLimit/canvas.width,canvas.width=canvasDimensionLimit):(canvas.width*=canvasDimensionLimit/canvas.height,canvas.height=canvasDimensionLimit))}function createImage(url){return new Promise((resolve,reject)=>{const img=new Image;img.decode=()=>resolve(img),img.onload=()=>resolve(img),img.onerror=reject,img.crossOrigin="anonymous",img.decoding="async",img.src=url})}async function svgToDataURL(svg){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(svg)).then(encodeURIComponent).then(html=>`data:image/svg+xml;charset=utf-8,${html}`)}async function nodeToDataURL(node,width,height){const xmlns="http://www.w3.org/2000/svg",svg=document.createElementNS(xmlns,"svg"),foreignObject=document.createElementNS(xmlns,"foreignObject");return svg.setAttribute("width",`${width}`),svg.setAttribute("height",`${height}`),svg.setAttribute("viewBox",`0 0 ${width} ${height}`),foreignObject.setAttribute("width","100%"),foreignObject.setAttribute("height","100%"),foreignObject.setAttribute("x","0"),foreignObject.setAttribute("y","0"),foreignObject.setAttribute("externalResourcesRequired","true"),svg.appendChild(foreignObject),foreignObject.appendChild(node),svgToDataURL(svg)}const isInstanceOfElement=(node,instance)=>{if(node instanceof instance)return!0;const nodePrototype=Object.getPrototypeOf(node);return nodePrototype===null?!1:nodePrototype.constructor.name===instance.name||isInstanceOfElement(nodePrototype,instance)};function formatCSSText(style){const content=style.getPropertyValue("content");return`${style.cssText} content: '${content.replace(/'|"/g,"")}';`}function formatCSSProperties(style){return toArray(style).map(name=>{const value=style.getPropertyValue(name),priority=style.getPropertyPriority(name);return`${name}: ${value}${priority?" !important":""};`}).join(" ")}function getPseudoElementStyle(className,pseudo,style){const selector=`.${className}:${pseudo}`,cssText=style.cssText?formatCSSText(style):formatCSSProperties(style);return document.createTextNode(`${selector}{${cssText}}`)}function clonePseudoElement(nativeNode,clonedNode,pseudo){const style=window.getComputedStyle(nativeNode,pseudo),content=style.getPropertyValue("content");if(content===""||content==="none")return;const className=uuid();try{clonedNode.className=`${clonedNode.className} ${className}`}catch{return}const styleElement=document.createElement("style");styleElement.appendChild(getPseudoElementStyle(className,pseudo,style)),clonedNode.appendChild(styleElement)}function clonePseudoElements(nativeNode,clonedNode){clonePseudoElement(nativeNode,clonedNode,":before"),clonePseudoElement(nativeNode,clonedNode,":after")}const WOFF="application/font-woff",JPEG="image/jpeg",mimes={woff:WOFF,woff2:WOFF,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:JPEG,jpeg:JPEG,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function getExtension(url){const match=/\.([^./]*?)$/g.exec(url);return match?match[1]:""}function getMimeType(url){const extension=getExtension(url).toLowerCase();return mimes[extension]||""}function getContentFromDataUrl(dataURL){return dataURL.split(/,/)[1]}function isDataUrl(url){return url.search(/^(data:)/)!==-1}function makeDataUrl(content,mimeType){return`data:${mimeType};base64,${content}`}async function fetchAsDataURL(url,init,process2){const res=await fetch(url,init);if(res.status===404)throw new Error(`Resource "${res.url}" not found`);const blob=await res.blob();return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onerror=reject,reader.onloadend=()=>{try{resolve(process2({res,result:reader.result}))}catch(error){reject(error)}},reader.readAsDataURL(blob)})}const cache={};function getCacheKey(url,contentType,includeQueryParams){let key=url.replace(/\?.*/,"");return includeQueryParams&&(key=url),/ttf|otf|eot|woff2?/i.test(key)&&(key=key.replace(/.*\//,"")),contentType?`[${contentType}]${key}`:key}async function resourceToDataURL(resourceUrl,contentType,options){const cacheKey=getCacheKey(resourceUrl,contentType,options.includeQueryParams);if(cache[cacheKey]!=null)return cache[cacheKey];options.cacheBust&&(resourceUrl+=(/\?/.test(resourceUrl)?"&":"?")+new Date().getTime());let dataURL;try{const content=await fetchAsDataURL(resourceUrl,options.fetchRequestInit,({res,result})=>(contentType||(contentType=res.headers.get("Content-Type")||""),getContentFromDataUrl(result)));dataURL=makeDataUrl(content,contentType)}catch(error){dataURL=options.imagePlaceholder||"";let msg=`Failed to fetch resource: ${resourceUrl}`;error&&(msg=typeof error=="string"?error:error.message),msg&&console.warn(msg)}return cache[cacheKey]=dataURL,dataURL}async function cloneCanvasElement(canvas){const dataURL=canvas.toDataURL();return dataURL==="data:,"?canvas.cloneNode(!1):createImage(dataURL)}async function cloneVideoElement(video,options){if(video.currentSrc){const canvas=document.createElement("canvas"),ctx=canvas.getContext("2d");canvas.width=video.clientWidth,canvas.height=video.clientHeight,ctx?.drawImage(video,0,0,canvas.width,canvas.height);const dataURL2=canvas.toDataURL();return createImage(dataURL2)}const poster=video.poster,contentType=getMimeType(poster),dataURL=await resourceToDataURL(poster,contentType,options);return createImage(dataURL)}async function cloneIFrameElement(iframe){var _a;try{if(!((_a=iframe?.contentDocument)===null||_a===void 0)&&_a.body)return await cloneNode(iframe.contentDocument.body,{},!0)}catch{}return iframe.cloneNode(!1)}async function cloneSingleNode(node,options){return isInstanceOfElement(node,HTMLCanvasElement)?cloneCanvasElement(node):isInstanceOfElement(node,HTMLVideoElement)?cloneVideoElement(node,options):isInstanceOfElement(node,HTMLIFrameElement)?cloneIFrameElement(node):node.cloneNode(!1)}const isSlotElement=node=>node.tagName!=null&&node.tagName.toUpperCase()==="SLOT";async function cloneChildren(nativeNode,clonedNode,options){var _a,_b;let children=[];return isSlotElement(nativeNode)&&nativeNode.assignedNodes?children=toArray(nativeNode.assignedNodes()):isInstanceOfElement(nativeNode,HTMLIFrameElement)&&(!((_a=nativeNode.contentDocument)===null||_a===void 0)&&_a.body)?children=toArray(nativeNode.contentDocument.body.childNodes):children=toArray(((_b=nativeNode.shadowRoot)!==null&&_b!==void 0?_b:nativeNode).childNodes),children.length===0||isInstanceOfElement(nativeNode,HTMLVideoElement)||await children.reduce((deferred,child)=>deferred.then(()=>cloneNode(child,options)).then(clonedChild=>{clonedChild&&clonedNode.appendChild(clonedChild)}),Promise.resolve()),clonedNode}function cloneCSSStyle(nativeNode,clonedNode){const targetStyle=clonedNode.style;if(!targetStyle)return;const sourceStyle=window.getComputedStyle(nativeNode);sourceStyle.cssText?(targetStyle.cssText=sourceStyle.cssText,targetStyle.transformOrigin=sourceStyle.transformOrigin):toArray(sourceStyle).forEach(name=>{let value=sourceStyle.getPropertyValue(name);name==="font-size"&&value.endsWith("px")&&(value=`${Math.floor(parseFloat(value.substring(0,value.length-2)))-.1}px`),isInstanceOfElement(nativeNode,HTMLIFrameElement)&&name==="display"&&value==="inline"&&(value="block"),name==="d"&&clonedNode.getAttribute("d")&&(value=`path(${clonedNode.getAttribute("d")})`),targetStyle.setProperty(name,value,sourceStyle.getPropertyPriority(name))})}function cloneInputValue(nativeNode,clonedNode){isInstanceOfElement(nativeNode,HTMLTextAreaElement)&&(clonedNode.innerHTML=nativeNode.value),isInstanceOfElement(nativeNode,HTMLInputElement)&&clonedNode.setAttribute("value",nativeNode.value)}function cloneSelectValue(nativeNode,clonedNode){if(isInstanceOfElement(nativeNode,HTMLSelectElement)){const clonedSelect=clonedNode,selectedOption=Array.from(clonedSelect.children).find(child=>nativeNode.value===child.getAttribute("value"));selectedOption&&selectedOption.setAttribute("selected","")}}function decorate(nativeNode,clonedNode){return isInstanceOfElement(clonedNode,Element)&&(cloneCSSStyle(nativeNode,clonedNode),clonePseudoElements(nativeNode,clonedNode),cloneInputValue(nativeNode,clonedNode),cloneSelectValue(nativeNode,clonedNode)),clonedNode}async function ensureSVGSymbols(clone,options){const uses=clone.querySelectorAll?clone.querySelectorAll("use"):[];if(uses.length===0)return clone;const processedDefs={};for(let i=0;i<uses.length;i++){const id=uses[i].getAttribute("xlink:href");if(id){const exist=clone.querySelector(id),definition=document.querySelector(id);!exist&&definition&&!processedDefs[id]&&(processedDefs[id]=await cloneNode(definition,options,!0))}}const nodes=Object.values(processedDefs);if(nodes.length){const ns="http://www.w3.org/1999/xhtml",svg=document.createElementNS(ns,"svg");svg.setAttribute("xmlns",ns),svg.style.position="absolute",svg.style.width="0",svg.style.height="0",svg.style.overflow="hidden",svg.style.display="none";const defs=document.createElementNS(ns,"defs");svg.appendChild(defs);for(let i=0;i<nodes.length;i++)defs.appendChild(nodes[i]);clone.appendChild(svg)}return clone}async function cloneNode(node,options,isRoot){return!isRoot&&options.filter&&!options.filter(node)?null:Promise.resolve(node).then(clonedNode=>cloneSingleNode(clonedNode,options)).then(clonedNode=>cloneChildren(node,clonedNode,options)).then(clonedNode=>decorate(node,clonedNode)).then(clonedNode=>ensureSVGSymbols(clonedNode,options))}const URL_REGEX=/url\((['"]?)([^'"]+?)\1\)/g,URL_WITH_FORMAT_REGEX=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,FONT_SRC_REGEX=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function toRegex(url){const escaped=url.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${escaped})(['"]?\\))`,"g")}function parseURLs(cssText){const urls=[];return cssText.replace(URL_REGEX,(raw,quotation,url)=>(urls.push(url),raw)),urls.filter(url=>!isDataUrl(url))}async function embed(cssText,resourceURL,baseURL,options,getContentFromUrl){try{const resolvedURL=baseURL?resolveUrl(resourceURL,baseURL):resourceURL,contentType=getMimeType(resourceURL);let dataURL;return getContentFromUrl||(dataURL=await resourceToDataURL(resolvedURL,contentType,options)),cssText.replace(toRegex(resourceURL),`$1${dataURL}$3`)}catch{}return cssText}function filterPreferredFontFormat(str,{preferredFontFormat}){return preferredFontFormat?str.replace(FONT_SRC_REGEX,match=>{for(;;){const[src,,format]=URL_WITH_FORMAT_REGEX.exec(match)||[];if(!format)return"";if(format===preferredFontFormat)return`src: ${src};`}}):str}function shouldEmbed(url){return url.search(URL_REGEX)!==-1}async function embedResources(cssText,baseUrl,options){if(!shouldEmbed(cssText))return cssText;const filteredCSSText=filterPreferredFontFormat(cssText,options);return parseURLs(filteredCSSText).reduce((deferred,url)=>deferred.then(css=>embed(css,url,baseUrl,options)),Promise.resolve(filteredCSSText))}async function embedProp(propName,node,options){var _a;const propValue=(_a=node.style)===null||_a===void 0?void 0:_a.getPropertyValue(propName);if(propValue){const cssString=await embedResources(propValue,null,options);return node.style.setProperty(propName,cssString,node.style.getPropertyPriority(propName)),!0}return!1}async function embedBackground(clonedNode,options){await embedProp("background",clonedNode,options)||await embedProp("background-image",clonedNode,options),await embedProp("mask",clonedNode,options)||await embedProp("mask-image",clonedNode,options)}async function embedImageNode(clonedNode,options){const isImageElement=isInstanceOfElement(clonedNode,HTMLImageElement);if(!(isImageElement&&!isDataUrl(clonedNode.src))&&!(isInstanceOfElement(clonedNode,SVGImageElement)&&!isDataUrl(clonedNode.href.baseVal)))return;const url=isImageElement?clonedNode.src:clonedNode.href.baseVal,dataURL=await resourceToDataURL(url,getMimeType(url),options);await new Promise((resolve,reject)=>{clonedNode.onload=resolve,clonedNode.onerror=reject;const image=clonedNode;image.decode&&(image.decode=resolve),image.loading==="lazy"&&(image.loading="eager"),isImageElement?(clonedNode.srcset="",clonedNode.src=dataURL):clonedNode.href.baseVal=dataURL})}async function embedChildren(clonedNode,options){const deferreds=toArray(clonedNode.childNodes).map(child=>embedImages(child,options));await Promise.all(deferreds).then(()=>clonedNode)}async function embedImages(clonedNode,options){isInstanceOfElement(clonedNode,Element)&&(await embedBackground(clonedNode,options),await embedImageNode(clonedNode,options),await embedChildren(clonedNode,options))}function applyStyle(node,options){const{style}=node;options.backgroundColor&&(style.backgroundColor=options.backgroundColor),options.width&&(style.width=`${options.width}px`),options.height&&(style.height=`${options.height}px`);const manual=options.style;return manual!=null&&Object.keys(manual).forEach(key=>{style[key]=manual[key]}),node}const cssFetchCache={};async function fetchCSS(url){let cache2=cssFetchCache[url];if(cache2!=null)return cache2;const cssText=await(await fetch(url)).text();return cache2={url,cssText},cssFetchCache[url]=cache2,cache2}async function embedFonts(data,options){let cssText=data.cssText;const regexUrl=/url\(["']?([^"')]+)["']?\)/g,loadFonts=(cssText.match(/url\([^)]+\)/g)||[]).map(async loc=>{let url=loc.replace(regexUrl,"$1");return url.startsWith("https://")||(url=new URL(url,data.url).href),fetchAsDataURL(url,options.fetchRequestInit,({result})=>(cssText=cssText.replace(loc,`url(${result})`),[loc,result]))});return Promise.all(loadFonts).then(()=>cssText)}function parseCSS(source){if(source==null)return[];const result=[],commentsRegex=/(\/\*[\s\S]*?\*\/)/gi;let cssText=source.replace(commentsRegex,"");const keyframesRegex=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const matches=keyframesRegex.exec(cssText);if(matches===null)break;result.push(matches[0])}cssText=cssText.replace(keyframesRegex,"");const importRegex=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,combinedCSSRegex="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",unifiedRegex=new RegExp(combinedCSSRegex,"gi");for(;;){let matches=importRegex.exec(cssText);if(matches===null){if(matches=unifiedRegex.exec(cssText),matches===null)break;importRegex.lastIndex=unifiedRegex.lastIndex}else unifiedRegex.lastIndex=importRegex.lastIndex;result.push(matches[0])}return result}async function getCSSRules(styleSheets,options){const ret=[],deferreds=[];return styleSheets.forEach(sheet=>{if("cssRules"in sheet)try{toArray(sheet.cssRules||[]).forEach((item,index)=>{if(item.type===CSSRule.IMPORT_RULE){let importIndex=index+1;const url=item.href,deferred=fetchCSS(url).then(metadata=>embedFonts(metadata,options)).then(cssText=>parseCSS(cssText).forEach(rule=>{try{sheet.insertRule(rule,rule.startsWith("@import")?importIndex+=1:sheet.cssRules.length)}catch(error){console.error("Error inserting rule from remote css",{rule,error})}})).catch(e=>{console.error("Error loading remote css",e.toString())});deferreds.push(deferred)}})}catch(e){const inline=styleSheets.find(a=>a.href==null)||document.styleSheets[0];sheet.href!=null&&deferreds.push(fetchCSS(sheet.href).then(metadata=>embedFonts(metadata,options)).then(cssText=>parseCSS(cssText).forEach(rule=>{inline.insertRule(rule,sheet.cssRules.length)})).catch(err=>{console.error("Error loading remote stylesheet",err)})),console.error("Error inlining remote css file",e)}}),Promise.all(deferreds).then(()=>(styleSheets.forEach(sheet=>{if("cssRules"in sheet)try{toArray(sheet.cssRules||[]).forEach(item=>{ret.push(item)})}catch(e){console.error(`Error while reading CSS rules from ${sheet.href}`,e)}}),ret))}function getWebFontRules(cssRules){return cssRules.filter(rule=>rule.type===CSSRule.FONT_FACE_RULE).filter(rule=>shouldEmbed(rule.style.getPropertyValue("src")))}async function parseWebFontRules(node,options){if(node.ownerDocument==null)throw new Error("Provided element is not within a Document");const styleSheets=toArray(node.ownerDocument.styleSheets),cssRules=await getCSSRules(styleSheets,options);return getWebFontRules(cssRules)}async function getWebFontCSS(node,options){const rules=await parseWebFontRules(node,options);return(await Promise.all(rules.map(rule=>{const baseUrl=rule.parentStyleSheet?rule.parentStyleSheet.href:null;return embedResources(rule.cssText,baseUrl,options)}))).join(`
2
+ `)}async function embedWebFonts(clonedNode,options){const cssText=options.fontEmbedCSS!=null?options.fontEmbedCSS:options.skipFonts?null:await getWebFontCSS(clonedNode,options);if(cssText){const styleNode=document.createElement("style"),sytleContent=document.createTextNode(cssText);styleNode.appendChild(sytleContent),clonedNode.firstChild?clonedNode.insertBefore(styleNode,clonedNode.firstChild):clonedNode.appendChild(styleNode)}}async function toSvg(node,options={}){const{width,height}=getImageSize(node,options),clonedNode=await cloneNode(node,options,!0);return await embedWebFonts(clonedNode,options),await embedImages(clonedNode,options),applyStyle(clonedNode,options),await nodeToDataURL(clonedNode,width,height)}async function toCanvas(node,options={}){const{width,height}=getImageSize(node,options),svg=await toSvg(node,options),img=await createImage(svg),canvas=document.createElement("canvas"),context=canvas.getContext("2d"),ratio=options.pixelRatio||getPixelRatio(),canvasWidth=options.canvasWidth||width,canvasHeight=options.canvasHeight||height;return canvas.width=canvasWidth*ratio,canvas.height=canvasHeight*ratio,options.skipAutoScale||checkCanvasDimensions(canvas),canvas.style.width=`${canvasWidth}`,canvas.style.height=`${canvasHeight}`,options.backgroundColor&&(context.fillStyle=options.backgroundColor,context.fillRect(0,0,canvas.width,canvas.height)),context.drawImage(img,0,0,canvas.width,canvas.height),canvas}async function toPng(node,options={}){return(await toCanvas(node,options)).toDataURL()}export{toCanvas,toPng,toSvg};