UNPKG

shellmind

Version:

️‍🔥CLI ai based chat application ️‍🔥

238 lines 240 kB
#!/usr/bin/env node import de from"figlet";import Ba from"chalk-animation";import{Command as Ha}from"commander";import v from"chalk";import w,{readFileSync as Ka}from"fs";import k from"path";import Ya from"readline";import{editor as Ne,confirm as R,select as Va,input as Za}from"@inquirer/prompts";import Ja from"cli-html";import $e from"ora";import Wa from"inquirer-file-selector";var Le;(function(a){a.STRING="string",a.NUMBER="number",a.INTEGER="integer",a.BOOLEAN="boolean",a.ARRAY="array",a.OBJECT="object"})(Le||(Le={}));/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */var qe;(function(a){a.LANGUAGE_UNSPECIFIED="language_unspecified",a.PYTHON="python"})(qe||(qe={}));var Fe;(function(a){a.OUTCOME_UNSPECIFIED="outcome_unspecified",a.OUTCOME_OK="outcome_ok",a.OUTCOME_FAILED="outcome_failed",a.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Fe||(Fe={}));/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */const De=["user","model","function","system"];var Ue;(function(a){a.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",a.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",a.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",a.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",a.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"})(Ue||(Ue={}));var Me;(function(a){a.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",a.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",a.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",a.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",a.BLOCK_NONE="BLOCK_NONE"})(Me||(Me={}));var Pe;(function(a){a.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",a.NEGLIGIBLE="NEGLIGIBLE",a.LOW="LOW",a.MEDIUM="MEDIUM",a.HIGH="HIGH"})(Pe||(Pe={}));var Ge;(function(a){a.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",a.SAFETY="SAFETY",a.OTHER="OTHER"})(Ge||(Ge={}));var P;(function(a){a.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",a.STOP="STOP",a.MAX_TOKENS="MAX_TOKENS",a.SAFETY="SAFETY",a.RECITATION="RECITATION",a.LANGUAGE="LANGUAGE",a.OTHER="OTHER"})(P||(P={}));var Be;(function(a){a.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",a.RETRIEVAL_QUERY="RETRIEVAL_QUERY",a.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",a.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",a.CLASSIFICATION="CLASSIFICATION",a.CLUSTERING="CLUSTERING"})(Be||(Be={}));var He;(function(a){a.MODE_UNSPECIFIED="MODE_UNSPECIFIED",a.AUTO="AUTO",a.ANY="ANY",a.NONE="NONE"})(He||(He={}));var Ke;(function(a){a.MODE_UNSPECIFIED="MODE_UNSPECIFIED",a.MODE_DYNAMIC="MODE_DYNAMIC"})(Ke||(Ke={}));/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */let E=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}};class F extends E{constructor(e,i){super(e),this.response=i}}let Ye=class extends E{constructor(e,i,n,s){super(e),this.status=i,this.statusText=n,this.errorDetails=s}},O=class extends E{};/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */const Xa="https://generativelanguage.googleapis.com",Qa="v1beta",ei="0.21.0",ai="genai-js";var N;(function(a){a.GENERATE_CONTENT="generateContent",a.STREAM_GENERATE_CONTENT="streamGenerateContent",a.COUNT_TOKENS="countTokens",a.EMBED_CONTENT="embedContent",a.BATCH_EMBED_CONTENTS="batchEmbedContents"})(N||(N={}));class ii{constructor(e,i,n,s,o){this.model=e,this.task=i,this.apiKey=n,this.stream=s,this.requestOptions=o}toString(){var e,i;const n=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Qa;let o=`${((i=this.requestOptions)===null||i===void 0?void 0:i.baseUrl)||Xa}/${n}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function ni(a){const e=[];return a?.apiClient&&e.push(a.apiClient),e.push(`${ai}/${ei}`),e.join(" ")}async function si(a){var e;const i=new Headers;i.append("Content-Type","application/json"),i.append("x-goog-api-client",ni(a.requestOptions)),i.append("x-goog-api-key",a.apiKey);let n=(e=a.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(s){throw new O(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${s.message}`)}for(const[s,o]of n.entries()){if(s==="x-goog-api-key")throw new O(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new O(`Header name ${s} can only be set using the apiClient field`);i.append(s,o)}}return i}async function oi(a,e,i,n,s,o){const t=new ii(a,e,i,n,o);return{url:t.toString(),fetchOptions:Object.assign(Object.assign({},pi(o)),{method:"POST",headers:await si(t),body:s})}}async function G(a,e,i,n,s,o={},t=fetch){const{url:c,fetchOptions:r}=await oi(a,e,i,n,s,o);return ti(c,r,t)}async function ti(a,e,i=fetch){let n;try{n=await i(a,e)}catch(s){ci(s,a)}return n.ok||await ri(n,a),n}function ci(a,e){let i=a;throw a instanceof Ye||a instanceof O||(i=new E(`Error fetching from ${e.toString()}: ${a.message}`),i.stack=a.stack),i}async function ri(a,e){let i="",n;try{const s=await a.json();i=s.error.message,s.error.details&&(i+=` ${JSON.stringify(s.error.details)}`,n=s.error.details)}catch{}throw new Ye(`Error fetching from ${e.toString()}: [${a.status} ${a.statusText}] ${i}`,a.status,a.statusText,n)}function pi(a){const e={};if(a?.signal!==void 0||a?.timeout>=0){const i=new AbortController;a?.timeout>=0&&setTimeout(()=>i.abort(),a.timeout),a?.signal&&a.signal.addEventListener("abort",()=>{i.abort()}),e.signal=i.signal}return e}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */function me(a){return a.text=()=>{if(a.candidates&&a.candidates.length>0){if(a.candidates.length>1&&console.warn(`This response had ${a.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),J(a.candidates[0]))throw new F(`${z(a)}`,a);return li(a)}else if(a.promptFeedback)throw new F(`Text not available. ${z(a)}`,a);return""},a.functionCall=()=>{if(a.candidates&&a.candidates.length>0){if(a.candidates.length>1&&console.warn(`This response had ${a.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),J(a.candidates[0]))throw new F(`${z(a)}`,a);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Ve(a)[0]}else if(a.promptFeedback)throw new F(`Function call not available. ${z(a)}`,a)},a.functionCalls=()=>{if(a.candidates&&a.candidates.length>0){if(a.candidates.length>1&&console.warn(`This response had ${a.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),J(a.candidates[0]))throw new F(`${z(a)}`,a);return Ve(a)}else if(a.promptFeedback)throw new F(`Function call not available. ${z(a)}`,a)},a}function li(a){var e,i,n,s;const o=[];if(!((i=(e=a.candidates)===null||e===void 0?void 0:e[0].content)===null||i===void 0)&&i.parts)for(const t of(s=(n=a.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)t.text&&o.push(t.text),t.executableCode&&o.push("\n```"+t.executableCode.language+` `+t.executableCode.code+"\n```\n"),t.codeExecutionResult&&o.push("\n```\n"+t.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Ve(a){var e,i,n,s;const o=[];if(!((i=(e=a.candidates)===null||e===void 0?void 0:e[0].content)===null||i===void 0)&&i.parts)for(const t of(s=(n=a.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)t.functionCall&&o.push(t.functionCall);if(o.length>0)return o}const ui=[P.RECITATION,P.SAFETY,P.LANGUAGE];function J(a){return!!a.finishReason&&ui.includes(a.finishReason)}function z(a){var e,i,n;let s="";if((!a.candidates||a.candidates.length===0)&&a.promptFeedback)s+="Response was blocked",!((e=a.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${a.promptFeedback.blockReason}`),!((i=a.promptFeedback)===null||i===void 0)&&i.blockReasonMessage&&(s+=`: ${a.promptFeedback.blockReasonMessage}`);else if(!((n=a.candidates)===null||n===void 0)&&n[0]){const o=a.candidates[0];J(o)&&(s+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(s+=`: ${o.finishMessage}`))}return s}function B(a){return this instanceof B?(this.v=a,this):new B(a)}function di(a,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=i.apply(a,e||[]),s,o=[];return s={},t("next"),t("throw"),t("return"),s[Symbol.asyncIterator]=function(){return this},s;function t(f){n[f]&&(s[f]=function(l){return new Promise(function(d,x){o.push([f,l,d,x])>1||c(f,l)})})}function c(f,l){try{r(n[f](l))}catch(d){m(o[0][3],d)}}function r(f){f.value instanceof B?Promise.resolve(f.value.v).then(p,u):m(o[0][2],f)}function p(f){c("next",f)}function u(f){c("throw",f)}function m(f,l){f(l),o.shift(),o.length&&c(o[0][0],o[0][1])}}typeof SuppressedError=="function"&&SuppressedError;/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */const Ze=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function mi(a){const e=a.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),i=vi(e),[n,s]=i.tee();return{stream:fi(n),response:xi(s)}}async function xi(a){const e=[],i=a.getReader();for(;;){const{done:n,value:s}=await i.read();if(n)return me(hi(e));e.push(s)}}function fi(a){return di(this,arguments,function*(){const i=a.getReader();for(;;){const{value:n,done:s}=yield B(i.read());if(s)break;yield yield B(me(n))}})}function vi(a){const e=a.getReader();return new ReadableStream({start(n){let s="";return o();function o(){return e.read().then(({value:t,done:c})=>{if(c){if(s.trim()){n.error(new E("Failed to parse stream"));return}n.close();return}s+=t;let r=s.match(Ze),p;for(;r;){try{p=JSON.parse(r[1])}catch{n.error(new E(`Error parsing JSON response: "${r[1]}"`));return}n.enqueue(p),s=s.substring(r[0].length),r=s.match(Ze)}return o()})}}})}function hi(a){const e=a[a.length-1],i={promptFeedback:e?.promptFeedback};for(const n of a){if(n.candidates)for(const s of n.candidates){const o=s.index;if(i.candidates||(i.candidates=[]),i.candidates[o]||(i.candidates[o]={index:s.index}),i.candidates[o].citationMetadata=s.citationMetadata,i.candidates[o].groundingMetadata=s.groundingMetadata,i.candidates[o].finishReason=s.finishReason,i.candidates[o].finishMessage=s.finishMessage,i.candidates[o].safetyRatings=s.safetyRatings,s.content&&s.content.parts){i.candidates[o].content||(i.candidates[o].content={role:s.content.role||"user",parts:[]});const t={};for(const c of s.content.parts)c.text&&(t.text=c.text),c.functionCall&&(t.functionCall=c.functionCall),c.executableCode&&(t.executableCode=c.executableCode),c.codeExecutionResult&&(t.codeExecutionResult=c.codeExecutionResult),Object.keys(t).length===0&&(t.text=""),i.candidates[o].content.parts.push(t)}}n.usageMetadata&&(i.usageMetadata=n.usageMetadata)}return i}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */async function Je(a,e,i,n){const s=await G(e,N.STREAM_GENERATE_CONTENT,a,!0,JSON.stringify(i),n);return mi(s)}async function We(a,e,i,n){const o=await(await G(e,N.GENERATE_CONTENT,a,!1,JSON.stringify(i),n)).json();return{response:me(o)}}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */function Xe(a){if(a!=null){if(typeof a=="string")return{role:"system",parts:[{text:a}]};if(a.text)return{role:"system",parts:[a]};if(a.parts)return a.role?a:{role:"system",parts:a.parts}}}function H(a){let e=[];if(typeof a=="string")e=[{text:a}];else for(const i of a)typeof i=="string"?e.push({text:i}):e.push(i);return gi(e)}function gi(a){const e={role:"user",parts:[]},i={role:"function",parts:[]};let n=!1,s=!1;for(const o of a)"functionResponse"in o?(i.parts.push(o),s=!0):(e.parts.push(o),n=!0);if(n&&s)throw new E("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!s)throw new E("No content is provided for sending chat message.");return n?e:i}function bi(a,e){var i;let n={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(i=e?.cachedContent)===null||i===void 0?void 0:i.name,contents:[]};const s=a.generateContentRequest!=null;if(a.contents){if(s)throw new O("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=a.contents}else if(s)n=Object.assign(Object.assign({},n),a.generateContentRequest);else{const o=H(a);n.contents=[o]}return{generateContentRequest:n}}function Qe(a){let e;return a.contents?e=a:e={contents:[H(a)]},a.systemInstruction&&(e.systemInstruction=Xe(a.systemInstruction)),e}function wi(a){return typeof a=="string"||Array.isArray(a)?{content:H(a)}:a}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */const ea=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],ki={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function yi(a){let e=!1;for(const i of a){const{role:n,parts:s}=i;if(!e&&n!=="user")throw new E(`First content should be with role 'user', got ${n}`);if(!De.includes(n))throw new E(`Each item should include role field. Got ${n} but valid roles are: ${JSON.stringify(De)}`);if(!Array.isArray(s))throw new E("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new E("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const c of s)for(const r of ea)r in c&&(o[r]+=1);const t=ki[n];for(const c of ea)if(!t.includes(c)&&o[c]>0)throw new E(`Content with role '${n}' can't contain '${c}' part`);e=!0}}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */const aa="SILENT_ERROR";class Ei{constructor(e,i,n,s={}){this.model=i,this.params=n,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n?.history&&(yi(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,i={}){var n,s,o,t,c,r;await this._sendPromise;const p=H(e),u={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(t=this.params)===null||t===void 0?void 0:t.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(r=this.params)===null||r===void 0?void 0:r.cachedContent,contents:[...this._history,p]},m=Object.assign(Object.assign({},this._requestOptions),i);let f;return this._sendPromise=this._sendPromise.then(()=>We(this._apiKey,this.model,u,m)).then(l=>{var d;if(l.response.candidates&&l.response.candidates.length>0){this._history.push(p);const x=Object.assign({parts:[],role:"model"},(d=l.response.candidates)===null||d===void 0?void 0:d[0].content);this._history.push(x)}else{const x=z(l.response);x&&console.warn(`sendMessage() was unsuccessful. ${x}. Inspect response object for details.`)}f=l}),await this._sendPromise,f}async sendMessageStream(e,i={}){var n,s,o,t,c,r;await this._sendPromise;const p=H(e),u={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(t=this.params)===null||t===void 0?void 0:t.toolConfig,systemInstruction:(c=this.params)===null||c===void 0?void 0:c.systemInstruction,cachedContent:(r=this.params)===null||r===void 0?void 0:r.cachedContent,contents:[...this._history,p]},m=Object.assign(Object.assign({},this._requestOptions),i),f=Je(this._apiKey,this.model,u,m);return this._sendPromise=this._sendPromise.then(()=>f).catch(l=>{throw new Error(aa)}).then(l=>l.response).then(l=>{if(l.candidates&&l.candidates.length>0){this._history.push(p);const d=Object.assign({},l.candidates[0].content);d.role||(d.role="model"),this._history.push(d)}else{const d=z(l);d&&console.warn(`sendMessageStream() was unsuccessful. ${d}. Inspect response object for details.`)}}).catch(l=>{l.message!==aa&&console.error(l)}),f}}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */async function ji(a,e,i,n){return(await G(e,N.COUNT_TOKENS,a,!1,JSON.stringify(i),n)).json()}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */async function _i(a,e,i,n){return(await G(e,N.EMBED_CONTENT,a,!1,JSON.stringify(i),n)).json()}async function Si(a,e,i,n){const s=i.requests.map(t=>Object.assign(Object.assign({},t),{model:e}));return(await G(e,N.BATCH_EMBED_CONTENTS,a,!1,JSON.stringify({requests:s}),n)).json()}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */class ia{constructor(e,i,n={}){this.apiKey=e,this._requestOptions=n,i.model.includes("/")?this.model=i.model:this.model=`models/${i.model}`,this.generationConfig=i.generationConfig||{},this.safetySettings=i.safetySettings||[],this.tools=i.tools,this.toolConfig=i.toolConfig,this.systemInstruction=Xe(i.systemInstruction),this.cachedContent=i.cachedContent}async generateContent(e,i={}){var n;const s=Qe(e),o=Object.assign(Object.assign({},this._requestOptions),i);return We(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}async generateContentStream(e,i={}){var n;const s=Qe(e),o=Object.assign(Object.assign({},this._requestOptions),i);return Je(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}startChat(e){var i;return new Ei(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(i=this.cachedContent)===null||i===void 0?void 0:i.name},e),this._requestOptions)}async countTokens(e,i={}){const n=bi(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),i);return ji(this.apiKey,this.model,n,s)}async embedContent(e,i={}){const n=wi(e),s=Object.assign(Object.assign({},this._requestOptions),i);return _i(this.apiKey,this.model,n,s)}async batchEmbedContents(e,i={}){const n=Object.assign(Object.assign({},this._requestOptions),i);return Si(this.apiKey,this.model,e,n)}}/** * @license * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */class Ti{constructor(e){this.apiKey=e}getGenerativeModel(e,i){if(!e.model)throw new E("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new ia(this.apiKey,e,i)}getGenerativeModelFromCachedContent(e,i,n){if(!e.name)throw new O("Cached content must contain a `name` field.");if(!e.model)throw new O("Cached content must contain a `model` field.");const s=["model","systemInstruction"];for(const t of s)if(i?.[t]&&e[t]&&i?.[t]!==e[t]){if(t==="model"){const c=i.model.startsWith("models/")?i.model.replace("models/",""):i.model,r=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(c===r)continue}throw new O(`Different value for "${t}" specified in modelParams (${i[t]}) and cachedContent (${e[t]})`)}const o=Object.assign(Object.assign({},i),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new ia(this.apiKey,o,n)}}function xe(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let $=xe();function na(a){$=a}const K={exec:()=>null};function h(a,e=""){let i=typeof a=="string"?a:a.source;const n={replace:(s,o)=>{let t=typeof o=="string"?o:o.source;return t=t.replace(y.caret,"$1"),i=i.replace(s,t),n},getRegex:()=>new RegExp(i,e)};return n}const y={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+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:a=>new RegExp(`^( {0,3}${a})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:a=>new RegExp(`^ {0,${Math.min(3,a-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:a=>new RegExp(`^ {0,${Math.min(3,a-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:a=>new RegExp(`^ {0,${Math.min(3,a-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:a=>new RegExp(`^ {0,${Math.min(3,a-1)}}#`),htmlBeginRegex:a=>new RegExp(`^ {0,${Math.min(3,a-1)}}<(?:[a-z].*>|!--)`,"i")},Ci=/^(?:[ \t]*(?:\n|$))+/,Ai=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ii=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Y=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ri=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,sa=/(?:[*+-]|\d{1,9}[.)])/,oa=h(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,sa).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/).getRegex(),fe=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Oi=/^[^\n]+/,ve=/(?!\s*\])(?:\\.|[^\[\]\\])+/,zi=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ve).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ni=h(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,sa).getRegex(),W="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",he=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,$i=h("^ {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|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",he).replace("tag",W).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),ta=h(fe).replace("hr",Y).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",W).getRegex(),Li=h(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",ta).getRegex(),ge={blockquote:Li,code:Ai,def:zi,fences:Ii,heading:Ri,hr:Y,html:$i,lheading:oa,list:Ni,newline:Ci,paragraph:ta,table:K,text:Oi},ca=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Y).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\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",W).getRegex(),qi={...ge,table:ca,paragraph:h(fe).replace("hr",Y).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ca).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",W).getRegex()},Fi={...ge,html:h(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",he).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:K,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:h(fe).replace("hr",Y).replace("heading",` *#{1,6} *[^ ]`).replace("lheading",oa).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Di=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ui=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ra=/^( {2,}|\\)\n(?!\s*$)/,Mi=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,X=/[\p{P}\p{S}]/u,be=/[\s\p{P}\p{S}]/u,pa=/[^\s\p{P}\p{S}]/u,Pi=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,be).getRegex(),la=/(?!~)[\p{P}\p{S}]/u,Gi=/(?!~)[\s\p{P}\p{S}]/u,Bi=/(?:[^\s\p{P}\p{S}]|~)/u,Hi=/\[[^[\]]*?\]\((?:\\.|[^\\\(\)]|\((?:\\.|[^\\\(\)])*\))*\)|`[^`]*?`|<[^<>]*?>/g,ua=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,Ki=h(ua,"u").replace(/punct/g,X).getRegex(),Yi=h(ua,"u").replace(/punct/g,la).getRegex(),da="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Vi=h(da,"gu").replace(/notPunctSpace/g,pa).replace(/punctSpace/g,be).replace(/punct/g,X).getRegex(),Zi=h(da,"gu").replace(/notPunctSpace/g,Bi).replace(/punctSpace/g,Gi).replace(/punct/g,la).getRegex(),Ji=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,pa).replace(/punctSpace/g,be).replace(/punct/g,X).getRegex(),Wi=h(/\\(punct)/,"gu").replace(/punct/g,X).getRegex(),Xi=h(/^<(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(),Qi=h(he).replace("(?:-->|$)","-->").getRegex(),en=h("^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",Qi).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Q=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,an=h(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",Q).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),ma=h(/^!?\[(label)\]\[(ref)\]/).replace("label",Q).replace("ref",ve).getRegex(),xa=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",ve).getRegex(),nn=h("reflink|nolink(?!\\()","g").replace("reflink",ma).replace("nolink",xa).getRegex(),we={_backpedal:K,anyPunctuation:Wi,autolink:Xi,blockSkip:Hi,br:ra,code:Ui,del:K,emStrongLDelim:Ki,emStrongRDelimAst:Vi,emStrongRDelimUnd:Ji,escape:Di,link:an,nolink:xa,punctuation:Pi,reflink:ma,reflinkSearch:nn,tag:en,text:Mi,url:K},sn={...we,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",Q).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Q).getRegex()},ke={...we,emStrongRDelimAst:Zi,emStrongLDelim:Yi,url:h(/^((?: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.!#$%&'*+\/=?_`{\|}~-]+@)))/},on={...ke,br:h(ra).replace("{2,}","*").getRegex(),text:h(ke.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ee={normal:ge,gfm:qi,pedantic:Fi},V={normal:we,gfm:ke,breaks:on,pedantic:sn},tn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},fa=a=>tn[a];function I(a,e){if(e){if(y.escapeTest.test(a))return a.replace(y.escapeReplace,fa)}else if(y.escapeTestNoEncode.test(a))return a.replace(y.escapeReplaceNoEncode,fa);return a}function va(a){try{a=encodeURI(a).replace(y.percentDecode,"%")}catch{return null}return a}function ha(a,e){const i=a.replace(y.findPipe,(o,t,c)=>{let r=!1,p=t;for(;--p>=0&&c[p]==="\\";)r=!r;return r?"|":" |"}),n=i.split(y.splitPipe);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(y.slashPipe,"|");return n}function Z(a,e,i){const n=a.length;if(n===0)return"";let s=0;for(;s<n&&a.charAt(n-s-1)===e;)s++;return a.slice(0,n-s)}function cn(a,e){if(a.indexOf(e[1])===-1)return-1;let i=0;for(let n=0;n<a.length;n++)if(a[n]==="\\")n++;else if(a[n]===e[0])i++;else if(a[n]===e[1]&&(i--,i<0))return n;return-1}function ga(a,e,i,n,s){const o=e.href,t=e.title||null,c=a[1].replace(s.other.outputLinkReplace,"$1");if(a[0].charAt(0)!=="!"){n.state.inLink=!0;const r={type:"link",raw:i,href:o,title:t,text:c,tokens:n.inlineTokens(c)};return n.state.inLink=!1,r}return{type:"image",raw:i,href:o,title:t,text:c}}function rn(a,e,i){const n=a.match(i.other.indentCodeCompensation);if(n===null)return e;const s=n[1];return e.split(` `).map(o=>{const t=o.match(i.other.beginningSpace);if(t===null)return o;const[c]=t;return c.length>=s.length?o.slice(s.length):o}).join(` `)}class ae{options;rules;lexer;constructor(e){this.options=e||$}space(e){const i=this.rules.block.newline.exec(e);if(i&&i[0].length>0)return{type:"space",raw:i[0]}}code(e){const i=this.rules.block.code.exec(e);if(i){const n=i[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i[0],codeBlockStyle:"indented",text:this.options.pedantic?n:Z(n,` `)}}}fences(e){const i=this.rules.block.fences.exec(e);if(i){const n=i[0],s=rn(n,i[3]||"",this.rules);return{type:"code",raw:n,lang:i[2]?i[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):i[2],text:s}}}heading(e){const i=this.rules.block.heading.exec(e);if(i){let n=i[2].trim();if(this.rules.other.endingHash.test(n)){const s=Z(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw:i[0],depth:i[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){const i=this.rules.block.hr.exec(e);if(i)return{type:"hr",raw:Z(i[0],` `)}}blockquote(e){const i=this.rules.block.blockquote.exec(e);if(i){let n=Z(i[0],` `).split(` `),s="",o="";const t=[];for(;n.length>0;){let c=!1;const r=[];let p;for(p=0;p<n.length;p++)if(this.rules.other.blockquoteStart.test(n[p]))r.push(n[p]),c=!0;else if(!c)r.push(n[p]);else break;n=n.slice(p);const u=r.join(` `),m=u.replace(this.rules.other.blockquoteSetextReplace,` $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s} ${u}`:u,o=o?`${o} ${m}`:m;const f=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(m,t,!0),this.lexer.state.top=f,n.length===0)break;const l=t.at(-1);if(l?.type==="code")break;if(l?.type==="blockquote"){const d=l,x=d.raw+` `+n.join(` `),b=this.blockquote(x);t[t.length-1]=b,s=s.substring(0,s.length-d.raw.length)+b.raw,o=o.substring(0,o.length-d.text.length)+b.text;break}else if(l?.type==="list"){const d=l,x=d.raw+` `+n.join(` `),b=this.list(x);t[t.length-1]=b,s=s.substring(0,s.length-l.raw.length)+b.raw,o=o.substring(0,o.length-d.raw.length)+b.raw,n=x.substring(t.at(-1).raw.length).split(` `);continue}}return{type:"blockquote",raw:s,tokens:t,text:o}}}list(e){let i=this.rules.block.list.exec(e);if(i){let n=i[1].trim();const s=n.length>1,o={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const t=this.rules.other.listItemRegex(n);let c=!1;for(;e;){let p=!1,u="",m="";if(!(i=t.exec(e))||this.rules.block.hr.test(e))break;u=i[0],e=e.substring(u.length);let f=i[2].split(` `,1)[0].replace(this.rules.other.listReplaceTabs,j=>" ".repeat(3*j.length)),l=e.split(` `,1)[0],d=!f.trim(),x=0;if(this.options.pedantic?(x=2,m=f.trimStart()):d?x=i[1].length+1:(x=i[2].search(this.rules.other.nonSpaceChar),x=x>4?1:x,m=f.slice(x),x+=i[1].length),d&&this.rules.other.blankLine.test(l)&&(u+=l+` `,e=e.substring(l.length+1),p=!0),!p){const j=this.rules.other.nextBulletRegex(x),q=this.rules.other.hrRegex(x),C=this.rules.other.fencesBeginRegex(x),U=this.rules.other.headingBeginRegex(x),Ga=this.rules.other.htmlBeginRegex(x);for(;e;){const ue=e.split(` `,1)[0];let M;if(l=ue,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting," "),M=l):M=l.replace(this.rules.other.tabCharGlobal," "),C.test(l)||U.test(l)||Ga.test(l)||j.test(l)||q.test(l))break;if(M.search(this.rules.other.nonSpaceChar)>=x||!l.trim())m+=` `+M.slice(x);else{if(d||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||C.test(f)||U.test(f)||q.test(f))break;m+=` `+l}!d&&!l.trim()&&(d=!0),u+=ue+` `,e=e.substring(ue.length+1),f=M.slice(x)}}o.loose||(c?o.loose=!0:this.rules.other.doubleBlankLine.test(u)&&(c=!0));let b=null,A;this.options.gfm&&(b=this.rules.other.listIsTask.exec(m),b&&(A=b[0]!=="[ ] ",m=m.replace(this.rules.other.listReplaceTask,""))),o.items.push({type:"list_item",raw:u,task:!!b,checked:A,loose:!1,text:m,tokens:[]}),o.raw+=u}const r=o.items.at(-1);if(r)r.raw=r.raw.trimEnd(),r.text=r.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let p=0;p<o.items.length;p++)if(this.lexer.state.top=!1,o.items[p].tokens=this.lexer.blockTokens(o.items[p].text,[]),!o.loose){const u=o.items[p].tokens.filter(f=>f.type==="space"),m=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=m}if(o.loose)for(let p=0;p<o.items.length;p++)o.items[p].loose=!0;return o}}html(e){const i=this.rules.block.html.exec(e);if(i)return{type:"html",block:!0,raw:i[0],pre:i[1]==="pre"||i[1]==="script"||i[1]==="style",text:i[0]}}def(e){const i=this.rules.block.def.exec(e);if(i){const n=i[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=i[2]?i[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=i[3]?i[3].substring(1,i[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):i[3];return{type:"def",tag:n,raw:i[0],href:s,title:o}}}table(e){const i=this.rules.block.table.exec(e);if(!i||!this.rules.other.tableDelimiter.test(i[2]))return;const n=ha(i[1]),s=i[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=i[3]?.trim()?i[3].replace(this.rules.other.tableRowBlankLine,"").split(` `):[],t={type:"table",raw:i[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const c of s)this.rules.other.tableAlignRight.test(c)?t.align.push("right"):this.rules.other.tableAlignCenter.test(c)?t.align.push("center"):this.rules.other.tableAlignLeft.test(c)?t.align.push("left"):t.align.push(null);for(let c=0;c<n.length;c++)t.header.push({text:n[c],tokens:this.lexer.inline(n[c]),header:!0,align:t.align[c]});for(const c of o)t.rows.push(ha(c,t.header.length).map((r,p)=>({text:r,tokens:this.lexer.inline(r),header:!1,align:t.align[p]})));return t}}lheading(e){const i=this.rules.block.lheading.exec(e);if(i)return{type:"heading",raw:i[0],depth:i[2].charAt(0)==="="?1:2,text:i[1],tokens:this.lexer.inline(i[1])}}paragraph(e){const i=this.rules.block.paragraph.exec(e);if(i){const n=i[1].charAt(i[1].length-1)===` `?i[1].slice(0,-1):i[1];return{type:"paragraph",raw:i[0],text:n,tokens:this.lexer.inline(n)}}}text(e){const i=this.rules.block.text.exec(e);if(i)return{type:"text",raw:i[0],text:i[0],tokens:this.lexer.inline(i[0])}}escape(e){const i=this.rules.inline.escape.exec(e);if(i)return{type:"escape",raw:i[0],text:i[1]}}tag(e){const i=this.rules.inline.tag.exec(e);if(i)return!this.lexer.state.inLink&&this.rules.other.startATag.test(i[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(i[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(i[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(i[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:i[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:i[0]}}link(e){const i=this.rules.inline.link.exec(e);if(i){const n=i[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;const t=Z(n.slice(0,-1),"\\");if((n.length-t.length)%2===0)return}else{const t=cn(i[2],"()");if(t>-1){const r=(i[0].indexOf("!")===0?5:4)+i[1].length+t;i[2]=i[2].substring(0,t),i[0]=i[0].substring(0,r).trim(),i[3]=""}}let s=i[2],o="";if(this.options.pedantic){const t=this.rules.other.pedanticHrefTitle.exec(s);t&&(s=t[1],o=t[3])}else o=i[3]?i[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),ga(i,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},i[0],this.lexer,this.rules)}}reflink(e,i){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=i[s.toLowerCase()];if(!o){const t=n[0].charAt(0);return{type:"text",raw:t,text:t}}return ga(n,o,n[0],this.lexer,this.rules)}}emStrong(e,i,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const t=[...s[0]].length-1;let c,r,p=t,u=0;const m=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(m.lastIndex=0,i=i.slice(-1*e.length+t);(s=m.exec(i))!=null;){if(c=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!c)continue;if(r=[...c].length,s[3]||s[4]){p+=r;continue}else if((s[5]||s[6])&&t%3&&!((t+r)%3)){u+=r;continue}if(p-=r,p>0)continue;r=Math.min(r,r+p+u);const f=[...s[0]][0].length,l=e.slice(0,t+s.index+f+r);if(Math.min(t,r)%2){const x=l.slice(1,-1);return{type:"em",raw:l,text:x,tokens:this.lexer.inlineTokens(x)}}const d=l.slice(2,-2);return{type:"strong",raw:l,text:d,tokens:this.lexer.inlineTokens(d)}}}}codespan(e){const i=this.rules.inline.code.exec(e);if(i){let n=i[2].replace(this.rules.other.newLineCharGlobal," ");const s=this.rules.other.nonSpaceChar.test(n),o=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&o&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:i[0],text:n}}}br(e){const i=this.rules.inline.br.exec(e);if(i)return{type:"br",raw:i[0]}}del(e){const i=this.rules.inline.del.exec(e);if(i)return{type:"del",raw:i[0],text:i[2],tokens:this.lexer.inlineTokens(i[2])}}autolink(e){const i=this.rules.inline.autolink.exec(e);if(i){let n,s;return i[2]==="@"?(n=i[1],s="mailto:"+n):(n=i[1],s=n),{type:"link",raw:i[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let i;if(i=this.rules.inline.url.exec(e)){let n,s;if(i[2]==="@")n=i[0],s="mailto:"+n;else{let o;do o=i[0],i[0]=this.rules.inline._backpedal.exec(i[0])?.[0]??"";while(o!==i[0]);n=i[0],i[1]==="www."?s="http://"+i[0]:s=i[0]}return{type:"link",raw:i[0],text:n,href:s,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){const i=this.rules.inline.text.exec(e);if(i){const n=this.lexer.state.inRawBlock;return{type:"text",raw:i[0],text:i[0],escaped:n}}}}class S{tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||$,this.options.tokenizer=this.options.tokenizer||new ae,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inl