PageSourceSearch

https://bkmaxwell.com/assets/scripts/formviewer/formviewer.min.js

js bkmaxwell.com collected 2026-10-05 07:13:47 UTC 192,409 bytes, 1 lines download raw bytes

vendor: 4,382 bytes, line 1
1var FormViewer=function(){"use strict";function e(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let t={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};function r(e){t=e}const s={exec:()=>null};function n(e,t=""){let r="string"==typeof e?e:e.source;const s={replace:(e,t)=>{let n="string"==typeof t?t:t.source;return n=n.replace(i.caret,"$1"),r=r.replace(e,n),s},getRegex:()=>new RegExp(r,t)};return s}const i={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[\t ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},o=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,a=/(?:[*+-]|\d{1,9}[.)])/,l=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,c=n(l).replace(/bull/g,a).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),d=n(l).replace(/bull/g,a).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),u=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,p=/(?!\s*\])(?:\\.|[^\[\]\\])+/,h=n(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",p).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),m=n(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,a).getRegex(),g="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",f=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,b=n("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>
vendor: 9,107 bytes, line 1
1)[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ \t]*)+\\n|$))","i").replace("comment",f).replace("tag",g).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),y=n(u).replace("hr",o).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",g).getRegex(),v={blockquote:n(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",y).getRegex(),code:/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,def:h,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:o,html:b,lheading:c,list:m,newline:/^(?:[ \t]*(?:\n|$))+/,paragraph:y,table:s,text:/^[^\n]+/},k=n("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",o).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3}\t)[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",g).getRegex(),w={...v,lheading:d,table:k,paragraph:n(u).replace("hr",o).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",k).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",g).getRegex()},x={...v,html:n("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",f).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:s,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:n(u).replace("hr",o).replace("heading"," *#{1,6} *[^\n]").replace("lheading",c).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},_=/^( {2,}|\\)\n(?!\s*$)/,E=/[\p{P}\p{S}]/u,L=/[\s\p{P}\p{S}]/u,C=/[^\s\p{P}\p{S}]/u,R=n(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,L).getRegex(),T=/(?!~)[\p{P}\p{S}]/u,S=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,q=n(S,"u").replace(/punct/g,E).getRegex(),M=n(S,"u").replace(/punct/g,T).getRegex(),$="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",N=n($,"gu").replace(/notPunctSpace/g,C).replace(/punctSpace/g,L).replace(/punct/g,E).getRegex(),I=n($,"gu").replace(/notPunctSpace/g,/(?:[^\s\p{P}\p{S}]|~)/u).replace(/punctSpace/g,/(?!~)[\s\p{P}\p{S}]/u).replace(/punct/g,T).getRegex(),A=n("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,C).replace(/punctSpace/g,L).replace(/punct/g,E).getRegex(),O=n(/\\(punct)/,"gu").replace(/punct/g,E).getRegex(),P=n(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),H=n(f).replace("(?:--\x3e|$)","--\x3e").getRegex(),D=n("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",H).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),U=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,G=n(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",U).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),j=n(/^!?\[(label)\]\[(ref)\]/).replace("label",U).replace("ref",p).getRegex(),z=n(/^!?\[(ref)\](?:\[\])?/).replace("ref",p).getRegex(),B={_backpedal:s,anyPunctuation:O,autolink:P,blockSkip:/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,br:_,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:s,emStrongLDelim:q,emStrongRDelimAst:N,emStrongRDelimUnd:A,escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,link:G,nolink:z,punctuation:R,reflink:j,reflinkSearch:n("reflink|nolink(?!\\()","g").replace("reflink",j).replace("nolink",z).getRegex(),tag:D,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:s},F={...B,link:n(/^!?\[(label)\]\((.*?)\)/).replace("label",U).getRegex(),reflink:n(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",U).getRegex()},J={...B,emStrongRDelimAst:I,emStrongLDelim:M,url:n(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},V={...J,br:n(_).replace("{2,}","*").getRegex(),text:n(J.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Y={normal:v,gfm:w,pedantic:x},W={normal:B,gfm:J,breaks:V,pedantic:F},Z={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Q=e=>Z[e];function X(e,t){if(t){if(i.escapeTest.test(e))return e.replace(i.escapeReplace,Q)}else if(i.escapeTestNoEncode.test(e))return e.replace(i.escapeReplaceNoEncode,Q);return e}function K(e){try{e=encodeURI(e).replace(i.percentDecode,"%")}catch{return null}return e}function ee(e,t){const r=e.replace(i.findPipe,((e,t,r)=>{let s=!1,n=t;for(;--n>=0&&"\\"===r[n];)s=!s;return s?"|":" |"})).split(i.splitPipe);let s=0;if(r[0].trim()||r.shift(),r.length>0&&!r.at(-1)?.trim()&&r.pop(),t)if(r.length>t)r.splice(t);else for(;r.length<t;)r.push("");for(;s<r.length;s++)r[s]=r[s].trim().replace(i.slashPipe,"|");return r}function te(e,t,r){const s=e.length;if(0===s)return"";let n=0;for(;n<s;){if(e.charAt(s-n-1)!==t)break;n++}return e.slice(0,s-n)}function re(e,t,r,s,n){const i=t.href,o=t.title||null,a=e[1].replace(n.other.outputLinkReplace,"$1");s.state.inLink=!0;const l={type:"!"===e[0].charAt(0)?"image":"link",raw:r,href:i,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,l}class se{options;rules;lexer;constructor(e){this.options=e||t}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:te(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],r=function(e,t,r){const s=e.match(r.other.indentCodeCompensation);if(null===s)return t;const n=s[1];return t.split("\n").map((e=>{const t=e.match(r.other.beginningSpace);if(null===t)return e;const[s]=t;return s.length>=n.length?e.slice(n.length):e})).join("\n")}(e,t[3]||"",this.rules);return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){const t=te(e,"#");this.options.pedantic?e=t.trim():t&&!this.rules.other.endingSpaceChar.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:te(t[0],"\n")}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){let e=te(t[0],"\n").split("\n"),r="",s="";const n=[];for(;e.length>0;){let t=!1;const i=[];let o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))i.push(e[o]),t=!0;else{if(t)break;
vendor: 5,938 bytes, line 1
1i.push(e[o])}e=e.slice(o);const a=i.join("\n"),l=a.replace(this.rules.other.blockquoteSetextReplace,"\n    $1").replace(this.rules.other.blockquoteSetextReplace2,"");r=r?`${r}\n${a}`:a,s=s?`${s}\n${l}`:l;const c=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(l,n,!0),this.lexer.state.top=c,0===e.length)break;const d=n.at(-1);if("code"===d?.type)break;if("blockquote"===d?.type){const t=d,i=t.raw+"\n"+e.join("\n"),o=this.blockquote(i);n[n.length-1]=o,r=r.substring(0,r.length-t.raw.length)+o.raw,s=s.substring(0,s.length-t.text.length)+o.text;break}if("list"!==d?.type);else{const t=d,i=t.raw+"\n"+e.join("\n"),o=this.list(i);n[n.length-1]=o,r=r.substring(0,r.length-d.raw.length)+o.raw,s=s.substring(0,s.length-t.raw.length)+o.raw,e=i.substring(n.at(-1).raw.length).split("\n")}}return{type:"blockquote",raw:r,tokens:n,text:s}}}list(e){let t=this.rules.block.list.exec(e);if(t){let r=t[1].trim();const s=r.length>1,n={type:"list",raw:"",ordered:s,start:s?+r.slice(0,-1):"",loose:!1,items:[]};r=s?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=s?r:"[*+-]");const i=this.rules.other.listItemRegex(r);let o=!1;for(;e;){let r=!1,s="",a="";if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;s=t[0],e=e.substring(s.length);let l=t[2].split("\n",1)[0].replace(this.rules.other.listReplaceTabs,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],d=!l.trim(),u=0;if(this.options.pedantic?(u=2,a=l.trimStart()):d?u=t[1].length+1:(u=t[2].search(this.rules.other.nonSpaceChar),u=u>4?1:u,a=l.slice(u),u+=t[1].length),d&&this.rules.other.blankLine.test(c)&&(s+=c+"\n",e=e.substring(c.length+1),r=!0),!r){const t=this.rules.other.nextBulletRegex(u),r=this.rules.other.hrRegex(u),n=this.rules.other.fencesBeginRegex(u),i=this.rules.other.headingBeginRegex(u),o=this.rules.other.htmlBeginRegex(u);for(;e;){const p=e.split("\n",1)[0];let h;if(c=p,this.options.pedantic?(c=c.replace(this.rules.other.listReplaceNesting,"  "),h=c):h=c.replace(this.rules.other.tabCharGlobal,"    "),n.test(c))break;if(i.test(c))break;if(o.test(c))break;if(t.test(c))break;if(r.test(c))break;if(h.search(this.rules.other.nonSpaceChar)>=u||!c.trim())a+="\n"+h.slice(u);else{if(d)break;if(l.replace(this.rules.other.tabCharGlobal,"    ").search(this.rules.other.nonSpaceChar)>=4)break;if(n.test(l))break;if(i.test(l))break;if(r.test(l))break;a+="\n"+c}d||c.trim()||(d=!0),s+=p+"\n",e=e.substring(p.length+1),l=h.slice(u)}}n.loose||(o?n.loose=!0:this.rules.other.doubleBlankLine.test(s)&&(o=!0));let p,h=null;this.options.gfm&&(h=this.rules.other.listIsTask.exec(a),h&&(p="[ ] "!==h[0],a=a.replace(this.rules.other.listReplaceTask,""))),n.items.push({type:"list_item",raw:s,task:!!h,checked:p,loose:!1,text:a,tokens:[]}),n.raw+=s}const a=n.items.at(-1);if(!a)return;a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd(),n.raw=n.raw.trimEnd();for(let e=0;e<n.items.length;e++)if(this.lexer.state.top=!1,n.items[e].tokens=this.lexer.blockTokens(n.items[e].text,[]),!n.loose){const t=n.items[e].tokens.filter((e=>"space"===e.type)),r=t.length>0&&t.some((e=>this.rules.other.anyLine.test(e.raw)));n.loose=r}if(n.loose)for(let e=0;e<n.items.length;e++)n.items[e].loose=!0;return n}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:r,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!this.rules.other.tableDelimiter.test(t[2]))return;const r=ee(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(r.length===s.length){for(const e of s)this.rules.other.tableAlignRight.test(e)?i.align.push("right"):this.rules.other.tableAlignCenter.test(e)?i.align.push("center"):this.rules.other.tableAlignLeft.test(e)?i.align.push("left"):i.align.push(null);for(let e=0;e<r.length;e++)i.header.push({text:r[e],tokens:this.lexer.inline(r[e]),header:!0,align:i.align[e]});for(const e of n)i.rows.push(ee(e,i.header.length).map(((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:i.align[t]}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;const t=te(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}
vendor: 4,158 bytes, line 1
1else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let r=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])r++;else if(e[s]===t[1]&&(r--,r<0))return s;return r>0?-2:-1}(t[2],"()");if(-2===e)return;if(e>-1){const r=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,r).trim(),t[3]=""}}let r=t[2],s="";if(this.options.pedantic){const e=this.rules.other.pedanticHrefTitle.exec(r);e&&(r=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(r=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?r.slice(1):r.slice(1,-1)),re(t,{href:r?r.replace(this.rules.inline.anyPunctuation,"$1"):r,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer,this.rules)}}reflink(e,t){let r;if((r=this.rules.inline.reflink.exec(e))||(r=this.rules.inline.nolink.exec(e))){const e=t[(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," ").toLowerCase()];if(!e){const e=r[0].charAt(0);return{type:"text",raw:e,text:e}}return re(r,e,r[0],this.lexer,this.rules)}}emStrong(e,t,r=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&r.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!r||this.rules.inline.punctuation.exec(r)){const r=[...s[0]].length-1;let n,i,o=r,a=0;const l="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(l.lastIndex=0,t=t.slice(-1*e.length+r);null!=(s=l.exec(t));){if(n=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!n)continue;if(i=[...n].length,s[3]||s[4]){o+=i;continue}if((s[5]||s[6])&&r%3&&!((r+i)%3)){a+=i;continue}if(o-=i,o>0)continue;i=Math.min(i,i+o+a);const t=[...s[0]][0].length,l=e.slice(0,r+s.index+t+i);if(Math.min(r,i)%2){const e=l.slice(1,-1);return{type:"em",raw:l,text:e,tokens:this.lexer.inlineTokens(e)}}const c=l.slice(2,-2);return{type:"strong",raw:l,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal," ");const r=this.rules.other.nonSpaceChar.test(e),s=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return r&&s&&(e=e.substring(1,e.length-1)),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,r;return"@"===t[2]?(e=t[1],r="mailto:"+e):(e=t[1],r=e),{type:"link",raw:t[0],text:e,href:r,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,r;if("@"===t[2])e=t[0],r="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=t[0],r="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:r,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){const e=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:e}}}}class ne{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||t,this.options.tokenizer=this.options.tokenizer||new se,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const r={other:i,block:Y.normal,inline:W.normal};this.options.pedantic?(r.block=Y.pedantic,r.inline=W.pedantic):this.options.gfm&&(r.block=Y.gfm,this.options.breaks?r.inline=W.breaks:r.inline=W.gfm),this.tokenizer.rules=r}static get rules(){return{block:Y,inline:W}}static lex(e,t){return new ne(t).lex(e)}static lexInline(e,t){return new ne(t).inlineTokens(e)}lex(e){e=e.replace(i.carriageReturn,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],r=!1){for(this.options.pedantic&&(e=e.replace(i.tabCharGlobal,"    ").replace(i.space
vendor: 4,256 bytes, line 1
1Line,""));e;){let s;if(this.options.extensions?.block?.some((r=>!!(s=r.call({lexer:this},e,t))&&(e=e.substring(s.raw.length),t.push(s),!0))))continue;if(s=this.tokenizer.space(e)){e=e.substring(s.raw.length);const r=t.at(-1);1===s.raw.length&&void 0!==r?r.raw+="\n":t.push(s);continue}if(s=this.tokenizer.code(e)){e=e.substring(s.raw.length);const r=t.at(-1);"paragraph"===r?.type||"text"===r?.type?(r.raw+="\n"+s.raw,r.text+="\n"+s.text,this.inlineQueue.at(-1).src=r.text):t.push(s);continue}if(s=this.tokenizer.fences(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.heading(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.hr(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.blockquote(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.list(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.html(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.def(e)){e=e.substring(s.raw.length);const r=t.at(-1);"paragraph"===r?.type||"text"===r?.type?(r.raw+="\n"+s.raw,r.text+="\n"+s.raw,this.inlineQueue.at(-1).src=r.text):this.tokens.links[s.tag]||(this.tokens.links[s.tag]={href:s.href,title:s.title});continue}if(s=this.tokenizer.table(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.lheading(e)){e=e.substring(s.raw.length),t.push(s);continue}let n=e;if(this.options.extensions?.startBlock){let t=1/0;const r=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},r),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(n=e.substring(0,t+1))}if(this.state.top&&(s=this.tokenizer.paragraph(n))){const i=t.at(-1);r&&"paragraph"===i?.type?(i.raw+="\n"+s.raw,i.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(s),r=n.length!==e.length,e=e.substring(s.raw.length)}else if(s=this.tokenizer.text(e)){e=e.substring(s.raw.length);const r=t.at(-1);"text"===r?.type?(r.raw+="\n"+s.raw,r.text+="\n"+s.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(s)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let r=e,s=null;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(s=this.tokenizer.rules.inline.reflinkSearch.exec(r));)e.includes(s[0].slice(s[0].lastIndexOf("[")+1,-1))&&(r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(s=this.tokenizer.rules.inline.anyPunctuation.exec(r));)r=r.slice(0,s.index)+"++"+r.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;null!=(s=this.tokenizer.rules.inline.blockSkip.exec(r));)r=r.slice(0,s.index)+"["+"a".repeat(s[0].length-2)+"]"+r.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);let n=!1,i="";for(;e;){let s;if(n||(i=""),n=!1,this.options.extensions?.inline?.some((r=>!!(s=r.call({lexer:this},e,t))&&(e=e.substring(s.raw.length),t.push(s),!0))))continue;if(s=this.tokenizer.escape(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.tag(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.link(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(s.raw.length);const r=t.at(-1);"text"===s.type&&"text"===r?.type?(r.raw+=s.raw,r.text+=s.text):t.push(s);continue}if(s=this.tokenizer.emStrong(e,r,i)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.codespan(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.br(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.del(e)){e=e.substring(s.raw.length),t.push(s);continue}if(s=this.tokenizer.autolink(e)){e=e.substring(s.raw.length),t.push(s);continue}if(!this.state.inLink&&(s=this.tokenizer.url(e))){e=e.substring(s.raw.length),t.push(s);continue}let o=e;if(this.options.extensions?.startInline){let t=1/0;const r=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},r),"number"==typeof s&&s>=0&&(t=Math.min(t,s))}
vendor: 4,339 bytes, line 1
1)),t<1/0&&t>=0&&(o=e.substring(0,t+1))}if(s=this.tokenizer.inlineText(o)){e=e.substring(s.raw.length),"_"!==s.raw.slice(-1)&&(i=s.raw.slice(-1)),n=!0;const r=t.at(-1);"text"===r?.type?(r.raw+=s.raw,r.text+=s.text):t.push(s)}else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return t}}class ie{options;parser;constructor(e){this.options=e||t}space(e){return""}code({text:e,lang:t,escaped:r}){const s=(t||"").match(i.notSpaceStart)?.[0],n=e.replace(i.endingNewline,"")+"\n";return s?'<pre><code class="language-'+X(s)+'">'+(r?n:X(n,!0))+"</code></pre>\n":"<pre><code>"+(r?n:X(n,!0))+"</code></pre>\n"}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return"<hr>\n"}list(e){const t=e.ordered,r=e.start;let s="";for(let t=0;t<e.items.length;t++){const r=e.items[t];s+=this.listitem(r)}const n=t?"ol":"ul";return"<"+n+(t&&1!==r?' start="'+r+'"':"")+">\n"+s+"</"+n+">\n"}listitem(e){let t="";if(e.task){const r=this.checkbox({checked:!!e.checked});e.loose?"paragraph"===e.tokens[0]?.type?(e.tokens[0].text=r+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&"text"===e.tokens[0].tokens[0].type&&(e.tokens[0].tokens[0].text=r+" "+X(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:r+" ",text:r+" ",escaped:!0}):t+=r+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`<li>${t}</li>\n`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t="",r="";for(let t=0;t<e.header.length;t++)r+=this.tablecell(e.header[t]);t+=this.tablerow({text:r});let s="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];r="";for(let e=0;e<n.length;e++)r+=this.tablecell(n[e]);s+=this.tablerow({text:r})}return s&&(s=`<tbody>${s}</tbody>`),"<table>\n<thead>\n"+t+"</thead>\n"+s+"</table>\n"}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){const t=this.parser.parseInline(e.tokens),r=e.header?"th":"td";return(e.align?`<${r} align="${e.align}">`:`<${r}>`)+t+`</${r}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${X(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:r}){const s=this.parser.parseInline(r),n=K(e);if(null===n)return s;let i='<a href="'+(e=n)+'"';return t&&(i+=' title="'+X(t)+'"'),i+=">"+s+"</a>",i}image({href:e,title:t,text:r,tokens:s}){s&&(r=this.parser.parseInline(s,this.parser.textRenderer));const n=K(e);if(null===n)return X(r);let i=`<img src="${e=n}" alt="${r}"`;return t&&(i+=` title="${X(t)}"`),i+=">",i}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:X(e.text)}}class oe{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}}class ae{options;renderer;textRenderer;constructor(e){this.options=e||t,this.options.renderer=this.options.renderer||new ie,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new oe}static parse(e,t){return new ae(t).parse(e)}static parseInline(e,t){return new ae(t).parseInline(e)}parse(e,t=!0){let r="";for(let s=0;s<e.length;s++){const n=e[s];if(this.options.extensions?.renderers?.[n.type]){const e=n,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){r+=t||"";continue}}const i=n;switch(i.type){case"space":r+=this.renderer.space(i);continue;case"hr":r+=this.renderer.hr(i);continue;case"heading":r+=this.renderer.heading(i);continue;case"code":r+=this.renderer.code(i);continue;case"table":r+=this.renderer.table(i);continue;case"blockquote":r+=this.renderer.blockquote(i);continue;case"list":r+=this.renderer.list(i);continue;case"html":r+=this.renderer.html(i);continue;
vendor: 8,038 bytes, line 1
1case"paragraph":r+=this.renderer.paragraph(i);continue;case"text":{let n=i,o=this.renderer.text(n);for(;s+1<e.length&&"text"===e[s+1].type;)n=e[++s],o+="\n"+this.renderer.text(n);r+=t?this.renderer.paragraph({type:"paragraph",raw:o,text:o,tokens:[{type:"text",raw:o,text:o,escaped:!0}]}):o;continue}default:{const e='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return r}parseInline(e,t=this.renderer){let r="";for(let s=0;s<e.length;s++){const n=e[s];if(this.options.extensions?.renderers?.[n.type]){const e=this.options.extensions.renderers[n.type].call({parser:this},n);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(n.type)){r+=e||"";continue}}const i=n;switch(i.type){case"escape":case"text":r+=t.text(i);break;case"html":r+=t.html(i);break;case"link":r+=t.link(i);break;case"image":r+=t.image(i);break;case"strong":r+=t.strong(i);break;case"em":r+=t.em(i);break;case"codespan":r+=t.codespan(i);break;case"br":r+=t.br(i);break;case"del":r+=t.del(i);break;default:{const e='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return r}}class le{options;block;constructor(e){this.options=e||t}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}provideLexer(){return this.block?ne.lex:ne.lexInline}provideParser(){return this.block?ae.parse:ae.parseInline}}const ce=new class{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ae;Renderer=ie;TextRenderer=oe;Lexer=ne;Tokenizer=se;Hooks=le;constructor(...e){this.use(...e)}walkTokens(e,t){let r=[];for(const s of e)switch(r=r.concat(t.call(this,s)),s.type){case"table":{const e=s;for(const s of e.header)r=r.concat(this.walkTokens(s.tokens,t));for(const s of e.rows)for(const e of s)r=r.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=s;r=r.concat(this.walkTokens(e.items,t));break}default:{const e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((s=>{const n=e[s].flat(1/0);r=r.concat(this.walkTokens(n,t))})):e.tokens&&(r=r.concat(this.walkTokens(e.tokens,t)))}}return r}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const r={...e};if(r.async=this.defaults.async||r.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const r=t.renderers[e.name];t.renderers[e.name]=r?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=r.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const r=t[e.level];r?r.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),r.extensions=t),e.renderer){const t=this.defaults.renderer||new ie(this.defaults);for(const r in e.renderer){if(!(r in t))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;const s=r,n=e.renderer[s],i=t[s];t[s]=(...e)=>{let r=n.apply(t,e);return!1===r&&(r=i.apply(t,e)),r||""}}r.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new se(this.defaults);for(const r in e.tokenizer){if(!(r in t))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;const s=r,n=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let r=n.apply(t,e);return!1===r&&(r=i.apply(t,e)),r}}r.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const r in e.hooks){if(!(r in t))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;const s=r,n=e.hooks[s],i=t[s];le.passThroughHooks.has(r)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(n.call(t,e)).then((e=>i.call(t,e)));const r=n.call(t,e);return i.call(t,r)}:t[s]=(...e)=>{let r=n.apply(t,e);return!1===r&&(r=i.apply(t,e)),r}}r.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;r.walkTokens=function(e){let r=[];return r.push(s.call(this,e)),t&&(r=r.concat(t.call(this,e))),r}}this.defaults={...this.defaults,...r}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ae.parse(e,t??this.defaults)}parseMarkdown(e){return(t,r)=>{const s={...r},n={...this.defaults,...s},i=this.onError(!!n.silent,!!n.async);if(!0===this.defaults.async&&!1===s.async)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(null==t)return i(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof t)return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));n.hooks&&(n.hooks.options=n,n.hooks.block=e);const o=n.hooks?n.hooks.provideLexer():e?ne.lex:ne.lexInline,a=n.hooks?n.hooks.provideParser():e?ae.parse:ae.parseInline;if(n.async)return Promise.resolve(n.hooks?n.hooks.preprocess(t):t).then((e=>o(e,n))).then((e=>n.hooks?n.hooks.processAllTokens(e):e)).then((e=>n.walkTokens?Promise.all(this.walkTokens(e,n.walkTokens)).then((()=>e)):e)).then((e=>a(e,n))).then((e=>n.hooks?n.hooks.postprocess(e):e)).catch(i);try{n.hooks&&(t=n.hooks.preprocess(t));let e=o(t,n);n.hooks&&(e=n.hooks.processAllTokens(e)),n.walkTokens&&this.walkTokens(e,n.walkTokens);let r=a(e,n);return n.hooks&&(r=n.hooks.postprocess(r)),r}catch(e){return i(e)}}}onError(e,t){return r=>{if(r.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+X(r.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(r);throw r}}};function de(e,t){return ce.parse(e,t)}de.options=de.setOptions=function(e){return ce.setOptions(e),de.defaults=ce.defaults,r(de.defaults),de},de.getDefaults=e,de.defaults=t,de.use=function(...e){return ce.use(...e),de.defaults=ce.defaults,r(de.defaults),de},de.walkTokens=function(e,t){return ce.walkTokens(e,t)},de.parseInline=ce.parseInline,de.Parser=ae,de.parser=ae.parse,de.Renderer=ie,de.TextRenderer=oe,de.Lexer=ne,de.lexer=ne.lex,de.Tokenizer=se,de.Hooks=le,de.parse=de,de.options,de.setOptions,de.use,de.walkTokens,de.parseInline,ae.parse,ne.lex;class ue{constructor(e={},t){this.builder=t,this.opts=Object.assign({},{lang:[]},e)}async checkIntent(e,t,r){let s,n,i,o="You are an assistant",a=`This is the user's request:\n\n${e}`;if(r.image&&"openai"===t)return a+="\nExtract some information.\n",s=[{name:"check_request",description:"Check request and extract information.",parameters:{type:"object",properties:{prompt:{type:"string",description:"Return user's instruction/prompt for generating the image."},num_images:{type:"number",description:"The number of images to generate, only if specified."},size:{type:"string",description:"Choose specified size: auto, 1024x1024, 1536x1024, 1024x1536"},quality:{type:"string",description:"Choose: auto, low, medium, high"},background:{type:"string",description:"Choose: auto, transparent, opaque"},output_format:{type:"string",description:"Choose: png, jpeg, webp"}},required:[]}}],n=await this.builder.send(a,"",o,"",s),!!n&&(i=JSON.parse(n),i);if(r.image){if(a+="\n\nCheck the type of the request:\n- Text/Prompt to Image Generation\n- Text/Prompt to 2D Illustration Generation\n- Text/Prompt to Digital Illustration Generation\n- Text/Prompt to Book Cover Generation\n- Upscale Image\n- Upscale Video\n- Minimize Image\n- Remove Backgroun
1d of an Image\n- Change/Replace Background of an Image\n- Erase/Remove Unwanted Objects from Image\n- Edit Area in Image\n- Generate Variation of an Image\n- Describe an image or ask questions about the image\n",s=[{name:"check_request",description:"Check request.",parameters:{type:"object",properties:{text_to_image_generation:{type:"boolean",description:"Check if the request asks to create or generate an image based on the prompt."},text_to_2d_illustration_generation:{type:"boolean",description:"Check if the request asks to create or generate a 2D illustration based on the prompt."},text_to_digital_illustration_generation:{type:"boolean",description:"Check if the request asks to create or generate a digital illustration based on the prompt."},text_to_book_cover_generation:{type:"boolean",description:"Check if the request asks to create or generate a book cover based on the prompt."},upscale_image:{type:"boolean",description:"Check if the request asks to upscale or enlarge an image."},minimize_image:{type:"boolean",description:"Check if the request asks to minimize (compress) the size of an image."},edit_area_in_image:{type:"boolean",description:"Check if the request asks to edit an image."},describe_image:{type:"boolean",description:"Check if the request is asking to describe an image or asking questions about the image."}},required:[]}}],n=await this.builder.send(a,"",o,"",s),!n)return!1;i=JSON.parse(n)}else if(r.video){if(a+="\n\nCheck the type of the request:\n- Image to Video Generation (generate a video based on image)\n- Prompt/text to Video Generation (generate a video based on prompt)\n- Upscale video\n- Add sound to video\n",s=[{name:"check_request",description:"Check request.",parameters:{type:"object",properties:{image_to_video_generation:{type:"boolean",description:"Check if the request asked to create or generate a video based on image, not prompt."},text_to_video_generation:{type:"boolean",description:"Check if the request asked to create or generate a video based on prompt, not image."}},required:[]}}],n=await this.builder.send(a,"",o,"",s),!n)return!1;i=JSON.parse(n)}else if(r.audio){if(a+="\n\nCheck the type of the request:\n- Prompt/text to Audio Generation (generate sound or audio based on prompt)\n- Text to Speech (generate speech from text)\n",s=[{name:"check_request",description:"Check request.",parameters:{type:"object",properties:{text_to_speech:{type:"boolean",description:"heck if the request is asking to generate speech from text."}},required:[]}}],n=await this.builder.send(a,"",o,"",s),!n)return!1;i=JSON.parse(n)}return this.builder.settings.consoleLog&&console.log(i),this.extractInfo(i,t,e)}async extractInfo(e,t,r){const s=this.builder.settings.defaultModels;if(e.text_to_image_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_image_generation[t].join("\n- ")}\n`,o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `;let a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the image."},num_images:{type:"number",description:"The number of images to generate, only if specified."},width:{type:"number",description:"Return image width to generate, only if specified."},height:{type:"number",description:"Return image height to generate, only if specified."},aspect_ratio:{type:"string",description:"Return the aspect ration, only if specified. Example: 3:4, 16:9, etc"},color1_red:{type:"string",description:"Return red part from color1 rgb."},color1_green:{type:"string",description:"Return green part from color1 rgb."},color1_blue:{type:"string",description:"Return blue part from color1 rgb."},color2_red:{type:"string",description:"Return red part from color2 rgb."},color2_green:{type:"string",description:"Return green part from color2 rgb."},color2_blue:{type:"string",description:"Return blue part from color2 rgb."},color3_red:{type:"string",description:"Return red part from color3 rgb."},color3_green:{type:"string",description:"Return green part from color3 rgb."},color3_blue:{type:"string",description:"Return blue part from color3 rgb."},color4_red:{type:"string",description:"Return red part from color4 rgb."},color4_green:{type:"string",description:"Return green part from color4 rgb."},color4_blue:{type:"string",description:"Return blue part from color4 rgb."},color5_red:{type:"string",description:"Return red part from color5 rgb."},color5_green:{type:"string",description:"Return green part from color5 rgb."},color5_blue:{type:"string",description:"Return blue part from color5 rgb."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.image_to_video_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.image_to_video_generation[t].join("\n- ")}\n`,o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `;let a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the video."},image_url:{type:"string",description:"Return user's image reference URL (if JPG or PNG image URL is specified)."},duration:{type:"number",description:"Return duration of the video to generate."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.text_to_video_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_video_generation[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the video."},duration:{type:"number",description:"Return duration of the video to generate. If not explicitely specified, return 5"}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.minimize_image){let t="You are an assistant",s="",n=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,i=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{image_url:{type:"string",description:"Return user's image reference URL (if JPG or PNG image URL is specified)."}},required:["image_url"]}}],o=await this.builder.send(n,s,t,"",i);if(!o)return!1;let a=JSON.parse(o);return{...e,...a}}if(e.upscale_image){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.upscale_image[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},image_url:{type:"string",description:"Return user's image reference URL (if JPG or PNG image URL is specified)."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.describe_image){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.describe_image[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},image_url:{type:"string",description:"Return user's image reference URL (if JPG or PNG image URL is specified)."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the video."}},required:["image_url","prompt"]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.edit_area_in_image){const n="You are an assistant",i=s.edit_area_in_image[t];let o="";i&&(o=`\nThie is the list of models:\n- ${i.join("\n- ")}\n`);let a=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,l=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},image_url:{type:"string",description:"Return user's image reference URL (if JPG or PNG image URL is specified)."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the video."},num_images:{type:"number",description:"The number of images to generate."}},required:[]}}],c=await this.builder.send(a,o,n,"",l);if(!c)return!1;let d=JSON.parse(c);return{...e,...d}}if(e.text_to_2d_illustration_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_2d_illustration_generation[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the image."},style:{type:"string",description:'Return "digital_illustration"'},style_id:{type:"string",description:"Return specified style_id for generating the image."},num_images:{type:"number",description:"The number of images to generate."},width:{type:"number",description:"Return image width to generate."},height:{type:"number",description:"Return image height to generate."},aspect_ratio:{type:"string",description:"Example: 3:4, 16:9, etc"},color1_red:{type:"string",description:"Return red part from color1 rgb."},color1_green:{type:"string",description:"Return green part from color1 rgb."},color1_blue:{type:"string",description:"Return blue part from color1 rgb."},color2_red:{type:"string",description:"Return red part from color2 rgb."},color2_green:{type:"string",description:"Return green part from color2 rgb."},color2_blue:{type:"string",description:"Return blue part from color2 rgb."},color3_red:{type:"string",description:"Return red part from color3 rgb."},color3_green:{type:"string",description:"Return green part from color3 rgb."},color3_blue:{type:"string",description:"Return blue part from color3 rgb."},color4_red:{type:"string",description:"Return red part from color4 rgb."},color4_green:{type:"string",description:"Return green part from color4 rgb."},color4_blue:{type:"string",description:"Return blue part from color4 rgb."},color5_red:{type:"string",description:"Return red part from color5 rgb."},color5_green:{type:"string",description:"Return green part from color5 rgb."},color5_blue:{type:"string",description:"Return blue part from color5 rgb."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.text_to_digital_illustration_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_digital_illustration_generation[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the image."},style:{type:"string",description:'Return "digital_illustration"'},style_id:{type:"string",description:"Return specified style_id for generating the image."},num_images:{type:"number",description:"The number of images to generate."},width:{type:"number",description:"Return image width to generate."},height:{type:"number",description:"Return image height to generate."},aspect_ratio:{type:"string",description:"Example: 3:4, 16:9, etc"},color1_red:{type:"string",description:"Return red part from color1 rgb."},color1_green:{type:"string",description:"Return green part from color1 rgb."},color1_blue:{type:"string",description:"Return blue part from color1 rgb."},color2_red:{type:"string",description:"Return red part from color2 rgb."},color2_green:{type:"string",description:"Return green part from color2 rgb."},color2_blue:{type:"string",description:"Return blue part from color2 rgb."},color3_red:{type:"string",description:"Return red part from color3 rgb."},color3_green:{type:"string",description:"Return green part from color3 rgb."},color3_blue:{type:"string",description:"Return blue part from color3 rgb."},color4_red:{type:"string",description:"Return red part from color4 rgb."},color4_green:{type:"string",description:"Return green part from color4 rgb."},color4_blue:{type:"string",description:"Return blue part from color4 rgb."},color5_red:{type:"string",description:"Return red part from color5 rgb."},color5_green:{type:"string",description:"Return green part from color5 rgb."},color5_blue:{type:"string",description:"Return blue part from color5 rgb."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.text_to_book_cover_generation){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_book_cover_generation[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},prompt:{type:"string",description:"Return user's instruction/prompt for generating the image."},style:{type:"string",description:'Return "digital_illustration/cover"'},num_images:{type:"number",description:"The number of images to generate."},width:{type:"number",description:"Return image width to generate."},height:{type:"number",description:"Return image height to generate."},aspect_ratio:{type:"string",description:"Example: 3:4, 16:9, etc"},color1_red:{type:"string",description:"Return red part from color1 rgb."},color1_green:{type:"string",description:"Return green part from color1 rgb."},color1_blue:{type:"string",description:"Return blue part from color1 rgb."},color2_red:{type:"string",description:"Return red part from color2 rgb."},color2_green:{type:"string",description:"Return green part from color2 rgb."},color2_blue:{type:"string",description:"Return blue part from color2 rgb."},color3_red:{type:"string",description:"Return red part from color3 rgb."},color3_green:{type:"string",description:"Return green part from color3 rgb."},color3_blue:{type:"string",description:"Return blue part from color3 rgb."},color4_red:{type:"string",description:"Return red part from color4 rgb."},color4_green:{type:"string",description:"Return green part from color4 rgb."},color4_blue:{type:"string",description:"Return blue part from color4 rgb."},color5_red:{type:"string",description:"Return red part from color5 rgb."},color5_green:{type:"string",description:"Return green part from color5 rgb."},color5_blue:{type:"string",description:"Return blue part from color5 rgb."}},required:[]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e,...c}}if(e.text_to_speech){const n="You are an assistant",i=`\nThie is the list of models:\n- ${s.text_to_speech[t].join("\n- ")}\n`;let o=`This is user's request:\n\n${r}\n\nCheck the request and return the details.\n    `,a=[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the chosen model name from the model list."},text:{type:"string",description:"Return text or prompt to convert to speech."},voice:{type:"string",description:"Return the voice reference to use."},speed:{type:"string",description:"Return the speed."}},required:["text"]}}],l=await this.builder.send(o,i,n,"",a);if(!l)return!1;let c=JSON.parse(l);return{...e
1,...c}}return!1}async checkModel(e){let t=`This is the information:\n\n${e}\n\nCheck the information and return the details.\n`,r=await this.builder.send(t,"","You are an assistant","",[{name:"check_request",description:"Check information.",parameters:{type:"object",properties:{model:{type:"string",description:"Return the model name."}},required:["model"]}}]);return!!r&&JSON.parse(r)}getDimension(e){let t,r;return e?"1:1"===e?(t=1024,r=1024):"3:2"===e?(t=1216,r=832):"4:3"===e?(t=1152,r=896):"5:4"===e?(t=1088,r=896):"16:9"===e?(t=1344,r=768):"21:9"===e?(t=1536,r=640):"2:3"===e?(t=832,r=1216):"3:4"===e?(t=896,r=1152):"4:5"===e?(t=896,r=1088):"9:19"===e?(t=768,r=1344):"9:21"===e?(t=640,r=1536):(t=1344,r=768):(t=1344,r=768),{w:t,h:r}}getEndpoint(e,t,r){r=r.replace("{REQUEST_ID}",t);let s=e.split("/").slice(0,2).join("/");return r=r.replace("{MODEL}",s)}async waitingResultFal(e,t,r,s){let n,i;e.request_id=t;const o=this.getEndpoint(e.model,t,this.builder.settings.falResultEndpoint);e.endpoint=o;let a={"Content-Type":"application/json",...this.builder.settings.headers};n=await fetch(this.builder.settings.getResultUrl_Fal,{signal:this.builder.mediaSignal,method:"POST",headers:a,body:JSON.stringify(e)});let l=await n.text();try{i=JSON.parse(l)}catch(e){return{mediaGenerated:!1,status:"error",message:l}}if(this.builder.output.push(i),i.error)return this.builder.settings.consoleLog&&console.log(i.error),{mediaGenerated:!1,status:"error",message:i.error};{const e=i.data;let t,n="",o="",a=!1,l=[],c=[];return e.entries&&e.entries.forEach((e=>{t=e.url.split(".").pop().toLowerCase(),"mp4"===t?(n+=`\n                        <p class="responsive-video">\n                            <video controls>\n                                <source src="${e.url}" type="video/mp4">\n                                Your browser does not support the video tag.\n                            </video>\n                        </p>\n                    `,o+=`![](${e.url})`):"wav"===t||"mp3"===t?(n+=`\n                    <p class="responsive-audio">\n                        <audio controls>\n                            <source src="${e.url}" type="audio/mpeg">\n                            Your browser does not support the audio tag.\n                        </audio>\n                    </p>\n                    `,o+=`![](${e.url})`):(n+=`\n                        <div>\n                            <img src="${e.url}" />\n                            <div>\n                                <a class="link-view" href="${e.url}" target="_blank" rel="noopener noreferrer">${this.out("View")}</a>\n                                <a class="link-download" href="${e.url}" download>${this.out("Download")}</a>\n                            </div>\n                        </div>\n                    `,o+=`![](${e.url})`,a=!0),l.push(e.url),c.push(e.file_url)})),a&&(n=`<div class="image-container">${n}</div>`),"string"==typeof e&&(n=e,o=e),s?(r.innerHTML="",r.remove()):(r.innerHTML=n,this.builder.outputHtml+=`<div class="result-container">${n}</div>`),{mediaGenerated:!0,status:"success",markdown:o,output:l,output2:c}}}async waitingResultReplicate(e,t,r,s){let n,i;e.request_id=t;let o=this.builder.settings.replicateStatusEndpoint;o=o.replace("{REQUEST_ID}",t),e.endpoint=o;let a={"Content-Type":"application/json",...this.builder.settings.headers};n=await fetch(this.builder.settings.getResultUrl_Replicate,{signal:this.builder.mediaSignal,method:"POST",headers:a,body:JSON.stringify(e)});let l=await n.text();try{i=JSON.parse(l)}catch(e){return{mediaGenerated:!1,status:"error",message:l}}if(this.builder.output.push(i),i.error)return this.builder.settings.consoleLog&&console.log(i.error),{mediaGenerated:!1,status:"error",message:i.error};{const e=i.data;let t=this.renderResult(e,r,s);return{mediaGenerated:!0,status:"success",markdown:t.markdown,output:t.output,output2:t.output2}}}async waitingReplicate(e,t,r,s){let n,i,o,a=e.model,l=this.builder.settings.replicateStatusEndpoint;l=l.replace("{REQUEST_ID}",t);let c={"Content-Type":"application/json",...this.builder.settings.headers},d={model:a,endpoint:l,request_id:t};do{if(i=await fetch(this.builder.settings.checkRequestStatusUrl_Replicate,{signal:this.builder.mediaSignal,method:"POST",headers:c,body:JSON.stringify(d)}),o=await i.json(),o.ok&&(n=o.data.status),!n)return{mediaGenerated:!1,status:"error",result:o,message:o.error||o.data&&JSON.stringify(o.data)||this.out("Request failed.")};"succeeded"!==n&&"failed"!==n&&"canceled"!==n&&(this.builder.settings.consoleLog&&c
1onsole.log(n),await new Promise((e=>setTimeout(e,5e3))))}while("succeeded"!==n&&"failed"!==n&&"canceled"!==n);return"succeeded"===n?await this.waitingResultReplicate(e,t,r,s):{mediaGenerated:!1,status:"error",result:o,message:o.data&&o.data.error||this.out("Request failed.")}}async waitingFal(e,t,r,s){let n,i,o,a=e.model;const l=this.getEndpoint(a,t,this.builder.settings.falStatusEndpoint);let c={"Content-Type":"application/json",...this.builder.settings.headers},d={model:a,endpoint:l,request_id:t};do{if(i=await fetch(this.builder.settings.checkRequestStatusUrl_Fal,{signal:this.builder.mediaSignal,method:"POST",headers:c,body:JSON.stringify(d)}),o=await i.json(),o.ok&&o.status)n=o.status;else if(o.data){let e=o.data;e.image||e.audio||e.audio_file||e.video?n="COMPLETED":e.detail&&"string"==typeof e.detail&&e.detail.startsWith("Request is still in progress")?n="IN_PROGRESS":e.status&&!e.error&&(n=e.status)}if(!n)return{mediaGenerated:!1,status:"error",result:o,message:o.error||o.data&&JSON.stringify(o.data)||this.out("Request failed.")};"COMPLETED"!==n&&(this.builder.settings.consoleLog&&console.log(n),this.builder.settings.consoleLog&&console.log(o),await new Promise((e=>setTimeout(e,5e3))))}while("COMPLETED"!==n);if("COMPLETED"===n)return await this.waitingResultFal(e,t,r,s)}renderResult(e,t,r){let s="",n="",i=[],o=[];if(e.entries){let t,r=!1;e.entries.forEach((e=>{t=e.url.split(".").pop().toLowerCase(),"mp4"===t?(s+=`\n                        <p class="responsive-video">\n                            <video controls>\n                                <source src="${e.url}" type="video/mp4">\n                                Your browser does not support the video tag.\n                            </video>\n                        </p>\n                    `,n+=`![](${e.url})`,i.push(e.url),o.push(e.file_url)):"wav"===t||"mp3"===t?(s+=`\n                    <p class="responsive-audio">\n                        <audio controls>\n                            <source src="${e.url}" type="audio/mpeg">\n                            Your browser does not support the audio tag.\n                        </audio>\n                    </p>\n                    `,n+=`![](${e.url})`,i.push(e.url),o.push(e.file_url)):(s+=`\n                        <div>\n                            <img src="${e.url}" />\n                            <div>\n                                <a class="link-view" href="${e.url}" target="_blank" rel="noopener noreferrer">${this.out("View")}</a>\n                                <a class="link-download" href="${e.url}" download>${this.out("Download")}</a>\n                            </div>\n                        </div>\n                    `,n+=`![](${e.url})`,i.push(e.url),o.push(e.file_url),r=!0)})),r&&(s=`<div class="image-container">${s}</div>`)}else"string"==typeof e&&(s=`\n            <p>\n            ${e}\n            </p>`,n=e);return r?(t.innerHTML="",t.remove()):(t.innerHTML=s,this.builder.outputHtml+=`<div class="result-container">${s}</div>`),{markdown:n,output:i,output2:o}}async generateReplicate(e,t,r){let s,n={};const i="replicate";if(e.text_to_image_generation){let t=this.validateModel(e.model,i,"text_to_image_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.aspect_ratio||"16:9",a=e.num_images||1;a>4&&(a=4),s={prompt:r,aspect_ratio:o,num_outputs:a},n.model=t,n.customData=this.builder.settings.customData}else if(e.edit_area_in_image){let t=this.validateModel(e.model,i,"edit_area_in_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};let i="replicate";const o=await this.builder.upload.getInputURLs(i,!0);if(o.error)return{mediaGenerated:!1,status:"error",message:o.error};let a=o[e.image_url],l=o[e.image_url+"_mask"];if(!l)return{mediaGenerated:!1,status:"error",message:this.out("Image mask not found.")};s={prompt:r,image:a,mask:l},n.model=t,n.customData=this.builder.settings.customData}else if(e.text_to_digital_illustration_generation){let t=this.validateModel(e.model,i,"text_to_digital_illustration_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.width||1280,a=e.height||768;e.num_images,s={prompt:r,size:`${o}x${a}`,style:"digital_illustration"},n.model=t,n.customData=this.builder.settings.customData}else if(e.upscale_image){let t=this.validateModel(e.model,r,"upscale_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};let r="replicate";const i=await this.builder.upload.getInputURLs(r);if(i.error)return{mediaGenerated:!1,status:"error",message:i.error};let o=i[e.image_url];if(!o)return{mediaGenerated:!1,status:"error",message:this.out("Image not provided.")};s={image:o},n.model=t,n.customData=this.builder.settings.customData}else if(e.describe_image){let t=this.validateModel(e.model,i,"describe_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};let i="replicate";const o=await this.builder.upload.getInputURLs(i);if(o.error)return{mediaGenerated:!1,status:"error",message:o.error};let a=o[e.image_url];if(!a)return{mediaGenerated:!1,status:"error",message:this.out("Image not provided.")};s={image:a,prompt:`${r}. No talk. Answer only.`},n.model=t,n.customData=this.builder.settings.customData}else if(e.image_to_video_generation){let t=this.validateModel(e.model,o,"image_to_video_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt||"stunning video",i=e.duration||5;i>10&&(i=5);let o="replicate";const a=await this.builder.upload.getInputURLs(o);if(a.error)return{mediaGenerated:!1,status:"error",message:a.error};let l=a[e.image_url];if(!l)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};"kwaivgi/kling-v1.6-pro"===t&&(s={start_image:l,prompt:r,duration:i}),"kwaivgi/kling-v1.6-standard"===t&&(s={start_image:l,prompt:r,duration:i}),"minimax/video-01-live"===t&&(s={first_frame_image:l,prompt:r}),"luma/ray"===t&&(s={start_image_url:l,prompt:r}),n.model=t,n.customData=this.builder.settings.customData}else if(e.text_to_video_generation){let t=this.validateModel(e.model,i,"text_to_video_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.duration||5;o>10&&(o=5),"kwaivgi/kling-v1.6-standard"===t&&(s={prompt:r,duration:o}),"minimax/video-01"===t&&(s={prompt:r}),"luma/ray"===t&&(s={prompt:r}),n.model=t,n.customData=this.builder.settings.customData}else if(e.text_to_speech){let t=this.validateModel(e.model,i,"text_to_speech");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};if(e.text.length>this.builder.settings.ttsMaxCharacters)return{mediaGenerated:!1,status:"error",message:this.out("The text exceeds the allowed limit.")};s={text:e.text,voice:e.voice||"af_nicole",speed:parseFloat(e.speed)||1},n.model=t,n.customData=this.builder.settings.customData}if(-1!==n.model.indexOf(":")){const e=n.model.split(":")[1];n.version=e;let t=this.builder.settings.replicateEndpoint1;
1n.endpoint=t,n.payload=s,this.builder.settings.consoleLog&&console.log("PAYLOAD 1")}else{let e=this.builder.settings.replicateEndpoint2;e=e.replace("{MODEL}",n.model),n.endpoint=e,n.payload=s,this.builder.settings.consoleLog&&console.log("PAYLOAD 2")}this.builder.payloads.push(n),this.builder.settings.consoleLog&&console.log(n);let o=!1;if(this.builder.settings.generateMediaUrl_Replicate&&(o=!0),o){let e,s=this.builder.settings.generateMediaUrl_Replicate;if(!s)return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured.")};let i={"Content-Type":"application/json",...this.builder.settings.headers},o=await fetch(s,{signal:this.builder.mediaSignal,method:"POST",headers:i,body:JSON.stringify(n)}),a=await o.json();if(!a.ok)return{mediaGenerated:!1,status:"error",message:a.error};if(e=a.data.id,!e)return{mediaGenerated:!1,status:"error",message:a.data&&a.data.detail};const l=this.waitingReplicate(n,e,t,r);return this.builder.isMediaGenerating=!1,l}{let e=this.builder.settings.generateMediaUrl;if(!e)return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured: generateMediaUrl.")};let s={"Content-Type":"application/json",...this.builder.settings.headers};const i=await fetch(e,{signal:this.builder.mediaSignal,method:"POST",headers:s,body:JSON.stringify(n)}),o=await i.json();if(this.builder.isMediaGenerating=!1,o.error)return this.builder.settings.consoleLog&&console.log(o.error),{mediaGenerated:!1,status:"error",message:o.error};{const e=o.data;let s=this.renderResult(e,t,r);return{mediaGenerated:!0,status:"success",markdown:s.markdown,output:s.output,output2:s.output2}}}}async generateOpenAI(e,t,r){let s,n={};let i=this.validateModel(e.model,"openai","image_generation"),o=e.prompt;if(!o)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};const a=new FormData;a.append("customData",this.builder.settings.customData),a.append("model",i),a.append("prompt",o);let l,c=!1,d=this.builder.getFormValues();for(const e of d){if(e.value instanceof FileList&&"multifile"===e.type){const t=e.value;if(t.length>0)for(const e of t)a.append("file[]",e),c=!0}if(e.value instanceof FileList&&"file"===e.type){const t=e.value;if(t.length>0){const e=t[0];a.append("file[]",e),c=!0}}if("string"==typeof e.value&&-1!==e.value.indexOf("base64")){let t=e.value.replace(/^data:image\/(png|svg\+xml|jpeg|gif|webp);base64,/,"");a.append("mask",t)}}let u=e.size||"auto",p=e.quality||"auto",h=e.num_images||1;if(c){a.append("size",u),a.append("n",h),a.append("quality",p);let e=this.builder.settings.generateMediaUrl_OpenAI_CreateImageEdit;l=await fetch(e,{method:"POST",body:a})}else{s={prompt:o,background:e.background||"auto",output_format:e.output_format||"png",size:u,quality:p,n:h},n.model=i,n.customData=this.builder.settings.customData,n.payload=s,this.builder.payloads.push(n),this.builder.settings.consoleLog&&console.log(n);const t=this.builder.settings.generateMediaUrl_OpenAI_CreateImage;let r={"Content-Type":"application/json",...this.builder.settings.headers};l=await fetch(t,{signal:this.builder.mediaSignal,method:"POST",headers:r,body:JSON.stringify(n)})}const m=await l.json();this.builder.settings.consoleLog&&console.log(m),this.builder.isMediaGenerating=!1;const g=m.data;let f=this.renderResult(g,t,r);return{mediaGenerated:!0,status:"success",markdown:f.markdown,output:f.output,output2:f.output2}}async generateGoogle(e,t,r){let s,n={};let i=this.validateModel(e.model,"google","edit_area_in_image");if(!i)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let o=e.prompt;if(!o)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let a=[];a.push({text:o});let l=this.builder.getFormValues();if(l&&0===Object.keys(l).length);else for(const e of l)if(e.value instanceof FileList&&"multifile"===e.type){const t=e.value;if(t.length>0)for(const e of t){const t=await new Promise(((t,r)=>{const s=new FileReader;s.onload=e=>{const r=e.target.result.split(",")[1];t(r)},s.onerror=r,s.readAsDataURL(e)}));a.push({inlineData:{mimeType:"image/png",data:t}})}}s={contents:a},n.model=i,n.customData=this.builder.settings.customData,n.payload=s,this.builder.payloads.push(n),this.builder.settings.consoleLog&&c
1onsole.log(n);const c=this.builder.settings.generateMediaUrl_Google;let d={"Content-Type":"application/json",...this.builder.settings.headers};const u=await fetch(c,{signal:this.builder.mediaSignal,method:"POST",headers:d,body:JSON.stringify(n)}),p=await u.json();this.builder.settings.consoleLog&&console.log(p),this.builder.isMediaGenerating=!1;const h=p.data;let m=this.renderResult(h,t,r);return{mediaGenerated:!0,status:"success",markdown:m.markdown,output:m.output,output2:m.output2}}async generateFal(e,t,r){let s,n="fal",i={};if(e.text_to_image_generation){let t=this.validateModel(e.model,n,"text_to_image_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.width||1280,a=e.height||768,l=e.aspect_ratio,c=e.num_images||1;if(c>4&&(c=4),"fal-ai/flux/schnell"!==t&&"fal-ai/flux/dev"!==t&&(c=1),l){let{w:e,h:t}=this.getDimension(l);o=e,a=t}let d=e.color1_red,u=e.color1_green,p=e.color1_blue,h=e.color2_red,m=e.color2_green,g=e.color2_blue,f=e.color3_red,b=e.color3_green,y=e.color3_blue,v=e.color4_red,k=e.color4_green,w=e.color4_blue,x=e.color5_red,_=e.color5_green,E=e.color5_blue,L=[];d&&u&&p&&("0"!==d||"0"!==u||"0"!==p)&&L.push({r:d,g:u,b:p}),h&&m&&g&&("0"!==h||"0"!==m||"0"!==g)&&L.push({r:h,g:m,b:g}),f&&b&&y&&("0"!==f||"0"!==b||"0"!==y)&&L.push({r:f,g:b,b:y}),v&&k&&w&&("0"!==v||"0"!==k||"0"!==w)&&L.push({r:v,g:k,b:w}),x&&_&&E&&("0"!==x||"0"!==_||"0"!==E)&&L.push({r:x,g:_,b:E});const C=async()=>{let e=[],t=this.builder.getFormValues();for(const r of t)if(r.value instanceof FileList&&"multifile"===r.type){const t=r.value;if(t.length>0){let r=0;for(const s of t){r++;const t=new FormData;t.append("file",s),t.append("customData",this.builder.settings.customData);let n=this.builder.settings.uploadMediaUrl_Fal;const i=await fetch(n,{method:"POST",body:t}),o=await i.json();if(o.ok){const t=o.url;e.push(t),this.builder.filesUploaded["file_"+r]=t}}}}return e};let R=await C();s={prompt:r,image_size:{width:o,height:a},num_images:c},-1!==t.indexOf("gemini")&&(s={prompt:r,input_image_urls:R}),"fal-ai/ideogram/v2a"===t&&(l=this.getClosestAspectRatio(o,a),s={prompt:r,aspect_ratio:l,num_images:c}),-1!==t.indexOf("recraft")&&(s={prompt:r,image_size:{width:o,height:a},num_images:c,colors:L}),i.model=t,i.customData=this.builder.settings.customData}else if(e.edit_area_in_image){let t=this.validateModel(e.model,n,"edit_area_in_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};const o=await this.builder.upload.getInputURLs(n);if(o.error)return{mediaGenerated:!1,status:"error",message:o.error};let a=o[e.image_url],l=o[e.image_url+"_mask"];if(s={image_url:a,mask_url:l,prompt:r},i.model=t,!l){s={image_url:a,prompt:r};let t=this.validateModel(e.model,n,"edit_image");i.model=t}i.customData=this.builder.settings.customData}else if(e.text_to_2d_illustration_generation){let t=this.validateModel(e.model,n,"text_to_2d_illustration_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.width||1280,a=e.height||768,l=e.num_images||1;l>4&&(l=4);let c=e.style||"any",d=e.style_id||this.builder.settings._2dIllustrationStyleId,u=e.color1_red,p=e.color1_green,h=e.color1_blue,m=e.color2_red,g=e.color2_green,f=e.color2_blue,b=e.color3_red,y=e.color3_green,v=e.color3_blue,k=e.color4_red,w=e.color4_green,x=e.color4_blue,_=e.color5_red,E=e.color5_green,L=e.color5_blue,C=[];u&&p&&h&&("0"!==u||"0"!==p||"0"!==h)&&C.push({r:u,g:p,b:h}),m&&g&&f&&("0"!==m||"0"!==g||"0"!==f)&&C.push({r:m,g:g,b:f}),b&&y&&v&&("0"!==b||"0"!==y||"0"!==v)&&C.push({r:b,g:y,b:v}),k&&w&&x&&("0"!==k||"0"!==w||"0"!==x)&&C.push({r:k,g:w,b:x}),_&&E&&L&&("0"!==_||"0"!==E||"0"!==L)&&C.push({r:_,g:E,b:L}
1),s={prompt:r,image_size:{width:o,height:a},num_images:l,style:c,style_id:d,colors:C},i.model=t,i.customData=this.builder.settings.customData}else if(e.text_to_digital_illustration_generation){let t=this.validateModel(e.model,n,"text_to_digital_illustration_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.width||1280,a=e.height||768,l=e.num_images||1;l>4&&(l=4);let c=e.style||"digital_illustration",d=e.color1_red,u=e.color1_green,p=e.color1_blue,h=e.color2_red,m=e.color2_green,g=e.color2_blue,f=e.color3_red,b=e.color3_green,y=e.color3_blue,v=e.color4_red,k=e.color4_green,w=e.color4_blue,x=e.color5_red,_=e.color5_green,E=e.color5_blue,L=[];d&&u&&p&&("0"!==d||"0"!==u||"0"!==p)&&L.push({r:d,g:u,b:p}),h&&m&&g&&("0"!==h||"0"!==m||"0"!==g)&&L.push({r:h,g:m,b:g}),f&&b&&y&&("0"!==f||"0"!==b||"0"!==y)&&L.push({r:f,g:b,b:y}),v&&k&&w&&("0"!==v||"0"!==k||"0"!==w)&&L.push({r:v,g:k,b:w}),x&&_&&E&&("0"!==x||"0"!==_||"0"!==E)&&L.push({r:x,g:_,b:E}),s={prompt:r,image_size:{width:o,height:a},num_images:l,style:c,colors:L},i.model=t,i.customData=this.builder.settings.customData}else if(e.text_to_book_cover_generation){let t=this.validateModel(e.model,n,"text_to_book_cover_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.width||1024,a=e.height||1365,l=e.num_images||1;l>4&&(l=1);let c="digital_illustration/cover",d=e.color1_red,u=e.color1_green,p=e.color1_blue,h=e.color2_red,m=e.color2_green,g=e.color2_blue,f=e.color3_red,b=e.color3_green,y=e.color3_blue,v=e.color4_red,k=e.color4_green,w=e.color4_blue,x=e.color5_red,_=e.color5_green,E=e.color5_blue,L=[];d&&u&&p&&("0"!==d||"0"!==u||"0"!==p)&&L.push({r:d,g:u,b:p}),h&&m&&g&&("0"!==h||"0"!==m||"0"!==g)&&L.push({r:h,g:m,b:g}),f&&b&&y&&("0"!==f||"0"!==b||"0"!==y)&&L.push({r:f,g:b,b:y}),v&&k&&w&&("0"!==v||"0"!==k||"0"!==w)&&L.push({r:v,g:k,b:w}),x&&_&&E&&("0"!==x||"0"!==_||"0"!==E)&&L.push({r:x,g:_,b:E}),s={prompt:r,image_size:{width:o,height:a},num_images:l,style:c,colors:L},i.model=t,i.customData=this.builder.settings.customData}else if(e.upscale_image){let t=this.validateModel(e.model,n,"upscale_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};const r=await this.builder.upload.getInputURLs(n);if(r.error)return{mediaGenerated:!1,status:"error",message:r.error};let o=r[e.image_url];if(!o)return{mediaGenerated:!1,status:"error",message:this.out("Image not provided.")};s={image_url:o,upscale_factor:2},i.model=t,i.customData=this.builder.settings.customData}else if(e.describe_image){let t=this.validateModel(e.model,n,"describe_image");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};if(!e.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};const o=await this.builder.upload.getInputURLs(n);if(o.error)return{mediaGenerated:!1,status:"error",message:o.error};let a=o[e.image_url];if(!a)return{mediaGenerated:!1,status:"error",message:this.out("Image not provided.")};s={image_url:a,prompt:`${r}. No talk. Answer only.`},i.model=t,i.customData=this.builder.settings.customData}else if(e.image_to_video_generation){let t=this.validateModel(e.model,n,"image_to_video_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;r=e.prompt||"stunning video";let o=e.duration||5;o>10&&(o=5);const a=await this.builder.upload.getInputURLs(n);if(a.error)return{mediaGenerated:!1,status:"error",message:a.error};let l=a[e.image_url];if(!l)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};s={prompt:r,image_url:l,duration:o,aspect_ratio:"16:9"},-1!==t.indexOf("fal-ai/luma-dream-machine")&&delete s.duration,i.model=t,i.customData=this.builder.settings.customData}else if(e.text_to_video_generation){let t=this.validateModel(e.model,n,"text_to_video_generation");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};let r=e.prompt;if(!r)return{mediaGenerated:!1,status:"error",message:this.out("Please input a prompt.")};let o=e.duration||5;o>10&&(o=5),s={prompt:r,duration:o,aspect_ratio:"16:9"},-1!==t.indexOf("fal-ai/luma-dream-machine")&&delete s.duration,i.model=t,i.customData=this.builder.settings.customData}else if(e.text_to_speech){let t=this.validateModel(e.model,n,"text_to_speech");if(!t)return{mediaGenerated:!1,status:"error",message:this.out("Model not found.")};if(e.text.length>this.builder.settings.ttsMaxCharacters)return{mediaGenerated:!1,status:"error",message:this.out("The text exceeds the allowed limit.")};s={text:e.text,voice:e.voice||"Matilda"},i.model=t,i.customData=this.builder.settings.customData}let o=`https://queue.fal.run/${i.model}`;i.endpoint=o,i.payload=s,this.builder.payloads.push(i),this.builder.settings.consoleLog&&c
1onsole.log(i);let a,l=this.builder.settings.generateMediaUrl_Fal;if(!l)return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured: generateMediaUrl_Fal.")};let c={"Content-Type":"application/json",...this.builder.settings.headers},d=await fetch(l,{signal:this.builder.mediaSignal,method:"POST",headers:c,body:JSON.stringify(i)}),u=await d.json();if(!u.ok)return{mediaGenerated:!1,status:"error",message:u.error};a=u.request_id;const p=this.waitingFal(i,a,t,r);return this.builder.isMediaGenerating=!1,p}validateModel(e,t,r){const s=this.builder.settings.defaultModels[r][t];return 1===s.length?(this.builder.settings.consoleLog&&console.log("Fixed model: "+s[0]),s[0]):e&&s&&s.includes(e)?(this.builder.settings.consoleLog&&console.log("Model is valid: "+e),e):s.length>=1&&(this.builder.settings.consoleLog&&console.log("Use default: "+s[0]),s[0])}async generate_GoogleMediaByJSON(e,t,r,s){let n;if(this.builder.isMediaGenerating=!0,this.mediaController=new AbortController,this.builder.mediaSignal=this.mediaController.signal,e.trim().startsWith("{"))try{n=JSON.parse(e)}catch(e){return{mediaGenerated:!1,status:"error",message:this.out("Incorrect JSON format.")}}let i=t.trim();if(!i)return{mediaGenerated:!1,status:"error",message:this.out("Please provide model information in the context.")};let o={};o.model=i,o.customData=this.builder.settings.customData,o.payload=n,this.builder.payloads.push(o),this.builder.settings.consoleLog&&console.log(o);const a=this.builder.settings.generateMediaUrl_Google;let l={"Content-Type":"application/json",...this.builder.settings.headers};const c=await fetch(a,{signal:this.builder.mediaSignal,method:"POST",headers:l,body:JSON.stringify(o)}),d=await c.json();this.builder.settings.consoleLog&&console.log(d);const u=d.data;let p=this.renderResult(u,r,s);return{mediaGenerated:!0,status:"success",markdown:p.markdown,output:p.output,output2:p.output2}}async uploadMultiple(){let e=[],t=this.builder.getFormValues();for(const r of t)if(r.value instanceof FileList&&"multifile"===r.type){const t={};t.name=r.name,t.files=[];const s=r.value;if(s.length>0){let e=0;for(const r of s){e++;const s=new FormData;s.append("file",r),s.append("customData",this.builder.settings.customData);let n=this.builder.settings.uploadMediaUrl_Fal;const i=await fetch(n,{method:"POST",body:s}),o=await i.json();if(o.ok){const r=o.url;t.files.push(r),this.builder.filesUploaded["file_"+e]=r}}}e.push(t)}return e}async generate(e,t,r,s,n,i,o){if("google"===(r=r||this.builder.settings.defaultMediaGenerationProvider)&&e.trim().startsWith("{"))return this.generate_GoogleMediaByJSON(e,t,i,o);let a;this.builder.isMediaGenerating=!0,this.mediaController=new AbortController,this.builder.mediaSignal=this.mediaController.signal;let l,c=!1;if(e.trim().startsWith("{"))try{l=JSON.parse(e),l&&"object"==typeof l&&(c=!0)}catch(e){return{mediaGenerated:!1,status:"error",message:this.out("Incorrect JSON format.")}}if(c){let e=t.trim();if(!e)return{mediaGenerated:!1,status:"error",message:this.out("Please provide model information in the context.")};let s=await this.uploadMultiple();const n=(e,t)=>{const r=e=>{if(Array.isArray(e)){const s=e[0],n=t.find((e=>e.name===s));if(n&&e.every((e=>e===s)))return n.files;for(let t=0;t<e.length;t++)e[t]=r(e[t])}else if("object"==typeof e&&null!==e)for(let t in e)e[t]=r(e[t]);return e};return r(e)};n(l,s),r||(r=e.startsWith("fal")?"fal":"replicate");const a=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),c=await this.builder.upload.getInputURLs(r);if(c.error)return{mediaGenerated:!1,status:"error",message:c.error};Object.keys(l).forEach((e=>{Object.keys(c).forEach((t=>{if(l[e]===t){let r=c[t];l[e]=r}if(Array.isArray(l[e]))for(let r=0;r<l[e].length;r++)if(l[e][r]===t){let s=c[t];l[e][r]=s}}))})),Object.keys(l).forEach((e=>{let t=l[e];if(a(t))for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&Object.keys(c).forEach((r=>{if(t[e]===r){let s=c[r];t[e]=s,r!==s||s.startsWith("http")||(t[e]="")}}));if(Array.isArray(t)){for(let e=0;e<t.length;e++)if(a(t[e]))for(const r in t[e])Object.prototype.hasOwnProperty.call(t[e],r)&&Object.keys(c).forEac
1h((s=>{if(t[e][r]===s){let n=c[s];t[e][r]=n,s!==n||n.startsWith("http")||(t[e][r]="")}}));l[e]=[...t.filter((e=>""!==e))]}}));let d={};if(d.model=e,d.customData=this.builder.settings.customData,"replicate"===r&&-1!==e.indexOf(":")){const t=e.split(":");d.version=t[1]}if("replicate"===r)if(-1!==e.indexOf(":")){let e=this.builder.settings.replicateEndpoint1;d.endpoint=e,d.payload=l,this.builder.settings.consoleLog&&console.log("JSON PAYLOAD 1")}else{let e=this.builder.settings.replicateEndpoint2;e=e.replace("{MODEL}",d.model),d.endpoint=e,d.payload=l,this.builder.settings.consoleLog&&console.log("JSON PAYLOAD 2")}else if("fal"===r){let e=`https://queue.fal.run/${d.model}`;d.endpoint=e,d.payload=l,this.builder.settings.consoleLog&&console.log("JSON PAYLOAD")}return this.builder.payloads.push(d),this.builder.settings.consoleLog&&console.log(d),this.generateMediaByJSON(d,r,i,o)}try{if(a=await this.checkIntent(e,r,n),this.builder.settings.consoleLog&&console.log(a),!a)return{mediaGenerated:!1,status:"aborted",message:this.out("Request aborted.")};if(a.minimize_image){if(!a.image_url)return{mediaGenerated:!1,status:"error",message:this.out("Image reference not found.")};const e=await this.builder.upload.getInputURLs();if(e.error)return{mediaGenerated:!1,status:"error",message:e.error};let t={image_url:e[a.image_url]||a.image_url,customData:this.builder.settings.customData};this.builder.payloads.push(t),this.builder.settings.consoleLog&&console.log(t);let r={"Content-Type":"application/json",...this.builder.settings.headers};const s=await fetch(this.builder.settings.minimizeImageUrl,{signal:this.builder.mediaSignal,method:"POST",headers:r,body:JSON.stringify(t)}),n=await s.json();if(this.builder.output.push(n),n.error)return this.builder.settings.consoleLog&&console.log(n.error),this.builder.isMediaGenerating=!1,{mediaGenerated:!1,status:"error",message:n.error};{const e=n.url,t=`\n                    <div class="image-container">\n                        <div>\n                            <img src="${e}" />\n                            <div>\n                                <a class="link-view" href="${e}" target="_blank" rel="noopener noreferrer">${this.out("View")}</a>\n                                <a class="link-download" href="${e}" download>${this.out("Download")}</a>\n                            </div>\n                        </div>\n                    </div>`;let r=`![](${e})`;return o?(i.innerHTML="",i.remove()):(i.innerHTML=t,this.builder.outputHtml+=`<div class="result-container">${t}</div>`),this.builder.isMediaGenerating=!1,{mediaGenerated:!0,status:"success",markdown:r,output:[e]}}}if("fal"===r)return this.generateFal(a,i,o);if("replicate"===r)return this.generateReplicate(a,i,o);if("google"===r)return this.generateGoogle(a,i,o);if("openai"===r)return this.generateOpenAI(a,i,o)}catch(e){return this.builder.settings.consoleLog&&console.log(e),this.builder.isMediaGenerating=!1,"AbortError"===e.name?{mediaGenerated:!1,status:"aborted",message:this.out("Request aborted.")}:{mediaGenerated:!1,status:"error",message:this.out("Request failed.")}}return this.builder.isMediaGenerating=!1,{mediaGenerated:!1,status:"error",message:this.out("Request failed.")}}async generateMediaByJSON(e,t,r,s){let n,i=!1;if("replicate"===t&&this.builder.settings.generateMediaUrl){if(n=this.builder.settings.generateMediaUrl,!n)return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured: generateMediaUrl.")}}else if("replicate"===t&&this.builder.settings.generateMediaUrl_Replicate){if(n=this.builder.settings.generateMediaUrl_Replicate,!n)return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured: generateMediaUrl_Replicate.")};i=!0}else if("fal"===t&&(n=this.builder.settings.generateMediaUrl_Fal,!n))return{mediaGenerated:!1,status:"error",message:this.out("Endpoint not configured: generateMediaUrl_Fal.")};let o={"Content-Type":"application/json",...this.builder.settings.headers};const a=await fetch(n,{signal:this.builder.mediaSignal,method:"POST",headers:o,body:JSON.stringify(e)}),l=await a.json();if(this.builder.isMediaGenerating=!1,"fal"===t){let t=l.request_id;return this.waitingFal(e,t,r,s)}
1if(l.error)return this.builder.settings.consoleLog&&console.log(l.error),{mediaGenerated:!1,status:"error",message:l.error};if(i){let t;if(!l.ok)return{mediaGenerated:!1,status:"error",message:l.error};if(t=l.data.id,!t)return{mediaGenerated:!1,status:"error",message:l.data&&l.data.detail};return this.waitingReplicate(e,t,r,s)}{const e=l.data;let t=this.renderResult(e,r,s);return{mediaGenerated:!0,status:"success",markdown:t.markdown,output:t.output,output2:t.output2}}}getClosestAspectRatio(e,t){if(0===t)return"3:2";const r=e/t,s=[{aspect:"10:16",ratio:.625},{aspect:"16:10",ratio:1.6},{aspect:"9:16",ratio:9/16},{aspect:"16:9",ratio:16/9},{aspect:"4:3",ratio:4/3},{aspect:"3:4",ratio:3/4},{aspect:"1:1",ratio:1},{aspect:"1:3",ratio:1/3},{aspect:"3:1",ratio:3},{aspect:"3:2",ratio:1.5},{aspect:"2:3",ratio:2/3}];let n=s[0],i=Math.abs(r-s[0].ratio);for(let e=1;e<s.length;e++){const t=Math.abs(r-s[e].ratio);t<i&&(i=t,n=s[e])}return n.aspect}out(e){if(this.opts.lang){let t=this.opts.lang[e];return t||e}return e}}class pe{constructor(e={},t){this.builder=t,this.opts=Object.assign({},{lang:[]},e)}async getInputURLs(e){let t=this.builder.getFormValues();const r=this.builder.filesUploaded;if(0!==Object.keys(r).length)return r;for(const s of t)if(s.value instanceof FileList){let t=await this.processMediaInput(s.name,e),n=t.url;s.name===t.url&&(n=""),r[s.name]=n}else{if(-1!==s.name.indexOf("_mask")){let t=await this.processMaskInput(s.name,e);if(t.error)return{error:t.error};{let e=t.url;r[s.name]=e}}if(-1!==s.name.indexOf("__url")){let e;e=this.builder.settings.isBuilder?document.querySelector(this.builder.settings.previewSelector):this.builder.element;const t=e.querySelector(`input[name="${s.name}"]`);if(t){const e=t.value;r[s.name]=e}}}return Object.keys(r).forEach((e=>{if(e.endsWith("__url")){const t=e.replace("__url","");Object.prototype.hasOwnProperty.call(r,t)&&(r[t]=r[e]),delete r[e]}})),r}async processMaskInput(e,t){let r;if(this.builder.settings.isBuilder){if(!this.builder.settings.previewSelector)return{error:this.out("previewSelector not set.")};r=document.querySelector(this.builder.settings.previewSelector)}else r=this.builder.element;const s=r.querySelector(`input[type="hidden"][name="${e}"]`);if(!s)return{error:this.out("Unable to perform the request.")};if(""===s.value)return{error:this.out("Please brush the area you want to edit.")};let n,i=s.value.replace(/^data:image\/(png|svg\+xml|jpeg|gif|webp);base64,/,"");if(""===i)return{error:this.out("Please brush over the areas to remove objects before continuing.")};let o,a={image:i,filename:`${e}_${this.builder.getId()}.png`,customData:this.builder.settings.customData};o="replicate"===t?this.builder.settings.uploadBase64Url:"fal"===t?this.builder.settings.uploadBase64Url_Fal:this.builder.settings.uploadBase64Url_Fal||this.builder.settings.uploadBase64Url;let l={"Content-Type":"application/json",...this.builder.settings.headers},c=await fetch(o,{signal:this.builder.mediaSignal,method:"POST",headers:l,body:JSON.stringify(a)}),d=await c.json();return d.ok&&(n=d.url),n?{url:n}:{error:this.out("Upload mask failed.")}}async processMediaInput(e,t){if(!e)return!1;let r;if(!this.isFullUrl(e)){let t=e;r=this.getFileInput(t)||this.getFileInput()}let s,n="";if(this.builder.photoBlob[e]){let r=this.builder.getId();const i=new FormData;let o;i.append("file",this.builder.photoBlob[e],`photo_${r}.jpg`),i.append("customData",this.builder.settings.customData),o="replicate"===t?this.builder.settings.uploadMediaUrl:"fal"===t?this.builder.settings.uploadMediaUrl_Fal:this.builder.settings.uploadMediaUrl_Fal||this.builder.settings.uploadMediaUrl;const a=await fetch(o,{method:"POST",body:i}),l=await a.json();return l.ok?(s=l.url,n=l.filename,{filename:n,url:s}):{error:this.out("Upload file failed.")}}if(r){const i=r.files[0];if(i){n=i.name;const e=new FormData;let r;e.append("file",i),e.append("customData",this.builder.settings.customData),r="replicate"===t?this.builder.settings.uploadMediaUrl:"fal"===t?this.builder.settings.uploadMediaUrl_Fal:this.builder.settings.uploadMediaUrl_Fal||this.builder.settings.uploadMediaUrl;const o=await fetch(r,{method:"POST",body:e}),a=await o.json();if(!a.ok)return{error:this.out("Upload file failed.")};s=a.url,n=a.filename}else s=e}else s=e;return{filename:n,url:s}}getFileInput(e){let t;if(this.builder.settings.isBuilder){if(!this.builder.settings.previewSelector)return console.log("previewSelector not set."),null;t=document.querySelector(this.builder.settings.previewSelector)}else t=this.builder.element;return t?e?t.querySelector(`input[type="file"][name="${e}"]`):t.querySelector('input[type="file"]'):null}isFullUrl(e){return-1!==e.indexOf("/")}out(e){if(this.opts.lang){let t=this.opts.lang[e];return t||e}return e}}class he{constructor(e,t={}){this.settings=Object.assign({},{lang:[]},t),this.empty=!0,this.element=e,this.init()}loadUrl(e){this.element.querySelector("img").src=e,this.loaded()}loadImage(e){if(e){const t=new FileReader;t.onload=e=>{this.element.querySelector("img").setAttribute("src",e.target.result)}
1,t.readAsDataURL(e)}}setImage(e){if(e){this.element.querySelector("img").src=e}}clearImage(){this.element.style.display=""}out(e){let t=this.settings.lang[e];return t||e}init(){const e=this.element;e.className="imagemask-wrapper";const t=document.createElement("div");t.className="imagemask-overlay",e.appendChild(t);const r=document.createElement("button");r.className="btn-close-imagemask",r.title=this.out("Close"),r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" \n        viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"  \n        stroke-linejoin="round" class="icon-close">\n            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>\n            <path d="M18 6l-12 12" /><path d="M6 6l12 12" />\n        </svg>',e.appendChild(r);const s=document.createElement("div");s.className="imagemask-body",e.appendChild(s);const n=document.createElement("div");n.className="imagemask-container",s.appendChild(n);const i=document.createElement("div");i.className="imagemask-controls",s.appendChild(i);const o=document.createElement("label");i.appendChild(o),o.innerHTML=`${this.out("Brush Size")}: \n            <input type="range" class="brush-size" min="5" max="100" value="30">`;const a=o.querySelector(".brush-size"),l=document.createElement("button");l.className="btn-undobrush",l.title=this.out("Undo"),l.innerHTML='\n        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  \n        class="icon-undo">\n                <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>\n                <path d="M9 14l-4 -4l4 -4"></path>\n                <path d="M5 10h11a4 4 0 1 1 0 8h-1"></path>\n        </svg>',i.appendChild(l);const c=document.createElement("button");c.className="btn-redobrush",c.title=this.out("Redo"),c.innerHTML='\n        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  \n        class="icon-redo">\n            <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>\n            <path d="M15 14l4 -4l-4 -4"></path>\n            <path d="M19 10h-11a4 4 0 1 0 0 8h1"></path>\n        </svg>',i.appendChild(c);const d=document.createElement("button");d.className="btn-clearbrush",d.title=this.out("Clear"),d.innerHTML='\n        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" \n        stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" \n        class="icon-eraser">\n            <path stroke="none" d="M0 0h24v24H0z" fill="none"/>\n            <path d="M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3" />\n            <path d="M18 13.3l-6.3 -6.3" /><\n        /svg>',i.appendChild(d);const u=document.createElement("button");u.className="btn-enlargemask",d.title=this.out("Enlarge"),u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"  \n        fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" \n        class="icon-maximize">\n        <path stroke="none" d="M0 0h24v24H0z" fill="none"/>\n            <path d="M16 4l4 0l0 4" /><path d="M14 10l6 -6" />\n            <path d="M8 20l-4 0l0 -4" /><path d="M4 20l6 -6" />\n            <path d="M16 20l4 0l0 -4" /><path d="M14 14l6 6" />\n            <path d="M8 4l-4 0l0 4" /><path d="M4 4l6 6" />\n        </svg>',i.appendChild(u);const p=document.createElement("input");p.type="hidden",p.name=this.settings.name,p.className="inp-imagemask",p.value="",s.appendChild(p);const h=document.createElement("canvas");h.className="imagemask";const m=h.getContext("2d",{willReadFrequently:!0}),g=document.createElement("canvas"),f=g.getContext("2d",{willReadFrequently:!0}),b=this.element.querySelector(".inp-imagemask"),y=e=>{const t=document.createElement("canvas"),r=t.getContext("2d",{willReadFrequently:!0});t.width=e.width,t.height=e.height,r.clearRect(0,0,e.width,e.height),r.fillStyle="black",r.fillRect(0,0,e.width,e.height),r.drawImage(e,0,0);const s=t.toDataURL("image/png");let n=document.querySelector(".imagemask-output");n||(n=document.createElement("img"),n.className="imagemask-output",document.body.appendChild(n)),n.src=s,this.empty||(b.value=s)};let v=[],k=[];const w=()=>{v.push(g.toDataURL()),v.length>10&&v.shift(),k=[]},x=e=>{const t=new Image;t.src=e,t.onload=()=>{m.clearRect(0,0,h.width,h.height),m.drawImage(t,0,0,h.width,h.height),f.clearRect(0,0,g.width,g.height),f.drawImage(t,0,0,g.width,g.height),y(g)}};h.addEventListener("mousedown",(()=>{w()})),l.addEventListener("click",(e=>{e.preventDefault(),v.length>0&&(k.push(h.toDataURL()),x(v.pop()))})),c.addEventListener("click",(e=>{e.preventDefault(),k.length>0&&(v.push(h.toDataURL()),x(k.pop()))}));const _=document.createElement("img");n.appendChild(_),n.appendChild(h),this.loaded=()=>{n.style.display="flex";document.querySelector(".imagemask-controls").style.display="flex",e.style.display="flex",C(),v=[],k=[],m.clearRect(0,0,h.width,h.height),f.clearRect(0,0,g.width,g.height),this.empty=!0,b.value="";try{y(g)}catch(e){}},_.onload=()=>{this.loaded()};let E=null,L=null;const C=()=>{h.width>0&&h.height>0&&(E=m.getImageData(0,0,h.width,h.height),L=f.getImageData(0,0,g.width,g.height));const e=_.offsetWidth,t=_.offsetHeight,r=window.devicePixelRatio||1;h.width=e*r,h.height=t*r,m.scale(r,r),h.style.width=`${e}px`,h.style.height=`${t}px`;
1const s=_.naturalWidth,n=_.naturalHeight;if(g.width=s*r,g.height=n*r,f.scale(r,r),g.style.width=`${s}px`,g.style.height=`${n}px`,E){const e=document.createElement("canvas");e.width=E.width,e.height=E.height;e.getContext("2d").putImageData(E,0,0);const t=document.createElement("canvas");t.width=L.width,t.height=L.height;t.getContext("2d").putImageData(L,0,0),m.drawImage(e,0,0,E.width,E.height,0,0,h.width,h.height),f.drawImage(t,0,0,L.width,L.height,0,0,g.width,g.height)}};let R=!1,T=parseInt(a.value,10);a.addEventListener("input",(e=>{T=parseInt(e.target.value,10)}));const S=e=>{R=!0,M(e)},q=()=>{R=!1,m.beginPath(),this.empty=!1,y(g)},M=e=>{if(!R)return;const{x:t,y:r}=(e=>{const t=h.getBoundingClientRect();if(e.touches){const r=e.touches[0];return{x:r.clientX-t.left,y:r.clientY-t.top}}return{x:e.clientX-t.left,y:e.clientY-t.top}})(e),s=g.width/h.width,n=t*s,i=r*(g.height/h.height);m.fillStyle="rgb(255, 255, 255)",m.beginPath(),m.arc(t,r,T/2,0,2*Math.PI),m.fill(),f.fillStyle="rgb(255, 255, 255)",f.beginPath(),f.arc(n,i,T/2*s,0,2*Math.PI),f.fill()};h.addEventListener("mousedown",S),h.addEventListener("mouseup",q),h.addEventListener("mousemove",M),h.addEventListener("touchstart",(e=>{S(e),e.preventDefault()}),{passive:!1}),h.addEventListener("touchend",(e=>{q(),e.preventDefault()})),h.addEventListener("touchmove",(e=>{M(e),e.preventDefault()}),{passive:!1}),d.addEventListener("click",(e=>{e.preventDefault(),w(),m.clearRect(0,0,h.width,h.height),f.clearRect(0,0,g.width,g.height),this.empty=!0,b.value="",y(g)})),window.addEventListener("resize",C);const $=s=>{s?(e.setAttribute("aria-modal","true"),e.setAttribute("role","dialog"),e.classList.add("fullscreen"),t.style.display="block",r.style.display="flex",u.style.display="none"):(e.removeAttribute("aria-modal"),e.removeAttribute("role"),e.classList.remove("fullscreen"),t.style.display="none",r.style.display="none",u.style.display=""),C()};u.addEventListener("click",(e=>{e.preventDefault(),$(!0)})),r.addEventListener("click",(e=>{e.preventDefault(),$(!1)})),document.addEventListener("keydown",(e=>{"Escape"===e.key&&$(!1)}))}}return class{constructor(e,t={}){this.settings=Object.assign({},{lang:[],headers:{},fileUploadText:"Drag and drop your file here.",multiFileUploadText:"Drag and drop your files here.",model:"gpt-4o-mini",model2:"gpt-4o-mini",sendCommandUrl:"/sendcommand",sendCommandStreamUrl:"/getstream",consoleLog:!1,saveResults:!1,disableMediaGeneration:!1,disableMediaGenerationTitle:"Demo Info",disableMediaGenerationMessage:"This is an online demo and media generation is currently disabled. Get the full version for complete functionality.",submitText:"Submit",resetText:"Reset",scrapeProvider:"firecrawl",scrapeLimit:6,scrapeExclude:["youtube.com","reddit.com","microsoft.com","mozilla.org"],inputCost:.15,outputCost:.6,_2dIllustrationStyleId:"bcaa0104-98ef-4cb8-a012-124dad015756",templateFilters:["all","image","video","audio","text"],templatesConfig:{fal:!0,replicate:!1,web:!1},defaultMediaGenerationProvider:"fal",replicateEndpoint1:"https://api.replicate.com/v1/predictions",replicateEndpoint2:"https://api.replicate.com/v1/models/{MODEL}/predictions",falStatusEndpoint:"https://queue.fal.run/{MODEL}/requests/{REQUEST_ID}/status",falResultEndpoint:"https://queue.fal.run/{MODEL}/requests/{REQUEST_ID}",replicateStatusEndpoint:"https://api.replicate.com/v1/predictions/{REQUEST_ID}",defaultModels:{image_generation:{openai:["gpt-image-1"]},image_variation_generation:{openai:["gpt-image-1"]},text_to_image_generation:{fal:["fal-ai/flux/schnell","fal-ai/flux/dev","fal-ai/flux-pro/v1.1","fal-ai/flux-pro/v1.1-ultra","fal-ai/recraft-v3","fal-ai/recraft-20b","fal-ai/ideogram/v2a","fal-ai/hidream-i1-fast","fal-ai/hidream-i1-dev","fal-ai/hidream-i1-full","fal-ai/gemini-flash-edit/multi"],replicate:["black-forest-labs/flux-schnell","black-forest-labs/flux-dev","black-forest-labs/flux-1.1-pro","black-forest-labs/flux-1.1-pro-ultra","recraft-ai/recraft-v3","ideogram-ai/ideogram-v2a"],google:["gemini-2.0-flash-exp-image-generation"],openai:["gpt-image-1"]},image_to_video_generation:{fal:["fal-ai/kling-video/v1.6/standard/image-to-vi
1deo","fal-ai/kling-video/v1.6/pro/image-to-video","fal-ai/kling-video/v2/master/image-to-video","fal-ai/minimax/video-01-live/image-to-video","fal-ai/luma-dream-machine/ray-2/image-to-video"],replicate:["kwaivgi/kling-v1.6-standard","kwaivgi/kling-v1.6-pro","minimax/video-01-live","luma/ray"]},text_to_video_generation:{fal:["fal-ai/kling-video/v1.6/standard/text-to-video","fal-ai/kling-video/v2/master/text-to-video","fal-ai/minimax/video-01-live ","fal-ai/luma-dream-machine/ray-2"],replicate:["kwaivgi/kling-v1.6-standard","minimax/video-01","luma/ray"]},upscale_image:{fal:["fal-ai/clarity-upscaler"],replicate:["recraft-ai/recraft-crisp-upscale"]},describe_image:{fal:["fal-ai/any-llm/vision"],replicate:[]},edit_area_in_image:{fal:["fal-ai/flux-pro/v1/fill"],replicate:["black-forest-labs/flux-fill-pro"],google:["gemini-2.0-flash-exp-image-generation"],openai:["gpt-image-1"]},edit_image:{fal:["fal-ai/gemini-flash-edit"],replicate:[],openai:["gpt-image-1"]},text_to_2d_illustration_generation:{fal:["fal-ai/recraft-v3"],replicate:[]},text_to_digital_illustration_generation:{fal:["fal-ai/recraft-v3"],replicate:["recraft-ai/recraft-v3"]},text_to_book_cover_generation:{fal:["fal-ai/recraft-v3"],replicate:[]},text_to_speech:{fal:["fal-ai/elevenlabs/tts/multilingual-v2"],replicate:["jaaari/kokoro-82m:f559560eb822dc509045f3921a1921234918b91739db4bf3daab2169b71c7a13"]}},ttsMaxCharacters:3e3,alwaysVisibleSubmit:!1},t),this.listeners={},window._txt&&(this.settings.lang=window._txt),this.steps=[];let r=this.settings.onChange;if(this.settings.onChange=e=>{r&&r.call(this,e)},!e)throw new Error("A valid DOM element is required.");e.classList.add("formview-container"),e.classList.add("fb-ui"),this.element=e,this.media=new ue({lang:this.settings.lang},this),this.upload=new pe({lang:this.settings.lang},this)}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),this}off(e,t){this.listeners[e]&&this.listeners[e].delete(t)}trigger(e,t){this.listeners[e]&&this.listeners[e].forEach((e=>e(t)))}async loadTemplates(){if(!this.settings.templatesUrl)return void console.log(this.out("Template URL is not set."));let e=document.querySelector(this.settings.templatesSelector);if(e){e.classList.remove("hidden"),e.classList.add("formtemplates-container"),e.classList.add("fb-ui");const t=await fetch(this.settings.templatesUrl,{method:"GET"});let r=(await t.json()).data;e.innerHTML="";let s=r.filter((e=>{const t=e.supports||[];if(0===t.length)return!0;const{fal:r,replicate:s,web:n,openai:i,google:o}=this.settings.templatesConfig;return!(!n&&t.includes("web"))&&(!(!o&&t.includes("google"))&&(!(!i&&t.includes("openai"))&&(r||s?!r&&t.includes("fal")?t.includes("replicate"):!(!s&&t.includes("replicate"))||t.includes("fal"):!(t.includes("fal")||t.includes("replicate")))))}));r=s;const n=this.settings.templateFilters,i={all:{desc:this.out("All")},image:{desc:this.out("Image")},video:{desc:this.out("Video")},audio:{desc:this.out("Audio")},web:{desc:this.out("Web")},text:{desc:this.out("Text")}},o=document.createElement("div");o.className="app-filters",e.appendChild(o);const a=document.createElement("ul");a.className="app-list",e.appendChild(a);const l=e=>{const t=r.filter((t=>"all"===e||t.categories.includes(e)));this.renderList(t,a)};n.forEach((e=>{const t=document.createElement("button");t.textContent=i[e].desc,t.setAttribute("data-value",e),"all"===e&&t.classList.add("active"),t.addEventListener("click",(()=>{o.querySelectorAll("button").forEach((e=>e.classList.remove("active"))),t.classList.add("active"),l(e)})),o.appendChild(t)})),l("all")}}renderList(e,t){t.innerHTML="",e.forEach((e=>{if(e.name){const r=document.createElement("li");t.appendChild(r);const s=document.createElement("a");s.setAttribute("href","#");let n=this.settings.assetsFolder,i=e.form.thumbnail,o="";if(n&&i){let t=n+i;o=`<img class="thumbnail" src="${t}" alt="${e.name}" />`,e.form.thumbnailFit&&(o=`<img class="thumbnail" style="object-fit:${e.form.thumbnailFit}" src="${t}" alt="${e.name}" />`)}const a=document.createElement("div");a.className="div-template-buttons";let l=!1,c=!1;if(this.settings.templateButtons&&this.settings.templateButtons.viewButton&&this.settings.templateButtons.viewButton.text){const t=document.createElement("button");t.className="btn-template-view",t.innerText=this.out(this.settings.templateButtons.viewButton.text),a.appendChild(t),t.addEventListener("click",(t=>{t.preventDefault(),this.isGenerating?alert(this.out("Please wait until generation is complete.")):(this.settings.onSelectTemplate&&this.settings.onSelectTemplate(e),this.trigger("templateView",e))})),l=!0}if(this.settings.templateButtons&&this.settings.templateButtons.useButton&&this.settings.templateButtons.useButton.text){const t=document.createElement("button");t.className="btn-template-use",t.innerText=this.out(this.settings.templateButtons.useButton.text),a.appendChild(t),t.addEventListener("click",(t=>{t.preventDefault(),this.settings.onSelectTemplate&&this.settings.onSelectTemplate(e),this.trigger("templateUse",e)})),c=!0}s.innerHTML=`\n                    ${o}\n                    <div class="card-text">\n                        <div class="title">${e.name}</div>\n                        <div class="description">${e.form.description}</div>\n                        ${e.info?` <div class="info mt-1">${e.info}</div>`:""}\n                    </div>\n                `,l||c?(s.querySelector(".card-text").appendChild(a),s.classList.remove("cursor-pointer"),s.classList.add("cursor-default")):(s.classList.add("cursor-pointer"),s.classList.remove("cursor-default")),r.appendChild(s),l||c||s.addEventListener("click",(t=>{t.preventDefault(),this.isGenerating?alert(this.out("Please wait until generation is complete.")):(this.settings.onSelectTemplate&&this.settings.onSelectTemplate(e),this.trigger("templateSelect",e))}))}}))}addResultTool(){const e=document.querySelector(this.settings.resultSelector);if(!e)return;let t=e.innerHTML;const r=(new DOMParser).parseFromString(t,"text/html"),s=r.querySelector(".result-tool");s&&s.remove();r.querySelectorAll(".link-view, .link-download, video, audio").forEach((e=>{e.remove()}));let n=!1;""===r.body.innerText.trim()&&(n=!0);const i=document.createElement("div");i.className="result-tool",e.appendChild(i);const o=document.createElement("button");o.className="btn-result-tool",o.innerHTML=`\n        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round">\n            <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" />\n        </svg>
1\n        <span>${this.out("Copy")}</span>\n        `,n||i.appendChild(o);const a=document.createElement("button");a.className="btn-result-tool",a.innerHTML=`\n        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round">\n            <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M4 7l16 0" /><path d="M10 11l0 6" /><path d="M14 11l0 6" /><path d="M5 7l1 12a2 2 0 0 0 2 2h8a2 2 0 0 0 2 -2l1 -12" /><path d="M9 7v-3a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v3" />\n        </svg>\n        <span>${this.out("Clear")}</span>\n        `,i.appendChild(a),o&&o.addEventListener("click",(t=>{t.preventDefault();const r=e.cloneNode(!0),s=r.querySelector(".result-tool");s&&s.remove();r.querySelectorAll(".link-view, .link-download").forEach((e=>{e.remove()})),r.style.position="fixed",r.style.left="-9999px",document.body.appendChild(r);const n=r.innerText.trim();document.body.removeChild(r),navigator.clipboard.writeText(n),o.innerHTML=`\n            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round">\n                <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path stroke="none" d="M0 0h24v24H0z" /><path d="M7 9.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2 2 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" /><path d="M11 14l2 2l4 -4" />\n            </svg>\n            <span>${this.out("Copied")}</span>\n            `,setTimeout((()=>{o.innerHTML=`\n                <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round">\n                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 7m0 2.667a2.667 2.667 0 0 1 2.667 -2.667h8.666a2.667 2.667 0 0 1 2.667 2.667v8.666a2.667 2.667 0 0 1 -2.667 2.667h-8.666a2.667 2.667 0 0 1 -2.667 -2.667z" /><path d="M4.012 16.737a2.005 2.005 0 0 1 -1.012 -1.737v-10c0 -1.1 .9 -2 2 -2h10c.75 0 1.158 .385 1.5 1" />\n                </svg>\n                <span>${this.out("Copy")}</span>\n                `}),600)})),a.addEventListener("click",(t=>{t.preventDefault(),localStorage.removeItem("_results"),localStorage.removeItem("_results_html"),e.innerHTML=""}))}getScrollableParent(e){for(;e.parentElement;){const t=window.getComputedStyle(e.parentElement).overflowY;if(("auto"===t||"scroll"===t)&&e.parentElement.scrollHeight>e.parentElement.clientHeight)return e.parentElement;e=e.parentElement}return null}stickyElement(e){if(!this.settings.alwaysVisibleSubmit)return;const t=this.getScrollableParent(e);let r;this._scrollListener&&(t?t.removeEventListener("scroll",this._scrollListener):window.removeEventListener("scroll",this._scrollListener),window.removeEventListener("resize",this._resizeListener));const s=()=>{e.style.position="",r=t?e.offsetTop+e.offsetHeight-t.offsetTop:e.offsetTop+e.offsetHeight},n=()=>{if(t){if(t.offsetHeight+t.scrollTop>r)e.style.position="",e.style.top="";else{const t=window.innerHeight-e.offsetHeight;e.style.position="fixed",e.style.top=`${t}px`}}else{if(window.innerHeight+window.scrollY>r)e.style.position="",e.style.top="";else{const t=window.innerHeight-e.offsetHeight;e.style.position="fixed",e.style.top=`${t}px`}}0!==e.parentNode.offsetWidth&&(e.style.width=`${e.parentNode.offsetWidth}px`)};let i;this._scrollListener=n,this._resizeListener=()=>{i&&clearTimeout(i),i=setTimeout((()=>{let t=null;const r=()=>{const i=e.offsetTop;i===t?(s(),n()):(t=i,requestAnimationFrame(r))};r()}),200)},s(),n(),t?t.addEventListener("scroll",n):window.addEventListener("scroll",n),window.addEventListener("resize",this._resizeListener)}view(e){if(!e)return;let t,r;try{t=JSON.parse(e)}catch(e){return void console.log("Invalid JSON Form.")}if(this.json=t,this.inputListener=()=>{clearTimeout(this.debounceTimeout),this.debounceTimeout=setTimeout((()=>{const e=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(e)}
1),300)},this.changeListener=()=>{const e=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(e)},this.settings.isBuilder){if(!this.settings.previewSelector)return void(this.settings.consoleLog&&console.log("previewSelector not set."));r=document.querySelector(this.settings.previewSelector)}else r=this.element;if(r){r.classList.remove("hidden"),r.classList.add("formview-container"),r.classList.add("fb-ui"),r.innerHTML="";if(!(t.hideHeader||!1)){const e=document.createElement("div");e.className="form-header",r.appendChild(e);const s=document.createElement("h1");s.className="form-title",s.innerText=t.title||this.out("Your Form Title Here"),e.appendChild(s);const n=document.createElement("p");n.className="form-desc",n.innerText=t.description||this.out("Your Description Here"),e.appendChild(n)}let e;e=this.settings.isBuilder?document.createElement("form"):document.createElement("div"),e.className="form-wrapper",e.style.flexFlow="wrap",r.appendChild(e);let s,n,i=1;if(t.elements&&t.elements.forEach((t=>{if("spacer"===t.type){const r=document.createElement("div");return r.className="form-spacer",t.spacerHeight&&!isNaN(parseFloat(t.spacerHeight))&&(r.style.height=t.spacerHeight+"px"),void(t.displayInOutput||e.appendChild(r))}if("separator"===t.type){const r=document.createElement("hr");return r.style.borderTopColor=t.color,void(t.displayInOutput||e.appendChild(r))}if("html"===t.type){if(t.html){const r=document.createElement("div");r.innerHTML=t.html,t.displayInOutput||e.appendChild(r)}return}if("heading"===t.type){const r=document.createElement(t.heading||"h2");return r.innerHTML=t.headingText||this.out("Your Heading Here!"),void(t.displayInOutput||e.appendChild(r))}if("paragraph"===t.type){const r=document.createElement("p");return r.innerHTML=t.paragraphText||this.out("Your paragraph content here!"),void(t.displayInOutput||e.appendChild(r))}if("media"===t.type){if("video"===t.tag){const s=document.createElement("video");s.style.width="100%",s.style.height="auto",s.controls=!0;var r=document.createElement("source");r.src=t.url,r.type="video/mp4",s.appendChild(r),t.displayInOutput||e.appendChild(s)}else if("audio"===t.tag){const r=document.createElement("audio");r.controls=!0;let s=document.createElement("source");s.src=t.url,s.type="audio/mp3",r.appendChild(s),t.displayInOutput||e.appendChild(r)}else if("img"===t.tag){const r=document.createElement("img");r.src=t.url,r.setAttribute("alt",this.out("Output Image")),t.displayInOutput||e.appendChild(r)}return}if("image"===t.type){const r=document.createElement("img");return r.src=t.url,r.setAttribute("alt",this.out("Output Image")),void(t.displayInOutput||e.appendChild(r))}if("video"===t.type){const r=document.createElement("video");r.style.width="100%",r.style.height="auto",r.controls=!0;let s=document.createElement("source");return s.src=t.url,s.type="video/mp4",r.appendChild(s),void(t.displayInOutput||e.appendChild(r))}if("audio"===t.type){const r=document.createElement("audio");r.controls=!0;let s=document.createElement("source");return s.src=t.url,s.type="audio/mp3",r.appendChild(s),void(t.displayInOutput||e.appendChild(r))}const s=document.createElement("div");s.className="form-field","hidden"===t.type&&(s.className="hidden"),t.displayInOutput||e.appendChild(s),"color"===t.type&&s.classList.add("field-color");const n=t.type;let o=t.name;if(e.querySelector(`[name="${o}"]`)&&(i++,o=o+"_"+i),"short-text"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`short_text_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`short_text_label_${e}`,n.type="text",n.name=o,n.value=t.value||"",n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("long-text"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`long_text_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");
1e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("textarea");n.id=`long_text_label_${e}`,n.name=o,n.value=t.value||"",n.className="inp-base",n.style.height=t.height+"px",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("number"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`number_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`number_label_${e}`,n.type="number",n.name=o,n.value=t.value||"",n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("slider"===n){s.classList.add("input-slider");let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`number_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("div");n.className="slider-container",s.appendChild(n);const i=document.createElement("div");i.className="slider-values",n.appendChild(i);const a=document.createElement("span");i.appendChild(a),a.innerText=t.minValue;const l=document.createElement("span");i.appendChild(l),l.innerText=t.maxValue;const c=document.createElement("input");c.id=`number_label_${e}`,c.type="range",c.name=o,c.setAttribute("min",t.minValue),c.setAttribute("max",t.maxValue),c.setAttribute("step",t.step),c.setAttribute("value",t.value||0),n.appendChild(c);const d=document.createElement("div");d.className="current-value",n.appendChild(d),n.querySelector(".current-value").textContent=t.value||0,c.addEventListener("input",(()=>{n.querySelector(".current-value").textContent=c.value}))}if("select"===n){let e=this.getId();const r=document.createElement("div");if(r.id=`radio_group_label_${e}`,r.className="field-label-normal",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("div");if(n.setAttribute("aria-labelledby",`radio_group_label_${e}`),n.setAttribute("role","group"),n.className="div-options",s.appendChild(n),t.choices&&t.choices.forEach(((r,s)=>{let i=r;t.choicesText&&(i=t.choicesText[s]||r);const a=document.createElement("label");a.setAttribute("for",`${e}_${s}`),a.className="option-label",n.appendChild(a);const l=document.createElement("input");l.type="radio",l.className="peer",l.id=`${e}_${s}`,l.name=o,l.value=r,a.appendChild(l),s===t.selected&&(l.checked=!0);const c=document.createElement("span");c.className="peer-span-rounded",a.appendChild(c);c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M12 7a5 5 0 1 1 -4.995 5.217l-.005 -.217l.005 -.217a5 5 0 0 1 4.995 -4.783z"></path></svg>',0===s&&t.isRequired&&l.setAttribute("required","required");const d=document.createElement("span");d.innerText=i,a.appendChild(d),l.addEventListener("change",this.changeListener)})),t.showOtherItem){const r=document.createElement("label");r.setAttribute("for",e+"_other"),r.className="option-label",n.appendChild(r);const i=document.createElement("input");i.type="radio",i.className="peer",i.id=e+"_other",i.name=o,i.value="other",r.appendChild(i);const a=document.createElement("span");a.className="peer-span-rounded",r.appendChild(a);const l='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path stroke="none" d="M0 0h24v24H0z" fill="none"></path><path d="M12 7a5 5 0 1 1 -4.995 5.217l-.005 -.217l.005 -.217a5 5 0 0 1 4.995 -4.783z"></path></svg>';a.innerHTML=l;const c=document.createElement("span");c.innerText=t.otherText,r.appendChild(c);const d=document.createElement("div");s.appendChild(d);const u=document.createElement("input");u.type="text",u.name=o+"_other",u.className="inp-base",d.appendChild(u),i.addEventListener("change",this.changeListener),u.addEventListener("input",this.inputListener)}}if("multi-select"===n){let e=this.getId();const r=document.createElement("div");if(r.id=`checkbox_group_label_${e}`,r.className="field-label-normal",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");
1e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("div");if(n.setAttribute("aria-labelledby",`checkbox_group_label_${e}`),n.setAttribute("role","group"),n.className="div-options",s.appendChild(n),t.choices&&t.choices.forEach(((r,s)=>{let i=r;t.choicesText&&(i=t.choicesText[s]||r);const a=document.createElement("label");a.setAttribute("for",`${e}_${s}`),a.className="option-label",n.appendChild(a);const l=document.createElement("input");l.type="checkbox",l.className="peer",l.id=`${e}_${s}`,l.name=o+"[]",l.value=r,a.appendChild(l);const c=document.createElement("span");c.className="peer-span-square",a.appendChild(c);c.innerHTML='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="4"  stroke-linecap="round"  stroke-linejoin="round">\n                                <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 12l5 5l10 -10" />\n                            </svg>';const d=document.createElement("span");d.innerText=i,a.appendChild(d),l.addEventListener("change",this.changeListener)})),t.showOtherItem){const r=document.createElement("label");r.setAttribute("for",e+"_other"),r.className="option-label",n.appendChild(r);const i=document.createElement("input");i.type="checkbox",i.className="peer",i.id=e+"_other",i.name=o,i.value="other",r.appendChild(i);const a=document.createElement("span");a.className="peer-span-square",r.appendChild(a);const l='<svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="4"  stroke-linecap="round"  stroke-linejoin="round">\n                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 12l5 5l10 -10" />\n                        </svg>';a.innerHTML=l;const c=document.createElement("span");c.innerText=t.otherText,r.appendChild(c);const d=document.createElement("div");s.appendChild(d);const u=document.createElement("input");u.type="text",u.name=o+"_other",u.className="inp-base",d.appendChild(u),i.addEventListener("change",this.changeListener),u.addEventListener("input",this.inputListener)}}if("switch"===n){let e=this.getId();const r=document.createElement("label");if(r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),r.id=`switch_${e}`,s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("div");n.className="switch",n.tabIndex=0,n.role="switch",n.setAttribute("aria-labelledby",`switch_${e}`),n.setAttribute("aria-checked","false"),n.setAttribute("data-checked","false"),s.appendChild(n);const i=document.createElement("div");i.className="switch-thumb",n.appendChild(i);const a=document.createElement("input");a.id=`switch_${e}`,a.type="text",a.name=o,a.style.cssText="opacity:0.01;width:1px;height:1px;position:absolute;bottom:0px;left:25px;",a.setAttribute("tabindex","-1"),t.isRequired&&(a.setAttribute("required","required"),a.setCustomValidity(this.out("Please toggle this switch to proceed."))),n.appendChild(a),"true"===t.value?(n.setAttribute("aria-checked","true"),n.setAttribute("data-checked","true"),a.value="true",t.isRequired&&a.setCustomValidity("")):(n.setAttribute("aria-checked","false"),n.setAttribute("data-checked","false"),a.value="false",t.isRequired&&a.setCustomValidity(this.out("Please toggle this switch to proceed."))),r.addEventListener("click",(()=>{n.focus()}));const l=()=>{const e="true"===n.getAttribute("aria-checked");n.setAttribute("aria-checked",!e),n.setAttribute("data-checked",!e),e?(a.value="false",t.isRequired&&a.setCustomValidity(this.out("Please toggle this switch to proceed."))):(a.value="true",t.isRequired&&a.setCustomValidity(""));const r=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(r)};n.addEventListener("keydown",(e=>{" "!==e.key&&"Enter"!==e.key||(e.preventDefault(),l())})),n.addEventListener("click",(()=>{l()}))}if("dropdown"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`dropdown_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");
1e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("div");n.className="relative",s.appendChild(n);const i=document.createElement("div");i.className="relative inline-block",n.appendChild(i);const a=document.createElement("select");a.id=`dropdown_${e}`,a.name=o,t.isRequired&&a.setAttribute("required","required"),i.appendChild(a);const l=document.createElement("option");if(l.setAttribute("selected","selected"),l.setAttribute("disabled","disabled"),l.value="",l.innerText=t.placeholder,a.appendChild(l),t.choices&&t.choices.forEach(((e,r)=>{let s=e;t.choicesText&&(s=t.choicesText[r]||e);const n=document.createElement("option");n.value=e,n.innerText=s,a.appendChild(n),r===t.selected&&(l.remove(),n.setAttribute("selected","selected"))})),t.showOtherItem){const e=document.createElement("option");e.value="other",e.innerText=t.otherText,a.appendChild(e)}const c=document.createElement("div");c.className="select-arrow",i.appendChild(c),this.appendHtml(c,'\n                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">\n                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />\n                        </svg>\n                        ');const d=document.createElement("input");d.type="text",d.id=`input_other_${e}`,d.name=o+"_other",d.className="input-other hidden inp-base",s.appendChild(d);const u=s.querySelector(`#dropdown_${e}`),p=s.querySelector(`#input_other_${e}`);u.addEventListener("change",(()=>{"other"===u.value?(p.classList.remove("hidden"),p.focus()):p.classList.add("hidden");const e=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(e)})),d.addEventListener("input",this.inputListener)}if("date"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`date_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`date_${e}`,n.type="date",n.name=o,n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("change",this.changeListener)}if("time"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`time_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");
1n.id=`time_${e}`,n.type="time",n.name=o,n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("change",this.changeListener)}if("datetime"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`datetime_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`datetime_${e}`,n.type="datetime-local",n.name=o,n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("change",this.changeListener)}if("color"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`color_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`color_${e}`,n.type="color",n.name=o,n.value=t.value||"",n.className="input-color",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("file"===n||"multifile"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`file_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const i=document.createElement("div");i.className="file-input-wrapper","file"===n&&i.setAttribute("aria-label",this.out(this.settings.fileUploadText)),"multifile"===n&&i.setAttribute("aria-label",this.out(this.settings.multiFileUploadText)),s.appendChild(i);const a=document.createElement("input");a.id=`input_url_label_${e}`,a.type="text",a.name=o+"__url",a.value=t.value||"",a.className="inp-base input-file-url",a.placeholder=t.placeholder||this.out("Enter URL."),s.appendChild(a),a.addEventListener("input",(()=>{const e=s.querySelector(".btn-clearfile");e&&e.click(),this.inputListener(),""!==a.value?t.isRequired&&l.removeAttribute("required"):t.isRequired&&l.setAttribute("required","required"),$(a.value)})),t.useURL?a.style.display="":a.style.display="none";const l=document.createElement("input");l.id=`file_${e}`,l.type="file","multifile"===n&&(l.multiple=!0),l.name=o,t.isRequired&&l.setAttribute("required","required"),l.className="peer",i.appendChild(l);const c=document.createElement("div");c.className="file-drop-area",i.appendChild(c);const d=document.createElement("div");let u,p,h;d.className="file-controls",d.id=`drag_message_${e}`,i.appendChild(d),(!t.source||t.source&&"local"===t.source||t.source&&"local_and_camera"===t.source)&&(u=document.createElement("div"),u.className="file-drop-info","file"===n&&(u.innerHTML=this.out(this.settings.fileUploadText)),"multifile"===n&&(u.innerHTML=this.out(this.settings.multiFileUploadText)),d.appendChild(u)),(!t.source||t.source&&"local"===t.source||t.source&&"local_and_camera"===t.source)&&(p=document.createElement("button"),p.className="btn-selectfile",p.innerHTML=`\n                        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-folder-open"><path stroke="none" d="M0 0h24v24H0z" fill="none"/>\n                            <path d="M5 19l2.757 -7.351a1 1 0 0 1 .936 -.649h12.307a1 1 0 0 1 .986 1.164l-.996 5.211a2 2 0 0 1 -1.964 1.625h-14.026a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2h4l3 3h7a2 2 0 0 1 2 2v2" />\n                        </svg>\n                        ${this.out("Select File")}\n                        `,d.appendChild(p)),(t.source&&"camera"===t.source||t.source&&"local_and_camera"===t.source)&&(h=document.createElement("button"),h.className="btn-takephoto",h.innerHTML=`\n                        <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-camera">\n                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2" /><path d="M9 13a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" />\n                        </svg>\n                        ${this.out("Take Photo")}\n                        `,d.appendChild(h));
1const m=document.createElement("div");m.className="file-preview-container",i.appendChild(m);const g=document.createElement("div");g.className="file-drop-info-highlight",g.id=`file_name_${e}`,i.appendChild(g),p&&p.addEventListener("click",(e=>{e.preventDefault(),l.click()})),i.classList.add("disabledrop"),(!t.source||t.source&&"local"===t.source||t.source&&"local_and_camera"===t.source)&&(i.classList.remove("disabledrop"),i.addEventListener("dragover",(e=>{e.preventDefault(),i.classList.add("drag-over")})),i.addEventListener("dragleave",(()=>{i.classList.remove("drag-over")})),"file"===n?i.addEventListener("drop",(e=>{e.preventDefault(),i.classList.remove("drag-over");const t=e.dataTransfer.files[0];t&&(l.files=e.dataTransfer.files,N(t))})):"multifile"===n&&i.addEventListener("drop",(e=>{e.preventDefault(),i.classList.remove("drag-over"),m.innerHTML="";const t=e.dataTransfer.files;t.length>0&&(l.files=t,Array.from(t).forEach((e=>{I(e)})))}))),"file"===n?l.addEventListener("change",(()=>{const e=l.files[0];e&&N(e)})):"multifile"===n&&l.addEventListener("change",(()=>{m.innerHTML="";const e=l.files;Array.from(e).forEach((e=>{e&&I(e)}))}));const f={images:[{type:"image/jpeg",extensions:".jpg, .jpeg"},{type:"image/png",extensions:".png"},{type:"image/gif",extensions:".gif"},{type:"image/webp",extensions:".webp"}],videos:[{type:"video/mp4",extensions:".mp4"},{type:"video/webm",extensions:".webm"},{type:"video/ogg",extensions:".ogg"},{type:"video/quicktime",extensions:".mov"}],audio:[{type:"audio/mpeg",extensions:".mp3"},{type:"audio/wav",extensions:".wav"}],documents:[{type:"application/pdf",extensions:".pdf"},{type:"application/json",extensions:".json"},{type:"text/plain",extensions:".txt"},{type:"text/csv",extensions:".csv"},{type:"application/msword",extensions:".doc"},{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",extensions:".docx"},{type:"application/vnd.ms-excel",extensions:".xls"},{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",extensions:".xlsx"}],others:[{type:"application/zip",extensions:".zip"},{type:"application/x-rar-compressed",extensions:".rar"}]};let b=[];(t.allowedFileTypes||["images","videos","audio","documents","others"]).forEac
1h((e=>{switch(e){case"images":b=b.concat(f.images);break;case"videos":b=b.concat(f.videos);break;case"audio":b=b.concat(f.audio);break;case"documents":b=b.concat(f.documents);break;case"others":b=b.concat(f.others)}}));const y=b.map((e=>e.type)).join(",");let v;if(l.setAttribute("accept",y),t.useImageMask){s.classList.add("image-mask");const e=document.createElement("div");s.appendChild(e),v=new he(e,{lang:this.settings.lang,name:o+"_mask"})}t.largePreview&&s.classList.add("large-preview");const k=()=>{const e=i.querySelector(".img-preview");e&&(e.remove(),t.useImageMask&&v.clearImage())};let w=`\n                        <div class="div-livevideo">\n                            <video class="livevideo" autoplay playsinline style="display:none"></video>\n                            <canvas class="photo-captured" style="display:none"></canvas>\n                            ${!t.source||t.source&&"local"===t.source||t.source&&"local_and_camera"===t.source?`<button class="btn-selectfile2" title="${this.out("Select File")}" style="display:none">\n                                    <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-folder-open"><path stroke="none" d="M0 0h24v24H0z" fill="none"/>\n                                        <path d="M5 19l2.757 -7.351a1 1 0 0 1 .936 -.649h12.307a1 1 0 0 1 .986 1.164l-.996 5.211a2 2 0 0 1 -1.964 1.625h-14.026a2 2 0 0 1 -2 -2v-11a2 2 0 0 1 2 -2h4l3 3h7a2 2 0 0 1 2 2v2" />\n                                    </svg>\n                                </button>\n                            `:""}\n                            <button class="btn-takephoto2" title="${this.out("Take Photo")}" style="display:none">\n                                <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-camera">\n                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2" /><path d="M9 13a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" />\n                                </svg>\n                            </button>\n\n                            <button class="btn-capturephoto" title="${this.out("Capture")}" style="display:none">\n                                <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-camera">\n                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M5 7h1a2 2 0 0 0 2 -2a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1a2 2 0 0 0 2 2h1a2 2 0 0 1 2 2v9a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-9a2 2 0 0 1 2 -2" /><path d="M9 13a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" />\n                                </svg>\n                            </button>\n                            <button type="button" class="btn-clearphoto" title="${this.out("Clear")}" style="display: none;">\n                                <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-eraser">\n                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3" /><path d="M18 13.3l-6.3 -6.3" />\n                                </svg>\n                            </button>\n                            <button type="button" class="btn-stopcamera" title="${this.out("Close")}" style="display: none;">\n                                <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="2"  stroke-linecap="round"  stroke-linejoin="round"  class="icon-close">\n                                    <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M18 6l-12 12" /><path d="M6 6l12 12" />\n                                </svg>\n                            </button>\n                        </div>\n                    `;this.appendHtml(i,w);const x=s.querySelector(".livevideo"),_=s.querySelector(".photo-captured"),E=s.querySelector(".btn-selectfile2"),L=s.querySelector(".btn-takephoto2"),C=s.querySelector(".btn-capturephoto"),R=s.querySelector(".btn-clearphoto"),T=s.querySelector(".btn-stopcamera");let S;this.photoBlob={},E&&E.addEventListener("click",(e=>{e.preventDefault(),p.click()}));const q=async()=>{const e=s.querySelector(".btn-clearfile");e&&e.click();try{S=await navigator.mediaDevices.getUserMedia({video:!0}),x.srcObject=S}catch(e){alert("Unable to access the camera."),x.style.display="none",C.style.display="none",T.style.display="none",d.style.display="none",g.style.display="none"}setTimeout((()=>{L.style.display="none",_.style.display="none",x.style.display="",C.style.display="",R.style.display="none",E&&(E.style.display="none"),L.style.display="none",T.style.display="",d.style.display="none",g.style.display="none"}),100)};h&&h.addEventListener("click",(async e=>{e.preventDefault(),q()})),L.addEventListener("click",(async e=>{e.preventDefault(),q()})),T.addEventListener("click",(()=>
1{S&&S.getTracks().forEach((e=>e.stop())),x.style.display="none",C.style.display="none",T.style.display="none",L.style.display="none",d.style.display="",g.style.display=""})),C.addEventListener("click",(e=>{if(e.preventDefault(),_.style.display="",_.width=x.videoWidth,_.height=x.videoHeight,_.getContext("2d").drawImage(x,0,0,_.width,_.height),S.getTracks().forEach((e=>e.stop())),x.style.display="none",C.style.display="none",R.style.display="",E&&(E.style.display=""),L.style.display="",T.style.display="none",_.toBlob((e=>{this.photoBlob[o]=e,l.removeAttribute("required")}),"image/jpeg"),L.style.display="",t.useImageMask){const e=_.toDataURL("image/jpeg");v.setImage(e)}}));const M=()=>{this.photoBlob[o]=null,_.style.display="none",_.getContext("2d").clearRect(0,0,_.width,_.height),""!==a.value?t.isRequired&&l.removeAttribute("required"):t.isRequired&&l.setAttribute("required","required"),R.style.display="none",E&&(E.style.display="none"),L.style.display="none",d.style.display="",g.style.display=""};R.addEventListener("click",(()=>{M()}));const $=(e,r)=>{const s=`.${e.split(".").pop().toLowerCase()}`;if(!b.some((e=>e.extensions.split(", ").includes(s))))return;let n=f.images.some((e=>e.extensions.split(", ").includes(s)));if(t.useImageMask){if(!n)return;v.loadUrl(e)}M(),g.innerHTML="";const o=document.createElement("div");g.appendChild(o);const c=document.createElement("button");if(c.className="btn-clearfile",c.innerHTML='\n                            <svg  xmlns="http://www.w3.org/2000/svg"  width="24"  height="24"  viewBox="0 0 24 24"  fill="none"  stroke="currentColor"  stroke-width="1.4"  stroke-linecap="round"  stroke-linejoin="round">\n                            <path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3" /><path d="M18 13.3l-6.3 -6.3" />\n                            </svg>\n                        ',g.appendChild(c),c.addEventListener("click",(e=>{let r=c.closest(".form-field").querySelector(".img-preview");r&&r.remove(),a.value="",l.value="",g.innerHTML="",u.innerText=this.out(this.settings.fileUploadText),t.useImageMask&&v.clearImage();const s=document.querySelector(".formview-container .submit-container");s&&setTimeout((()=>{this.stickyElement(s)}),1e3),e.preventDefault(),e.stopImmediatePropagation()})),n){let t=i.querySelector(".formview-container .img-preview");t||(t=document.createElement("img"),t.className="img-preview",i.appendChild(t)),t.src=e}else k();if(!r){const e=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(e)}const d=document.querySelector(".formview-container .submit-container");d&&setTimeout((()=>{this.stickyElement(d)}),1e3)};t.value&&$(t.value,!0);const N=e=>{if(e){if(!b.some((t=>t.type===e.type)))return void alert(this.out("Invalid file type."));if(t.useImageMask){if(!["image/jpeg","image/png","image/webp"].includes(e.type))return void alert(this.out("Invalid file type."));v.loadImage(e)}M(),a.value="",g.innerHTML="";const r=document.createElement("div");r.innerText=e.name,g.appendChild(r);const s=document.createElement("button");if(s.className="btn-clearfile",s.innerHTML='\n                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">\n                                    <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />\n                                </svg>\n                            ',g.appendChild(s),s.addEventListener("click",(e=>{let r=s.closest(".form-field").querySelector(".img-preview");r&&r.remove(),l.value="",g.innerHTML="",u.innerText=this.out(this.settings.fileUploadText),t.useImageMask&&v.clearImage();const n=document.querySelector(".formview-container .submit-container");n&&setTimeout((()=>{this.stickyElement(n)}),1e3),e.preventDefault(),e.stopImmediatePropagation()})),e.type.startsWith("image/")){const t=new FileReader;t.onload=function(e){let t=i.querySelector(".formview-container .img-preview");t||(t=document.createElement("img"),t.className="img-preview",i.appendChild(t)),t.src=e.target.result}
1,t.readAsDataURL(e)}else k();const n=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(n);const o=document.querySelector(".formview-container .submit-container");o&&setTimeout((()=>{this.stickyElement(o)}),1e3)}},I=e=>{if(e){b=b.concat(f.images);if(!b.some((t=>t.type===e.type)))return void alert(this.out("Invalid file type."));const t=document.createElement("div");t.className="image-item",m.appendChild(t);const r=document.createElement("div");r.className="file-drop-info-highlight",t.appendChild(r);const s=document.createElement("div");s.innerText=e.name,r.appendChild(s);const n=document.createElement("button");if(n.className="btn-clearfile",n.innerHTML='\n                                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">\n                                    <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />\n                                </svg>\n                            ',r.appendChild(n),n.addEventListener("click",(t=>{const r=n.closest(".image-item");r&&r.remove();(e=>{const t=new DataTransfer,r=l.files;Array.from(r).forEach((r=>{r!==e&&t.items.add(r)})),l.files=t.files})(e);const s=document.querySelector(".formview-container .submit-container");s&&setTimeout((()=>{this.stickyElement(s)}),1e3),t.preventDefault(),t.stopImmediatePropagation()})),e.type.startsWith("image/")){const r=new FileReader;r.onload=function(e){let r=document.createElement("img");r.className="img-preview",t.appendChild(r),r.src=e.target.result}
1,r.readAsDataURL(e)}const i=this.getFormValues();this.settings.onInputChange&&this.settings.onInputChange(i);const o=document.querySelector(".formview-container .submit-container");o&&setTimeout((()=>{this.stickyElement(o)}),1e3)}}}if("email"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`email_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`email_label_${e}`,n.type="email",n.name=o,n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("phone"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`phone_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`phone_label_${e}`,n.type="tel",n.name=o,n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("url"===n){let e=this.getId();const r=document.createElement("label");if(r.setAttribute("for",`url_label_${e}`),r.className="field-label",r.innerHTML=t.title+(t.isRequired?' <span class="text-red-500">*</span>':""),s.appendChild(r),t.fieldNote){const e=document.createElement("div");e.className="field-note",e.innerHTML=t.fieldNote,s.appendChild(e)}const n=document.createElement("input");n.id=`url_label_${e}`,n.type="url",n.name=o,n.value=t.value||"",n.className="inp-base",n.placeholder=t.placeholder,t.isRequired&&n.setAttribute("required","required"),s.appendChild(n),n.addEventListener("input",this.inputListener)}if("hidden"===n){let e=this.getId();const r=document.createElement("label");r.setAttribute("for",`hidden_label_${e}`),r.className="field-label hidden",r.innerText=t.title,s.appendChild(r);const n=document.createElement("input");n.id=`hidden_label_${e}`,n.type="hidden",n.name=o,n.value=t.value,s.appendChild(n)}})),this.settings.isBuilder){const r=document.createElement("div");r.className="submit-container",e.appendChild(r);let s=!0;if("hideReset"in t&&(s=t.hideReset),!s){const e=document.createElement("button");e.className="btn-resetform";const s=t.resetText||this.settings.resetText;e.innerText=s,r.appendChild(e),e.addEventListener("click",(t=>{t.preventDefault();const r=e.closest("form");if(r){r.reset();r.querySelectorAll(".btn-clearfile").forEach((e=>{e.click()}));r.querySelectorAll(".slider-container").forEach((e=>{const t=e.querySelector("input");e.querySelector(".current-value").textContent=t.value}))}}));(t.fullWidthButton||!1)&&e.classList.add("w-full")}const n=document.createElement("button");n.className="btn-submitform";const i=t.submitText||this.settings.submitText;n.innerText=i,r.appendChild(n);(t.fullWidthButton||!1)&&n.classList.add("w-full"),this.settings.alwaysVisibleSubmit&&r.classList.add("always-visible"),this.stickyElement(r),e.addEventListener("submit",(async e=>{e.preventDefault(),this.steps&&this.steps.length>0&&this.process()}))}else{let r="Reference Code:",s="reference_code",n="reference_code";const i=document.createElement("div");i.className="form-field ",i.classList.add(n),e.appendChild(i);let o=this.getId();const a=document.createElement("label");a.setAttribute("for",`short_text_label_${o}`),a.className="field-label",a.innerHTML=r,i.appendChild(a);const l=document.createElement("input");if(l.id=`short_text_label_${o}`,l.type="text",l.name=s,l.autocomplete="off",l.setAttribute("aria-hidden","true"),l.className="inp-base",i.appendChild(l),this.settings.captchaContainer){const t=this.settings.captchaContainerClassName,r=document.createElement("div");r.className="captcha-container",t&&r.classList.add(t),e.appendChild(r)}if(t.useSubmitButton){const r=document.createElement("div");r.className="submit-container",e.appendChild(r);let s=!0;if("hideReset"in t&&(s=t.hideReset),!s){const e=document.createElement("button");e.className="btn-resetform";const s=t.resetText||this.settings.resetText;e.innerText=s,r.appendChild(e),e.addEventListener("click",(t=>{t.preventDefault();const r=e.closest("form");if(r){r.reset();r.querySelectorAll(".btn-clearfile").forEach((e=>{e.click()}));r.querySelectorAll(".slider-container").forEach((e=>{const t=e.querySelector("input");e.querySelector(".current-value").textContent=t.value}))}}));(t.fullWidthButton||!1)&&e.classList.add("w-full")}const n=document.createElement("button");n.className="btn-submitform";const i=t.submitText;n.innerText=i,r.appendChild(n);(t.fullWidthButton||!1)&&n.classList.add("w-full"),this.settings.alwaysVisibleSubmit&&r.classList.add("always-visible"),this.stickyElement(r),n.addEventListener("click",(async e=>{this.trigger("submit",e)}));const o=e.closest("form");o?o.addEventListener("submit",(async e=>{this.steps&&this.steps.length>0&&(e.preventDefault(),e.stopImmediatePropagation(),this.process())})):n.addEventListener("click",(async e=>{this.steps&&this.steps.length>0&&(e.preventDefault(),this.process())}))}}this.settings.resultSelector&&(s=document.querySelector(this.settings.resultSelector),s.classList.add("result-wrapper"),s.innerHTML="",n=document.createElement("div"),n.classList.add("result-container"),s.appendChild(n)),t.elements&&s&&t.elements.forEac
1h((e=>{if(e.displayInOutput){if("spacer"===e.type){const t=document.createElement("div");return t.className="form-spacer",e.spacerHeight&&!isNaN(parseFloat(e.spacerHeight))&&(t.style.height=e.spacerHeight+"px"),void n.appendChild(t)}if("separator"===e.type){const t=document.createElement("hr");return t.style.borderTopColor=e.color,void n.appendChild(t)}if("html"!==e.type){if("heading"===e.type){const t=document.createElement(e.heading||"h2");return t.innerHTML=e.headingText||this.out("Your Heading Here!"),void n.appendChild(t)}if("paragraph"===e.type){const t=document.createElement("p");return t.innerHTML=e.paragraphText||this.out("Your paragraph content here!"),void n.appendChild(t)}if("media"!==e.type){if("image"===e.type){const t=document.createElement("img");return t.src=e.url,t.setAttribute("alt",this.out("Output Image")),void n.appendChild(t)}if("video"===e.type){const t=document.createElement("video");t.style.width="100%",t.style.height="auto",t.controls=!0;let r=document.createElement("source");return r.src=e.url,r.type="video/mp4",t.appendChild(r),void n.appendChild(t)}if("audio"===e.type){const t=document.createElement("audio");t.controls=!0;let r=document.createElement("source");return r.src=e.url,r.type="audio/mp3",t.appendChild(r),void n.appendChild(t)}}else if("video"===e.tag){const r=document.createElement("video");r.style.width="100%",r.style.height="auto",r.controls=!0;var t=document.createElement("source");t.src=e.url,t.type="video/mp4",r.appendChild(t),n.appendChild(r)}else if("audio"===e.tag){const t=document.createElement("audio");t.controls=!0;let r=document.createElement("source");r.src=e.url,r.type="audio/mp3",t.appendChild(r),n.appendChild(t)}else if("img"===e.tag){const t=document.createElement("img");t.src=e.url,t.setAttribute("alt",this.out("Output Image")),n.appendChild(t)}}else if(e.html){const t=document.createElement("div");t.innerHTML=e.html,n.appendChild(t)}}}))}if(this.settings.resultSelector){document.querySelector(this.settings.resultSelector).classList.add("result-wrapper")}if(this.settings.saveResults&&this.settings.resultSelector&&localStorage.getItem("_results"))try{this.previousResults=JSON.parse(localStorage.getItem("_results"));let e=localStorage.getItem("_results_html");const t=document.querySelector(this.settings.resultSelector);t.innerHTML=e,this.addResultTool(),t.querySelectorAll(".link-download").forEach((e=>{e.addEventListener("click",(async e=>{e.preventDefault();const t=e.target.href;try{const e=await fetch(t,{mode:"cors"});if(!e.ok)throw new Error("Failed to fetch the image.");const r=await e.blob(),s=t.substring(t.lastIndexOf("/")+1),n=document.createElement("a");n.href=URL.createObjectURL(r),n.download=s,n.click(),URL.revokeObjectURL(n.href)}catch(e){console.error("Error downloading the image:",e)}}))}))}catch(e){}const s=document.querySelector(".formview-container .submit-container");s&&setTimeout((()=>{this.stickyElement(s)}),1e3)}abort(){this.controller&&this.controller.abort()}async search(e){let t={"Content-Type":"application/json",...this.settings.headers};try{const r=await fetch(this.settings.searchUrl,{method:"POST",headers:t,body:JSON.stringify({query:e,customData:this.settings.customData})});if(!r.ok)throw new Error("Failed to fetch data");const s=await r.json();return(s[s.organic_results?"organic_results":"organic"]||[]).map((e=>({title:e.title,link:e.link,snippet:e.snippet||e.description})))}catch(e){return console.error("Error in search:",e.message||e),[]}}async scrapeUrls(e){if(0===e.length)return{data:"",urls:[],failed:[]};this.settings.consoleLog&&console.log(e);let t={"Content-Type":"application/json",...this.settings.headers};const r=await fetch(this.settings.scrapeUrl,{method:"POST",headers:t,body:JSON.stringify({urls:e,customData:this.settings.customData})});if(!r.ok)throw new Error(`Error: ${r.statusText}`);let s="";const n=await r.json();if(this.settings.consoleLog&&console.log(n),n.error)return this.settings.consoleLog&&console.log(n.error),{data:"",urls:[],failed:[]};let i=[],o=[];
1if("firecrawl"===this.settings.scrapeProvider&&n.forEach((e=>{if(e.success){const t=e.metadata.title,r=e.markdown,n=e.metadata.url;i.push(n),s+=`\n\n\n    ## ${t}\n\n    Source: ${n}\n                    \n    ${r}\n\n\n    ----------------\n\n\n    `}else{let t=e.url;if(t){const t=e.url;o.push(t)}else t=e.url.link,o.push(t)}})),"scrapingbee"===this.settings.scrapeProvider)for(let t=0;t<n.length;t++){let r=e[t];i.push(r);let o=n[t];s+=`\n    \n    \n## ${r}\n                \n${o}\n\n\n----------------\n\n\n`}return s=`These are the information from the URLs:\n\n${s}\n`,{data:s,urls:i,failed:o}}async checkPrompt(e){let t=`This is user's request:\n\n${e}        \n        `,r=await this.send("\nCheck if the request requires checking certain URLs. If so, returns the URLs.  \nAlso check if the request requires search to find answers by searching on the web to get the current relevant information.      \n",t,"You are an assistant",[{name:"check_request",description:"Check user request.",parameters:{type:"object",properties:{needscrape:{type:"boolean",description:"Check the if request requires search on the web or not."},url:{type:"string",description:"If request need to check certail URL, return the URL."},url2:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url3:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url4:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url5:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url6:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url7:{type:"string",description:"If the request needs to check a certail URL, return the URL."},url8:{type:"string",description:"If the request needs to check a certail URL, return the URL."},needsearch:{type:"boolean",description:"Check the if request requires search on the web or not."}},required:["needsearch","needscrape"]}}]);return!!r&&JSON.parse(r)}async getRelevantInfo(e,t,r){if(!this.settings.searchUrl&&!this.settings.scrapeUrl)return{data:"",urls:[],failed:[]};const s=document.createElement("div");s.classList.add("status"),r.appendChild(s);let n="",i=await this.checkPrompt(`${t}\n\n${e}`);this.settings.consoleLog&&console.log(i);let o=[],a=[];if(i.url&&i.needscrape&&this.settings.scrapeUrl){let e=document.createElement("p");e.innerHTML=this.out("Fetching data from the web..."),s.appendChild(e);let t=[];i.url&&t.push(i.url),i.url2&&t.push(i.url2),i.url3&&t.push(i.url3),i.url4&&t.push(i.url4),i.url5&&t.push(i.url5),i.url6&&t.push(i.url6),i.url7&&t.push(i.url7),i.url8&&t.push(i.url8);let r=await this.scrapeUrls(t);n+=r.data,o=r.urls,a=r.failed}else if(this.settings.searchUrl&&this.settings.scrapeUrl){let t=document.createElement("p");t.innerHTML=this.out("Searching the web.."),s.appendChild(t);let r=await this.search(e);const i=this.settings.scrapeExclude;let l=r.filter((e=>{let t=new URL(e.link).hostname;return!i.some((e=>t.includes(e)))}));const c=this.settings.scrapeLimit,d=l.slice(0,c);s.innerHTML="",t=document.createElement("p"),t.innerHTML=this.out("Getting more information..."),s.appendChild(t);let u=[];for(let e=0;e<d.length;e++)u.push(r[e].link);let p=await this.scrapeUrls(u);n+=p.data,o=p.urls,a=p.failed}return{data:n,urls:o,failed:a}}showDemoInfo(e){if(!this.settings.resultSelector)return void(this.settings.consoleLog&&console.log("resultSelector not set."));const t=document.querySelector(this.settings.resultSelector);t.innerHTML="";const r=document.createElement("div");let s;if(r.classList.add("result-container"),t.appendChild(r),r.innerHTML='\n        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 20" width="27" height="20" fill="currentColor">\n            <circle cx="15" cy="15" r="10">\n                <animate attributeName="cy" dur="0.6s" values="15;5;15" repeatCount="indefinite"></animate>\n            </circle>\n            <circle cx="60" cy="15" r="10">\n                <animate attributeName="cy" begin="0.2s" dur="0.6s" values="15;5;
115" repeatCount="indefinite"></animate>\n            </circle>\n            <circle cx="105" cy="15" r="10">\n                <animate attributeName="cy" begin="0.4s" dur="0.6s" values="15;5;15" repeatCount="indefinite"></animate>\n            </circle>\n        </svg>\n        ',this.settings.isBuilder){if(!this.settings.previewSelector)return void(this.settings.consoleLog&&console.log("previewSelector not set."));s=document.querySelector(this.settings.previewSelector)}else s=this.element;let n=s.querySelector(".btn-submitform"),i=n.innerHTML;n.innerHTML='&nbsp;\n            <span class="loading-icon" style="width:60px;display:flex;align-items:center;justify-content:center">\n                <svg class="animate-spin" style="margin: 0;width: 1.25rem;height: 1.25rem;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">\n                    <circle style="opacity: 0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>\n                    <path style="opacity: 0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>\n                </svg>\n            </span>\n            &nbsp;\n        ',setTimeout((()=>{r.innerHTML=e,n.innerHTML=i}),400)}async process(e){if(this.payloads=[],this.output=[],this.mediaGenerated=[],this.needCleanup=!1,!this.settings.resultSelector)return void(this.settings.consoleLog&&console.log("resultSelector not set."));const t=document.querySelector(this.settings.resultSelector);if(!t)return void console.log("resultElement not found.");let r,s,n=!1,i=!1;if(this.steps.forEach((e=>{e.prompt.trim().startsWith("{")&&(n=!0),e.tools&&(e.tools.image||e.tools.video||e.tools.audio)&&(n=!0),e.tools&&e.tools.search&&(i=!0)})),n&&this.settings.disableMediaGeneration)return r=`\n                <div class="form-info">\n                    <h3>${this.out(this.settings.disableMediaGenerationTitle)}</h3> \n                    <p>\n                        <b>${this.out(this.settings.disableMediaGenerationMessage)}</b>\n                    </p>\n                </div>`,void this.showDemoInfo(r);if(!this.settings.scrapeUrl&&i)return r=this.settings.demo?'\n                <div class="form-info">\n                    <h3>Demo Info</h3> \n                    <p>\n                    <b>This is an online demo, so web searching and scraping features are currently disabled. In the full version, you’ll have access to all these features!</b>\n                    </p>\n                </div>':'\n                    <div class="form-info">\n                        <p>\n                            <b>Web searching and scraping are currently disabled, so your request cannot be processed.</b>\n                        </p>\n                    </div>',void this.showDemoInfo(r);if(this.settings.isBuilder){if(!this.settings.previewSelector)return void(this.settings.consoleLog&&console.log("previewSelector not set."));s=document.querySelector(this.settings.previewSelector)}else s=this.element;let o=s.querySelector(".btn-submitform"),a=o.innerHTML;this.tokenInput=0,this.tokenOutput=0;let l=!1;if(null!=e&&(l=!0),this.singleStep=l,l||(this.filesUploaded={}),this.isNormal&&!l)return this.isMediaGenerating?void alert(this.out("The media generation process cannot be aborted.")):(this.abort(),o.innerHTML=a,o.removeAttribute("disabled"),void(this.isGenerating=!1));if(this.isNormal&&l)return;if(this.isSingle&&!l)return;if(this.isSingle&&l)return;this.isNormal=!1,this.isSingle=!1,l?(o.innerHTML='\n                <span class="loading-icon">\n                    <svg class="animate-spin" style="margin: 0;margin-right: 0.6rem;width: 1rem;height: 1rem;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">\n                        <circle style="opacity: 0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>\n                        <path style="opacity: 0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>\n                    </svg>\n                </span>\n            ',this.isSingle=!0):(o.innerHTML=`\n                <sp
1an class="loading-icon">\n                    <svg class="animate-spin" style="margin: 0;margin-right: 0.6rem;width: 1.25rem;height: 1.25rem;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">\n                        <circle style="opacity: 0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>\n                        <path style="opacity: 0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>\n                    </svg>\n                </span>\n                ${this.out("Abort")}\n            `,this.isNormal=!0),this.isGenerating=!0;let c=(e,t)=>{if(void 0===e)return"";if(!isNaN(e))return e;let r=e;return t&&t.trim().startsWith("{")&&(r=JSON.stringify(e).slice(1,-1)),r};t.innerHTML="";let d=JSON.parse(JSON.stringify(this.steps)),u=this.getFormValues();if(!u)return;if(u&&0===Object.keys(u).length);else{for(const e of d){let t=e.prompt;if("google"===e.provider)for(const e of u)if(e.value instanceof FileList){if(e.value.length>0){const r=e.value[0];if(!r)continue;const s=await new Promise(((e,t)=>{const s=new FileReader;s.onload=t=>{const r=t.target.result.split(",")[1];e(r)},s.onerror=t,s.readAsDataURL(r)}));t=t.replaceAll(`{{${e.name}}}`,s),t=t.replaceAll(`{{${e.name.toUpperCase()}}}`,s)}}e.prompt=t}
1d.forEach((e=>{let t=e.prompt;u.forEach((r=>{if(void 0===r.value&&(r.value=""),"object"==typeof r.value&&Array.isArray(r.value)){const e=r.value.join(", ");t=t.replaceAll(`{{${r.name}}}`,e),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,e)}else r.value instanceof FileList||"string"==typeof r.value&&-1!==r.value.indexOf("base64")?(t=t.replaceAll(`{{${r.name}}}`,r.name),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,r.name)):(t=t.replaceAll(`{{${r.name}}}`,c(r.value,e.prompt)),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,c(r.value,e.prompt)))})),e.prompt=t})),d.forEach((e=>{let t=e.context;u.forEach((r=>{if(r.value||(r.value=""),"object"==typeof r.value&&Array.isArray(r.value)){const e=r.value.join(", ");t=t.replaceAll(`{{${r.name}}}`,e),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,e)}else r.value instanceof FileList||"string"==typeof r.value&&-1!==r.value.indexOf("base64")?(t=t.replaceAll(`{{${r.name}}}`,r.name),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,r.name)):(t=t.replaceAll(`{{${r.name}}}`,c(r.value,e.prompt)),t=t.replaceAll(`{{${r.name.toUpperCase()}}}`,c(r.value,e.prompt)))})),e.context=t}))}const p=async(e,r,s,n,i,a,c,d)=>{const u=document.createElement("div");u.classList.add("result-container"),t.appendChild(u),u.innerHTML='\n            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 20" width="27" height="20" fill="currentColor">\n                <circle cx="15" cy="15" r="10">\n                    <animate attributeName="cy" dur="0.6s" values="15;5;15" repeatCount="indefinite"></animate>\n                </circle>\n                <circle cx="60" cy="15" r="10">\n                    <animate attributeName="cy" begin="0.2s" dur="0.6s" values="15;5;15" repeatCount="indefinite"></animate>\n                </circle>\n                <circle cx="105" cy="15" r="10">\n                    <animate attributeName="cy" begin="0.4s" dur="0.6s" values="15;5;15" repeatCount="indefinite"></animate>\n                </circle>\n            </svg>\n            ';let p,h=!1;if(e.trim().startsWith("{"))try{p=JSON.parse(e),p&&"object"==typeof p&&(h=!0)}catch(e){return u.innerHTML=`<p>${this.out("Incorrect JSON format.")}</p>`,!1}(c&&(c.image||c.video||c.audio)||h)&&(l||(o.innerHTML='&nbsp;\n                        <span class="loading-icon" style="width:60px;display:flex;align-items:center;justify-content:center">\n                            <svg class="animate-spin" style="margin: 0;width: 1.25rem;height: 1.25rem;" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">\n                                <circle style="opacity: 0.25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>\n                                <path style="opacity: 0.75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>\n                            </svg>\n                        </span>\n                        &nbsp;\n                    ',o.setAttribute("disabled","")));let m,g="",f="";if(c&&c.search&&(m=await this.getRelevantInfo(e,r,u),""!==m.data&&(r+=`\nUse the following information to answer the request:\n\n${m.data}\n`)),c&&(c.image||c.video||c.audio)||h){const t=await this.media.generate(e,r,s,n,c,u,d);return this.needCleanup=!0,this.settings.consoleLog&&console.log(t),t.mediaGenerated?{media:t.output,media2:t.output2,markdown:t.markdown}:(u.innerHTML=`<p>${t.message}</p>`,!1)}if(this.settings.assistantId){if(this.settings.assistantStreamUrl)await this.assistantStream(e,r,i,a,(async e=>{if(e&&"object"==typeof e);else{if(g+=e,!d){const e=de.parse(g);u.innerHTML=e,f+=e}await new Promise((e=>setTimeout(e,50)))}})),await new Promise((e=>{const t=setInterval((()=>{u.innerHTML===de.parse(g)&&(clearInterval(t),e())}),10)})),d&&(u.innerHTML="",u.remove()),this.outputHtml+=`<div class="result-container">${f}</div>`;else if(this.settings.assistantUrl){let t=await this.assistant(e,r,i,a);if(!t)return!1;if(g=t,d)u.innerHTML="",u.remove();else{const e=de.parse(t);u.innerHTML=e,this.outputHtml+=`<div class="result-container">${e}</div>`}}}else if(this.settings.sendCommandStreamUrl){let t="",s="",o="";const l=async e=>{let r=0;for(;r<e.length;){if(o=t.slice(0,o.length+1),r++,!d){const e=de.parse(o);u.innerHTML=e,s=e}await new Promise((e=>setTimeout(e,50)))}};await this.sendStream(e,r,i,n,a,(async e=>{g+=e,t+=e,await l(e)})),await new Promise((e=>{const r=setInterval((()=>{o.length===t.length&&(clearInterval(r),e())}),10)})),d&&(u.innerHTML="",u.remove()),this.outputHtml+=`<div class="result-container">${s}</div>`}else{let t=await this.send(e,r,i,n,a);if(!t)return!1;if(g=t,d)u.innerHTML="",u.remove();else{const e=de.parse(t);u.innerHTML=e,this.outputHtml+=`<div class="result-container">${e}</div>`}}if(!d){let e="";const r=75;
1if(m&&m.urls.forEach((t=>{let s=t;s.length>r&&(s=s.slice(0,r)+"..."),e+=`<div><a class="source_url" href="${t}">${s}</url></div>`})),m&&m.failed.forEach((t=>{let s=t;s.length>r&&(s=s.slice(0,r)+"..."),e+=`<div><a class="source_url" style="opacity:0.5" href="${t}">${s}</url></div>`})),""!==e){const r=document.createElement("div");r.classList.add("result-container"),t.appendChild(r),r.innerHTML=e}}return this.payloads.push({prompt:e,context:r}),this.output.push(g),{media:[],markdown:g}},h=async e=>{this.previousResults=[],this.outputHtml="";for(let t=0;t<e.length;t++){if(!this.isGenerating)return;let{prompt:r,context:s,provider:n,model:i,system:o,functs:a,tools:l,hideOutput:d}=e[t];n=n||"",s=s||"",o=o||"You are an assistant",a=a||[];let u=r;this.previousResults.forEach(((e,t)=>{const s=`{{output_step_${t+1}}}`;u=u.replace(new RegExp(s,"g"),c(e,r)),u=u.replace(new RegExp(s.toUpperCase(),"g"),c(e,r))})),r=u,r=r.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g," ").trim(),this.settings.consoleLog&&console.log(r),u=s,this.previousResults.forEach(((e,t)=>{const s=`{{output_step_${t+1}}}`;u=u.replace(new RegExp(s,"g"),c(e,r)),u=u.replace(new RegExp(s.toUpperCase(),"g"),c(e,r))})),s=u,s=s.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g," ").trim();let h=await p(r,s,n,i,o,a,l,d);if(!h)break;if(this.mediaGenerated.push(...h.media),h.media&&1===h.media.length){let e=h.media[0],r=h.media2&&1===h.media2.length&&h.media2[0];this.previousResults.push(r||e),d&&(this.filesUploaded[`output_step_${t}`]=e)}else this.previousResults.push(h.markdown)}};if(l||await h(d),l){0===e&&(this.previousResults=[]);const t=async(e,t)=>{if(!this.isGenerating)return;let{prompt:r,context:s,provider:n,model:i,system:o,functs:a,tools:l,hideOutput:c}=e[t];s=s||"",o=o||"You are an assistant",a=a||[];let d=r;this.previousResults&&this.previousResults.forEach(((e,t)=>{const r=`{{output_step_${t+1}}}`;d=d.replace(new RegExp(r,"g"),e),d=d.replace(new RegExp(r.toUpperCase(),"g"),e)})),r=d,r=r.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g," ").trim(),this.settings.consoleLog&&console.log(r),d=s,this.previousResults&&this.previousResults.forEach(((e,t)=>{const r=`{{output_step_${t+1}}}`;d=d.replace(new RegExp(r,"g"),e),d=d.replace(new RegExp(r.toUpperCase(),"g"),e)})),s=d,s=s.replace(/[\u00A0\u2000-\u200B\u202F\u205F\u3000\uFEFF]/g," ").trim(),this.settings.consoleLog&&console.log(s);let u=await p(r,s,n,i,o,a,l,c);if(u&&(this.mediaGenerated.push(...u.media),this.previousResults))if(u.media&&1===u.media.length){let e=u.media[0],r=u.media2&&1===u.media2.length&&u.media2[0];this.previousResults[t]=r||e,c&&(this.filesUploaded[`output_step_${t}`]=e)}else this.previousResults[t]=u.markdown};await t(d,e)}o.innerHTML=a,o.removeAttribute("disabled"),this.isGenerating=!1;const m=this.calculateCost();this.settings.onUsage&&this.settings.onUsage(m),this.trigger("usage",m),this.isNormal=!1,this.isSingle=!1;const g=0===Object.keys(this.filesUploaded).length&&this.filesUploaded.constructor===Object;if(this.needCleanup&&!g){this.settings.consoleLog&&(console.log("Cleanup"),console.log(this.filesUploaded));let e={"Content-Type":"application/json",...this.settings.headers};await fetch(this.settings.cleanup,{method:"POST",headers:e,body:JSON.stringify(this.filesUploaded)})}let f=this.outputHtml;this.mediaGenerated=this.mediaGenerated.filter((e=>-1!==f.indexOf(e))),this.trigger("resultReady",{previewText:((e,t=100)=>{const r=document.createElement("div");if(r.innerHTML=e,r.querySelector("video"))return"Video";if(r.querySelector("img"))return"Image";if(r.querySelector("audio"))return"Audio";const s=r.textContent.trim();return s.length>t?s.substring(0,t)+"...":s})(f),markdown:this.previousResults,html:f,media:this.mediaGenerated,input:this.payloads,output:this.output}),this.settings.saveResults&&(localStorage.setItem("_results",JSON.stringify(this.previousResults)),localStorage.setItem("_results_html",f)),this.addResultTool(),t.querySelectorAll(".link-download").forEach((e=>{e.addEventListener("click",(async e=>{e.preventDefault();const t=e.target.href;try{const e=await fetch(t,{mode:"cors"});if(!e.ok)throw new Error("Failed to fetch the image.");const r=await e.blob(),s=t.substring(t.lastIndexOf("/")+1),n=document.createElement("a");n.href=URL.createObjectURL(r),n.download=s,n.click(),URL.revokeObjectURL(n.href)}catch(e){console.error("Error downloading the image:",e)}}))}))}calculateCost(){const e=this.settings.inputCost/1e6,t=this.settings.outputCost/1e6;return this.tokenInput*e+this.tokenOutput*t}loadWorkflow(e){if(!e)return;const t=JSON.parse(e).steps;t.forEach((e=>{Object.prototype.hasOwnProperty.call(e,"context")||(e.context="")})),this.steps=t}getFileInput(e){let t;if(this.settings.isBuilder){if(!this.settings.previewSelector)return void(this.settings.consoleLog&&c
1onsole.log("previewSelector not set."));t=document.querySelector(this.settings.previewSelector)}else t=this.element;return t?e?t.querySelector(`input[type="file"][name="${e}"]`):t.querySelector('input[type="file"]'):null}getFormValues(){const e=this.element;if(!e)return[];const t=e.querySelectorAll("[name]");if(0===t.length)return{};const r={};t.forEach((t=>{let{name:s,type:n,value:i,checked:o,files:a}=t;if("checkbox"===n){if(s=s.replace("[]",""),o){if(r[s]=r[s]||[],"other"===i){i=e.querySelector(`[name="${s+"_other"}"]`).value}r[s].push(i)}}else if("radio"===n){if(o){if("other"===i){i=e.querySelector(`[name="${s+"_other"}"]`).value}r[s]=i}}else if("select-one"===n){if("other"===i){i=e.querySelector(`[name="${s+"_other"}"]`).value}r[s]=i}else if("file"===n)r[s]=a;else if("select-multiple"===n){const e=Array.from(t.selectedOptions);r[s]=e.map((e=>e.value))}else if("color"===n){r[s]=i;const e=this.hexToRgb(i);r[s+"_red"]=e.red,r[s+"_green"]=e.green,r[s+"_blue"]=e.blue}else r[s]=i}));let s=[];return this.json.elements.forEach((e=>{let t=e.title,n=e.name,i=e.type;if(""===n)return;let o=r[n],a={questions:t,name:n,value:o,type:i};s.push(a);let l=n+"__url";o=r[l],o&&(a={questions:t,name:l,value:o},s.push(a)),e.useImageMask&&(n+="_mask",o=r[n],a={questions:t,name:n,value:o},s.push(a));let c=n+"_red";o=r[c],void 0!==o&&(a={questions:t,name:c,value:o},s.push(a));let d=n+"_green";o=r[d],void 0!==o&&(a={questions:t,name:d,value:o},s.push(a));let u=n+"_blue";o=r[u],void 0!==o&&(a={questions:t,name:u,value:o},s.push(a))})),this.settings.consoleLog&&console.log(s),s}setTheme(e,t){let r;if(e)try{r=JSON.parse(e)}catch(e){r={}}else r={};this.themeData=e;const s=r.cssVariables;let n,i=document.documentElement;t&&(i=t),n=s&&s["--form-text-color"]||"",i.style.setProperty("--form-text-color",n),n=s&&s["--form-primary-color"]||"#3b82f6",i.style.setProperty("--form-primary-color",n),n=s&&s["--form-title-color"]||"",i.style.setProperty("--form-title-color",n),n=s&&s["--form-desc-color"]||"",i.style.setProperty("--form-desc-color",n),n=s&&s["--form-label-color"]||"",i.style.setProperty("--form-label-color",n),n=s&&s["--form-label-font-size"]||"",i.style.setProperty("--form-label-font-size",n),n=s&&s["--form-input-font-size"]||"",i.style.setProperty("--form-input-font-size",n),n=s&&s["--form-input-border-color"]||"",i.style.setProperty("--form-input-border-color",n),n=s&&s["--form-primary-border-width"]||"1px",i.style.setProperty("--form-primary-border-width",n),n=s&&s["--form-secondary-border-width"]||"2px",i.style.setProperty("--form-secondary-border-width",n),n=s&&s["--form-input-background-color"]||"",i.style.setProperty("--form-input-background-color",n),n=s&&s["--form-input-text-color"]||"",i.style.setProperty("--form-input-text-color",n),n=s&&s["--form-input-placeholder-color"]||"",i.style.setProperty("--form-input-placeholder-color",n),n=s&&s["--form-choice-border-color"]||"",i.style.setProperty("--form-choice-border-color",n),n=s&&s["--form-switch-background-color"]||"",i.style.setProperty("--form-switch-background-color",n),n=s&&s["--form-switch-knob-color"]||"",i.style.setProperty("--form-switch-knob-color",n),n=s&&s["--form-switch-focus-offset-color"]||"",i.style.setProperty("--form-switch-focus-offset-color",n),n=s&&s["--form-dropfile-border-color"]||"rgb(194 194 194)",i.style.setProperty("--form-dropfile-border-color",n),n=s&&s["--form-dropfile-hover-color"]||"",i.style.setProperty("--form-dropfile-hover-color",n),n=s&&s["--form-button-background-color"]||"",i.style.setProperty("--form-button-background-color",n),n=s&&s["--form-button-hover-background-color"]||"",i.style.setProperty("--form-button-hover-background-color",n),n=s&&s["--form-button-text-color"]||"",i.style.setProperty("--form-button-text-color",n),n=s&&s["--form-button-hover-text-color"]||"",i.style.setProperty("--form-button-hover-text-color",n),n=s&&s["--form-button-border-width"]||"1px",i.style.setProperty("--form-button-border-width",n),n=s&&s["--form-button-border-color"]||"",i.style.setProperty("--form-button-border-color",n),n=s&&s["--form-button-hover-border-color"]||"",i.style.setProperty("--form-button-hover-border-color",n),n=s&&s["--form-reset-background-color"]||"",i.style.setProperty("--form-reset-background-color",n),n=s&&s["--form-reset-hover-background-color"]||"",i.style.setProperty("--form-reset-hover-background-color",n),n=s&&s["--form-reset-text-color"]||"",i.style.setProperty("--form-reset-text-color",n),n=s&&s["--form-reset-hover-text-color"]||"",i.style.setProperty("--form-reset-hover-text-color",n),n=s&&s["--form-reset-border-width"]||"1px",i.style.setProperty("--form-reset-border-width",n),n=s&&s["--form-reset-border-color"]||"",i.style.setProperty("--form-reset-border-color",n),n=s&&s["--form-reset-hover-border-color"]||"",i.style.setProperty("--form-reset-hover-border-color",n)}async send(e,t,r,s,n){this.controller=new AbortController,this.signal=this.controller.signal;n||(n=[]),s=s||this.settings.model,n.length>0&&(s=this.settings.model2);const i={question:e,context:t,system:r,functs:n,temperature:.6,topP:.9,num:1,model:s,customData:this.settings.customData};try{let e={"Content-Type":"application/json",...this.settings.headers};const t=await fetch(this.settings.sendCommandUrl,{signal:this.signal,method:"POST",headers:e,body:JSON.stringify(i)});let r=await t.json();if(r.error)return console.log("Error:\n"+r.error),!1;if(r.answer.usage&&(this.tokenInput+=r.answer.usage.prompt_tokens,this.tokenOutput+=r.answer.usage.completion_tokens),0===n.length){let e;
1return r.answer.choices.forEach((t=>{e=t.message.content})),e}return r.answer}catch(e){return"AbortError"===e.name?this.settings.consoleLog&&console.log("Request aborted by user."):console.error("Error:",e),!1}}async sendStream(e,t,r,s,n,i){this.controller=new AbortController,this.signal=this.controller.signal;n||(n=[]);const o={question:e,context:t,system:r,functs:n,temperature:.6,topP:.9,num:1,model:s=s||this.settings.model,customData:this.settings.customData};try{let e={"Content-Type":"application/json",...this.settings.headers};const t=await fetch(this.settings.sendCommandStreamUrl,{signal:this.signal,method:"POST",headers:e,body:JSON.stringify(o)});if(!t.ok)return console.error("Error:",t.statusText),!1;const r=t.body.getReader(),s=new TextDecoder;let n="",a=!1;for(;!a;){const{done:e,value:t}=await r.read();if(a=e,a)break;n+=s.decode(t,{stream:!0});const o=n.split("\n");n="";let l=0,c=0;for(const e of o)if(""!==e.trim()&&e.startsWith("data:")){const t=e.slice(5).trim();if("[DONE]"===t){this.settings.consoleLog&&console.log("Stream completed.");break}try{const e=JSON.parse(t);if(e.usage&&(l=e.usage.prompt_tokens,c=e.usage.completion_tokens),e.choices&&e.choices[0].delta&&e.choices[0].delta.content){const t=e.choices[0].delta.content;i&&i(t)}}catch(t){n+=e+"\n"}}this.tokenInput+=l,this.tokenOutput+=c}return!0}catch(e){return"AbortError"===e.name?this.settings.consoleLog&&console.log("Request aborted by user."):console.error("Error:",e),!1}}async assistant(e,t,r,s){this.controller=new AbortController,this.signal=this.controller.signal;s||(s=[]);let n=this.settings.model;s.length>0&&(n=this.settings.model2);const i={assistantId:this.settings.assistantId,question:e,context:t,system:r,functs:s,temperature:.6,topP:.9,num:1,model:n,customData:this.settings.customData};try{let e={"Content-Type":"application/json",...this.settings.headers};const t=await fetch(this.settings.assistantUrl,{signal:this.signal,method:"POST",headers:e,body:JSON.stringify(i)});let r=await t.json();return r.error?(console.log("Error:\n"+r.error),!1):(r.usage&&(this.tokenInput+=r.usage.prompt_tokens,this.tokenOutput+=r.usage.completion_tokens),r.answer.content[0].text.value)}catch(e){return"AbortError"===e.name?this.settings.consoleLog&&console.log("Request aborted by user."):console.error("Error:",e),!1}}async assistantStream(e,t,r,s,n){this.controller=new AbortController,this.signal=this.controller.signal;s||(s=[]);const i={assistantId:this.settings.assistantId,question:e,context:t,system:r,functs:s,temperature:.6,topP:.9,num:1,model:this.settings.model,customData:this.settings.customData};try{let e={"Content-Type":"application/json",...this.settings.headers};const t=await fetch(this.settings.assistantStreamUrl,{signal:this.signal,method:"POST",headers:e,body:JSON.stringify(i)});if(!t.ok)return console.error("Error:",t.statusText),!1;const r=t.body.getReader(),s=new TextDecoder;let o="",a=!1;for(;!a;){const{done:e,value:t}=await r.read();if(a=e,a)break;o+=s.decode(t,{stream:!0});const i=o.split("\n");o="";for(const e of i)if(""!==e.trim()){if(!e.startsWith("data:")){const t=JSON.parse(e);this.tokenInput+=t.prompt_tokens,this.tokenOutput+=t.completion_tokens;break}{const t=e.slice(5).trim();"[DONE]"===t&&this.settings.consoleLog&&console.log("Stream completed.");try{const e=JSON.parse(t);if(e.choices&&e.choices[0].delta&&e.choices[0].delta.content){const t=e.choices[0].delta.content;n&&n(t)}}catch(t){o+=e+"\n"}}}}return!0}catch(e){return"AbortError"===e.name?this.settings.consoleLog&&console.log("Request aborted by user."):console.error("Error:",e),!1}}hexToRgb(e){const t=e.replace("#",""),r=parseInt(t,16);return{red:r>>16&255,green:r>>8&255,blue:255&r}}getId(e="id"){return`${e}-${Math.random().toString(36).substr(2,9)}`}appendHtml(e,t){e&&t&&e.insertAdjacentHTML("beforeend",t)}cleanup(){if(this.element){let e=this.element.querySelectorAll('input[type="text"], input[type="number"], input[type="email"], input[type="tel"], input[type="url"], textarea');e.forEach((e=>{e.removeEventListener("input",this.inputListener)})),e=this.element.querySelectorAll('input[type="date"], input[type="radio"], input[type="checkbox"]'),e.forEach((e=>{e.removeEventListener("change",this.changeListener)})),this.debounceTimeout&&(clearTimeout(this.debounceTimeout),this.debounceTimeout=null)}}destroy(){try{if(this._scrollListener){let e;e=this.settings.isBuilder?document.querySelector(this.settings.previewSelector):this.element;const t=e.querySelector(".submit-container"),r=this.getScrollableParent(t);r?r.removeEventListener("scroll",this._scrollListener):window.removeEventListener("scroll",this._scrollListener),window.removeEventListener("resize",this._scrollListener)}}catch(e){}this.element&&(this.cleanup(),this.element.innerHTML="",this.element=null);for(const e in this.listeners)this.listeners[e].clear();this.listeners={}}out(e){let t=this.settings.lang[e];return t||e}}}();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.