@opentiny/next-remoter 0.2.8 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/next-remoter-runtime.es.js +48 -56
- package/dist/next-remoter.cjs.js +39 -39
- package/dist/next-remoter.es.js +2927 -2935
- package/package.json +2 -2
package/dist/next-remoter.cjs.js
CHANGED
|
@@ -1,69 +1,69 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("vue"),Pt=require("@opentiny/tiny-robot"),Sd=require("@opentiny/genui-sdk-vue"),Hn=require("@opentiny/tiny-robot-kit"),Sr=require("@opentiny/tiny-robot-svgs"),Ht=require("@opentiny/next-sdk"),Td=require("@opentiny/vue-tooltip"),Nd=require("@opentiny/vue-icon");function Od(t,r){for(var o=0;o<r.length;o++){const c=r[o];if(typeof c!="string"&&!Array.isArray(c)){for(const u in c)if(u!=="default"&&!(u in t)){const f=Object.getOwnPropertyDescriptor(c,u);f&&Object.defineProperty(t,u,f.get?f:{enumerable:!0,get:()=>c[u]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var vl="vercel.ai.error",Rd=Symbol.for(vl),Is,Ss,xt=class Cl extends(Ss=Error,Is=Rd,Ss){constructor({name:r,message:o,cause:c}){super(o),this[Is]=!0,this.name=r,this.cause=c}static isInstance(r){return Cl.hasMarker(r,vl)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},bl="AI_APICallError",El=`vercel.ai.error.${bl}`,kd=Symbol.for(El),Ts,Ns,sn=class extends(Ns=xt,Ts=kd,Ns){constructor({message:r,url:o,requestBodyValues:c,statusCode:u,responseHeaders:f,responseBody:
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("vue"),Pt=require("@opentiny/tiny-robot"),Sd=require("@opentiny/genui-sdk-vue"),Hn=require("@opentiny/tiny-robot-kit"),Sr=require("@opentiny/tiny-robot-svgs"),Ht=require("@opentiny/next-sdk"),Td=require("@opentiny/vue-tooltip"),Nd=require("@opentiny/vue-icon");function Od(t,r){for(var o=0;o<r.length;o++){const c=r[o];if(typeof c!="string"&&!Array.isArray(c)){for(const u in c)if(u!=="default"&&!(u in t)){const f=Object.getOwnPropertyDescriptor(c,u);f&&Object.defineProperty(t,u,f.get?f:{enumerable:!0,get:()=>c[u]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var vl="vercel.ai.error",Rd=Symbol.for(vl),Is,Ss,xt=class Cl extends(Ss=Error,Is=Rd,Ss){constructor({name:r,message:o,cause:c}){super(o),this[Is]=!0,this.name=r,this.cause=c}static isInstance(r){return Cl.hasMarker(r,vl)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},bl="AI_APICallError",El=`vercel.ai.error.${bl}`,kd=Symbol.for(El),Ts,Ns,sn=class extends(Ns=xt,Ts=kd,Ns){constructor({message:r,url:o,requestBodyValues:c,statusCode:u,responseHeaders:f,responseBody:m,cause:x,isRetryable:_=u!=null&&(u===408||u===409||u===429||u>=500),data:g}){super({name:bl,message:r,cause:x}),this[Ts]=!0,this.url=o,this.requestBodyValues=c,this.statusCode=u,this.responseHeaders=f,this.responseBody=m,this.isRetryable=_,this.data=g}static isInstance(r){return xt.hasMarker(r,El)}},Al="AI_EmptyResponseBodyError",Il=`vercel.ai.error.${Al}`,Md=Symbol.for(Il),Os,Rs,Dd=class extends(Rs=xt,Os=Md,Rs){constructor({message:r="Empty response body"}={}){super({name:Al,message:r}),this[Os]=!0}static isInstance(r){return xt.hasMarker(r,Il)}};function Sl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Tl="AI_InvalidArgumentError",Nl=`vercel.ai.error.${Tl}`,Pd=Symbol.for(Nl),ks,Ms,Ol=class extends(Ms=xt,ks=Pd,Ms){constructor({message:r,cause:o,argument:c}){super({name:Tl,message:r,cause:o}),this[ks]=!0,this.argument=c}static isInstance(r){return xt.hasMarker(r,Nl)}},Rl="AI_InvalidPromptError",kl=`vercel.ai.error.${Rl}`,Bd=Symbol.for(kl),Ds,Ps,Ld=class extends(Ps=xt,Ds=Bd,Ps){constructor({prompt:t,message:r,cause:o}){super({name:Rl,message:`Invalid prompt: ${r}`,cause:o}),this[Ds]=!0,this.prompt=t}static isInstance(t){return xt.hasMarker(t,kl)}},Ml="AI_InvalidResponseDataError",Dl=`vercel.ai.error.${Ml}`,Fd=Symbol.for(Dl),Bs,Ls,fo=class extends(Ls=xt,Bs=Fd,Ls){constructor({data:r,message:o=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Ml,message:o}),this[Bs]=!0,this.data=r}static isInstance(r){return xt.hasMarker(r,Dl)}},Pl="AI_JSONParseError",Bl=`vercel.ai.error.${Pl}`,Ud=Symbol.for(Bl),Fs,Us,Oi=class extends(Us=xt,Fs=Ud,Us){constructor({text:r,cause:o}){super({name:Pl,message:`JSON parsing failed: Text: ${r}.
|
|
2
2
|
Error message: ${Sl(o)}`,cause:o}),this[Fs]=!0,this.text=r}static isInstance(r){return xt.hasMarker(r,Bl)}},Ll="AI_LoadAPIKeyError",Fl=`vercel.ai.error.${Ll}`,zd=Symbol.for(Fl),zs,$s,yi=class extends($s=xt,zs=zd,$s){constructor({message:r}){super({name:Ll,message:r}),this[zs]=!0}static isInstance(r){return xt.hasMarker(r,Fl)}},Ul="AI_TooManyEmbeddingValuesForCallError",zl=`vercel.ai.error.${Ul}`,$d=Symbol.for(zl),Vs,Zs,Vd=class extends(Zs=xt,Vs=$d,Zs){constructor(t){super({name:Ul,message:`Too many values for a single embedding call. The ${t.provider} model "${t.modelId}" can only embed up to ${t.maxEmbeddingsPerCall} values per call, but ${t.values.length} values were provided.`}),this[Vs]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return xt.hasMarker(t,zl)}},$l="AI_TypeValidationError",Vl=`vercel.ai.error.${$l}`,Zd=Symbol.for(Vl),js,Ws,cr=class Ao extends(Ws=xt,js=Zd,Ws){constructor({value:r,cause:o,context:c}){let u="Type validation failed";if(c?.field&&(u+=` for ${c.field}`),c?.entityName||c?.entityId){u+=" (";const f=[];c.entityName&&f.push(c.entityName),c.entityId&&f.push(`id: "${c.entityId}"`),u+=f.join(", "),u+=")"}super({name:$l,message:`${u}: Value: ${JSON.stringify(r)}.
|
|
3
|
-
Error message: ${Sl(o)}`,cause:o}),this[js]=!0,this.value=r,this.context=c}static isInstance(r){return xt.hasMarker(r,Vl)}static wrap({value:r,cause:o,context:c}){var u,f,p;return Ao.isInstance(o)&&o.value===r&&((u=o.context)==null?void 0:u.field)===c?.field&&((f=o.context)==null?void 0:f.entityName)===c?.entityName&&((p=o.context)==null?void 0:p.entityId)===c?.entityId?o:new Ao({value:r,cause:o,context:c})}},Zl="AI_UnsupportedFunctionalityError",jl=`vercel.ai.error.${Zl}`,jd=Symbol.for(jl),Hs,Gs,Dn=class extends(Gs=xt,Hs=jd,Gs){constructor({functionality:r,message:o=`'${r}' functionality not supported.`}){super({name:Zl,message:o}),this[Hs]=!0,this.functionality=r}static isInstance(r){return xt.hasMarker(r,jl)}};function se(t,r,o){function c(x,_){var g;Object.defineProperty(x,"_zod",{value:x._zod??{},enumerable:!1}),(g=x._zod).traits??(g.traits=new Set),x._zod.traits.add(t),r(x,_);for(const C in p.prototype)C in x||Object.defineProperty(x,C,{value:p.prototype[C].bind(x)});x._zod.constr=p,x._zod.def=_}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function p(x){var _;const g=o?.Parent?new f:this;c(g,x),(_=g._zod).deferred??(_.deferred=[]);for(const C of g._zod.deferred)C();return g}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:x=>o?.Parent&&x instanceof o.Parent?!0:x?._zod?.traits?.has(t)}),Object.defineProperty(p,"name",{value:t}),p}class Yr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Wl={};function Xn(t){return Wl}function Hl(t){const r=Object.values(t).filter(c=>typeof c=="number");return Object.entries(t).filter(([c,u])=>r.indexOf(+c)===-1).map(([c,u])=>u)}function Wd(t,r){return typeof r=="bigint"?r.toString():r}function $o(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function Vo(t){return t==null}function Zo(t){const r=t.startsWith("^")?1:0,o=t.endsWith("$")?t.length-1:t.length;return t.slice(r,o)}function Hd(t,r){const o=(t.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,u=o>c?o:c,f=Number.parseInt(t.toFixed(u).replace(".","")),p=Number.parseInt(r.toFixed(u).replace(".",""));return f%p/10**u}function nt(t,r,o){Object.defineProperty(t,r,{get(){{const c=o();return t[r]=c,c}},set(c){Object.defineProperty(t,r,{value:c})},configurable:!0})}function jo(t,r,o){Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0})}function Ur(t){return JSON.stringify(t)}const Gl=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ri(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Gd=$o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function ki(t){if(Ri(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const o=r.prototype;return!(Ri(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}const Xd=new Set(["string","number","symbol"]);function ni(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dr(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function be(t){const r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function qd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Yd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Jd(t,r){const o={},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(o[u]=c.shape[u])}return dr(t,{...t._zod.def,shape:o,checks:[]})}function Kd(t,r){const o={...t._zod.def.shape},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&delete o[u]}return dr(t,{...t._zod.def,shape:o,checks:[]})}function Qd(t,r){if(!ki(r))throw new Error("Invalid input to extend: expected a plain object");const o={...t._zod.def,get shape(){const c={...t._zod.def.shape,...r};return jo(this,"shape",c),c},checks:[]};return dr(t,o)}function e1(t,r){return dr(t,{...t._zod.def,get shape(){const o={...t._zod.def.shape,...r._zod.def.shape};return jo(this,"shape",o),o},catchall:r._zod.def.catchall,checks:[]})}function t1(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in c))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=t?new t({type:"optional",innerType:c[f]}):c[f])}else for(const f in c)u[f]=t?new t({type:"optional",innerType:c[f]}):c[f];return dr(r,{...r._zod.def,shape:u,checks:[]})}function n1(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in u))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=new t({type:"nonoptional",innerType:c[f]}))}else for(const f in c)u[f]=new t({type:"nonoptional",innerType:c[f]});return dr(r,{...r._zod.def,shape:u,checks:[]})}function Xr(t,r=0){for(let o=r;o<t.issues.length;o++)if(t.issues[o]?.continue!==!0)return!0;return!1}function ar(t,r){return r.map(o=>{var c;return(c=o).path??(c.path=[]),o.path.unshift(t),o})}function wi(t){return typeof t=="string"?t:t?.message}function qn(t,r,o){const c={...t,path:t.path??[]};if(!t.message){const u=wi(t.inst?._zod.def?.error?.(t))??wi(r?.error?.(t))??wi(o.customError?.(t))??wi(o.localeError?.(t))??"Invalid input";c.message=u}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function Wo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Jr(...t){const[r,o,c]=t;return typeof r=="string"?{message:r,code:"custom",input:o,inst:c}:{...r}}const Xl=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,Wd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ql=se("$ZodError",Xl),Yl=se("$ZodError",Xl,{Parent:Error});function r1(t,r=o=>o.message){const o={},c=[];for(const u of t.issues)u.path.length>0?(o[u.path[0]]=o[u.path[0]]||[],o[u.path[0]].push(r(u))):c.push(r(u));return{formErrors:c,fieldErrors:o}}function i1(t,r){const o=r||function(f){return f.message},c={_errors:[]},u=f=>{for(const p of f.issues)if(p.code==="invalid_union"&&p.errors.length)p.errors.map(x=>u({issues:x}));else if(p.code==="invalid_key")u({issues:p.issues});else if(p.code==="invalid_element")u({issues:p.issues});else if(p.path.length===0)c._errors.push(o(p));else{let x=c,_=0;for(;_<p.path.length;){const g=p.path[_];_===p.path.length-1?(x[g]=x[g]||{_errors:[]},x[g]._errors.push(o(p))):x[g]=x[g]||{_errors:[]},x=x[g],_++}}};return u(t),c}const o1=t=>(r,o,c,u)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},p=r._zod.run({value:o,issues:[]},f);if(p instanceof Promise)throw new Yr;if(p.issues.length){const x=new(u?.Err??t)(p.issues.map(_=>qn(_,f,Xn())));throw Gl(x,u?.callee),x}return p.value},s1=t=>async(r,o,c,u)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let p=r._zod.run({value:o,issues:[]},f);if(p instanceof Promise&&(p=await p),p.issues.length){const x=new(u?.Err??t)(p.issues.map(_=>qn(_,f,Xn())));throw Gl(x,u?.callee),x}return p.value},Jl=t=>(r,o,c)=>{const u=c?{...c,async:!1}:{async:!1},f=r._zod.run({value:o,issues:[]},u);if(f instanceof Promise)throw new Yr;return f.issues.length?{success:!1,error:new(t??ql)(f.issues.map(p=>qn(p,u,Xn())))}:{success:!0,data:f.value}},a1=Jl(Yl),Kl=t=>async(r,o,c)=>{const u=c?Object.assign(c,{async:!0}):{async:!0};let f=r._zod.run({value:o,issues:[]},u);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new t(f.issues.map(p=>qn(p,u,Xn())))}:{success:!0,data:f.value}},l1=Kl(Yl),c1=/^[cC][^\s-]{8,}$/,u1=/^[0-9a-z]+$/,d1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,f1=/^[0-9a-vA-V]{20}$/,h1=/^[A-Za-z0-9]{27}$/,p1=/^[a-zA-Z0-9_-]{21}$/,m1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,g1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xs=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,x1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,y1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function w1(){return new RegExp(y1,"u")}const _1=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,v1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,C1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,b1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,E1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ql=/^[A-Za-z0-9_-]*$/,A1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,I1=/^\+(?:[0-9]){6,14}[0-9]$/,ec="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",S1=new RegExp(`^${ec}$`);function tc(t){const r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function T1(t){return new RegExp(`^${tc(t)}$`)}function N1(t){const r=tc({precision:t.precision}),o=["Z"];t.local&&o.push(""),t.offset&&o.push("([+-]\\d{2}:\\d{2})");const c=`${r}(?:${o.join("|")})`;return new RegExp(`^${ec}T(?:${c})$`)}const O1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},R1=/^\d+$/,k1=/^-?\d+(?:\.\d+)?/i,M1=/true|false/i,D1=/null/i,P1=/^[^A-Z]*$/,B1=/^[^a-z]*$/,tn=se("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),nc={number:"number",bigint:"bigint",object:"date"},rc=se("$ZodCheckLessThan",(t,r)=>{tn.init(t,r);const o=nc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.maximum:u.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<f&&(r.inclusive?u.maximum=r.value:u.exclusiveMaximum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value<=r.value:c.value<r.value)||c.issues.push({origin:o,code:"too_big",maximum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),ic=se("$ZodCheckGreaterThan",(t,r)=>{tn.init(t,r);const o=nc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.minimum:u.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>f&&(r.inclusive?u.minimum=r.value:u.exclusiveMinimum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value>=r.value:c.value>r.value)||c.issues.push({origin:o,code:"too_small",minimum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),L1=se("$ZodCheckMultipleOf",(t,r)=>{tn.init(t,r),t._zod.onattach.push(o=>{var c;(c=o._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=o=>{if(typeof o.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%r.value===BigInt(0):Hd(o.value,r.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:r.value,input:o.value,inst:t,continue:!r.abort})}}),F1=se("$ZodCheckNumberFormat",(t,r)=>{tn.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=Yd[r.format];t._zod.onattach.push(p=>{const x=p._zod.bag;x.format=r.format,x.minimum=u,x.maximum=f,o&&(x.pattern=R1)}),t._zod.check=p=>{const x=p.value;if(o){if(!Number.isInteger(x)){p.issues.push({expected:c,format:r.format,code:"invalid_type",input:x,inst:t});return}if(!Number.isSafeInteger(x)){x>0?p.issues.push({input:x,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort}):p.issues.push({input:x,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort});return}}x<u&&p.issues.push({origin:"number",input:x,code:"too_small",minimum:u,inclusive:!0,inst:t,continue:!r.abort}),x>f&&p.issues.push({origin:"number",input:x,code:"too_big",maximum:f,inst:t})}}),U1=se("$ZodCheckMaxLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<u&&(c._zod.bag.maximum=r.maximum)}),t._zod.check=c=>{const u=c.value;if(u.length<=r.maximum)return;const p=Wo(u);c.issues.push({origin:p,code:"too_big",maximum:r.maximum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),z1=se("$ZodCheckMinLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>u&&(c._zod.bag.minimum=r.minimum)}),t._zod.check=c=>{const u=c.value;if(u.length>=r.minimum)return;const p=Wo(u);c.issues.push({origin:p,code:"too_small",minimum:r.minimum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),$1=se("$ZodCheckLengthEquals",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag;u.minimum=r.length,u.maximum=r.length,u.length=r.length}),t._zod.check=c=>{const u=c.value,f=u.length;if(f===r.length)return;const p=Wo(u),x=f>r.length;c.issues.push({origin:p,...x?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Ui=se("$ZodCheckStringFormat",(t,r)=>{var o,c;tn.init(t,r),t._zod.onattach.push(u=>{const f=u._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(o=t._zod).check??(o.check=u=>{r.pattern.lastIndex=0,!r.pattern.test(u.value)&&u.issues.push({origin:"string",code:"invalid_format",format:r.format,input:u.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),V1=se("$ZodCheckRegex",(t,r)=>{Ui.init(t,r),t._zod.check=o=>{r.pattern.lastIndex=0,!r.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),Z1=se("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=P1),Ui.init(t,r)}),j1=se("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=B1),Ui.init(t,r)}),W1=se("$ZodCheckIncludes",(t,r)=>{tn.init(t,r);const o=ni(r.includes),c=new RegExp(typeof r.position=="number"?`^.{${r.position}}${o}`:o);r.pattern=c,t._zod.onattach.push(u=>{const f=u._zod.bag;f.patterns??(f.patterns=new Set),f.patterns.add(c)}),t._zod.check=u=>{u.value.includes(r.includes,r.position)||u.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:u.value,inst:t,continue:!r.abort})}}),H1=se("$ZodCheckStartsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`^${ni(r.prefix)}.*`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.startsWith(r.prefix)||c.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:c.value,inst:t,continue:!r.abort})}}),G1=se("$ZodCheckEndsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`.*${ni(r.suffix)}$`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.endsWith(r.suffix)||c.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:c.value,inst:t,continue:!r.abort})}}),X1=se("$ZodCheckOverwrite",(t,r)=>{tn.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class q1{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}const c=r.split(`
|
|
4
|
-
`).filter(
|
|
5
|
-
`))}}const Y1={major:4,minor:0,patch:0},ct=se("$ZodType",(t,r)=>{var o;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=Y1;const c=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&c.unshift(t);for(const u of c)for(const f of u._zod.onattach)f(t);if(c.length===0)(o=t._zod).deferred??(o.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const u=(f,
|
|
3
|
+
Error message: ${Sl(o)}`,cause:o}),this[js]=!0,this.value=r,this.context=c}static isInstance(r){return xt.hasMarker(r,Vl)}static wrap({value:r,cause:o,context:c}){var u,f,m;return Ao.isInstance(o)&&o.value===r&&((u=o.context)==null?void 0:u.field)===c?.field&&((f=o.context)==null?void 0:f.entityName)===c?.entityName&&((m=o.context)==null?void 0:m.entityId)===c?.entityId?o:new Ao({value:r,cause:o,context:c})}},Zl="AI_UnsupportedFunctionalityError",jl=`vercel.ai.error.${Zl}`,jd=Symbol.for(jl),Hs,Gs,Dn=class extends(Gs=xt,Hs=jd,Gs){constructor({functionality:r,message:o=`'${r}' functionality not supported.`}){super({name:Zl,message:o}),this[Hs]=!0,this.functionality=r}static isInstance(r){return xt.hasMarker(r,jl)}};function se(t,r,o){function c(x,_){var g;Object.defineProperty(x,"_zod",{value:x._zod??{},enumerable:!1}),(g=x._zod).traits??(g.traits=new Set),x._zod.traits.add(t),r(x,_);for(const C in m.prototype)C in x||Object.defineProperty(x,C,{value:m.prototype[C].bind(x)});x._zod.constr=m,x._zod.def=_}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function m(x){var _;const g=o?.Parent?new f:this;c(g,x),(_=g._zod).deferred??(_.deferred=[]);for(const C of g._zod.deferred)C();return g}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:x=>o?.Parent&&x instanceof o.Parent?!0:x?._zod?.traits?.has(t)}),Object.defineProperty(m,"name",{value:t}),m}class Yr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Wl={};function Xn(t){return Wl}function Hl(t){const r=Object.values(t).filter(c=>typeof c=="number");return Object.entries(t).filter(([c,u])=>r.indexOf(+c)===-1).map(([c,u])=>u)}function Wd(t,r){return typeof r=="bigint"?r.toString():r}function $o(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function Vo(t){return t==null}function Zo(t){const r=t.startsWith("^")?1:0,o=t.endsWith("$")?t.length-1:t.length;return t.slice(r,o)}function Hd(t,r){const o=(t.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,u=o>c?o:c,f=Number.parseInt(t.toFixed(u).replace(".","")),m=Number.parseInt(r.toFixed(u).replace(".",""));return f%m/10**u}function nt(t,r,o){Object.defineProperty(t,r,{get(){{const c=o();return t[r]=c,c}},set(c){Object.defineProperty(t,r,{value:c})},configurable:!0})}function jo(t,r,o){Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0})}function Ur(t){return JSON.stringify(t)}const Gl=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ri(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Gd=$o(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function ki(t){if(Ri(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const o=r.prototype;return!(Ri(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}const Xd=new Set(["string","number","symbol"]);function ni(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dr(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function be(t){const r=t;if(!r)return{};if(typeof r=="string")return{error:()=>r};if(r?.message!==void 0){if(r?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");r.error=r.message}return delete r.message,typeof r.error=="string"?{...r,error:()=>r.error}:r}function qd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Yd={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Jd(t,r){const o={},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&(o[u]=c.shape[u])}return dr(t,{...t._zod.def,shape:o,checks:[]})}function Kd(t,r){const o={...t._zod.def.shape},c=t._zod.def;for(const u in r){if(!(u in c.shape))throw new Error(`Unrecognized key: "${u}"`);r[u]&&delete o[u]}return dr(t,{...t._zod.def,shape:o,checks:[]})}function Qd(t,r){if(!ki(r))throw new Error("Invalid input to extend: expected a plain object");const o={...t._zod.def,get shape(){const c={...t._zod.def.shape,...r};return jo(this,"shape",c),c},checks:[]};return dr(t,o)}function e1(t,r){return dr(t,{...t._zod.def,get shape(){const o={...t._zod.def.shape,...r._zod.def.shape};return jo(this,"shape",o),o},catchall:r._zod.def.catchall,checks:[]})}function t1(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in c))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=t?new t({type:"optional",innerType:c[f]}):c[f])}else for(const f in c)u[f]=t?new t({type:"optional",innerType:c[f]}):c[f];return dr(r,{...r._zod.def,shape:u,checks:[]})}function n1(t,r,o){const c=r._zod.def.shape,u={...c};if(o)for(const f in o){if(!(f in u))throw new Error(`Unrecognized key: "${f}"`);o[f]&&(u[f]=new t({type:"nonoptional",innerType:c[f]}))}else for(const f in c)u[f]=new t({type:"nonoptional",innerType:c[f]});return dr(r,{...r._zod.def,shape:u,checks:[]})}function Xr(t,r=0){for(let o=r;o<t.issues.length;o++)if(t.issues[o]?.continue!==!0)return!0;return!1}function ar(t,r){return r.map(o=>{var c;return(c=o).path??(c.path=[]),o.path.unshift(t),o})}function wi(t){return typeof t=="string"?t:t?.message}function qn(t,r,o){const c={...t,path:t.path??[]};if(!t.message){const u=wi(t.inst?._zod.def?.error?.(t))??wi(r?.error?.(t))??wi(o.customError?.(t))??wi(o.localeError?.(t))??"Invalid input";c.message=u}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function Wo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Jr(...t){const[r,o,c]=t;return typeof r=="string"?{message:r,code:"custom",input:o,inst:c}:{...r}}const Xl=(t,r)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:r,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(r,Wd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ql=se("$ZodError",Xl),Yl=se("$ZodError",Xl,{Parent:Error});function r1(t,r=o=>o.message){const o={},c=[];for(const u of t.issues)u.path.length>0?(o[u.path[0]]=o[u.path[0]]||[],o[u.path[0]].push(r(u))):c.push(r(u));return{formErrors:c,fieldErrors:o}}function i1(t,r){const o=r||function(f){return f.message},c={_errors:[]},u=f=>{for(const m of f.issues)if(m.code==="invalid_union"&&m.errors.length)m.errors.map(x=>u({issues:x}));else if(m.code==="invalid_key")u({issues:m.issues});else if(m.code==="invalid_element")u({issues:m.issues});else if(m.path.length===0)c._errors.push(o(m));else{let x=c,_=0;for(;_<m.path.length;){const g=m.path[_];_===m.path.length-1?(x[g]=x[g]||{_errors:[]},x[g]._errors.push(o(m))):x[g]=x[g]||{_errors:[]},x=x[g],_++}}};return u(t),c}const o1=t=>(r,o,c,u)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},m=r._zod.run({value:o,issues:[]},f);if(m instanceof Promise)throw new Yr;if(m.issues.length){const x=new(u?.Err??t)(m.issues.map(_=>qn(_,f,Xn())));throw Gl(x,u?.callee),x}return m.value},s1=t=>async(r,o,c,u)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let m=r._zod.run({value:o,issues:[]},f);if(m instanceof Promise&&(m=await m),m.issues.length){const x=new(u?.Err??t)(m.issues.map(_=>qn(_,f,Xn())));throw Gl(x,u?.callee),x}return m.value},Jl=t=>(r,o,c)=>{const u=c?{...c,async:!1}:{async:!1},f=r._zod.run({value:o,issues:[]},u);if(f instanceof Promise)throw new Yr;return f.issues.length?{success:!1,error:new(t??ql)(f.issues.map(m=>qn(m,u,Xn())))}:{success:!0,data:f.value}},a1=Jl(Yl),Kl=t=>async(r,o,c)=>{const u=c?Object.assign(c,{async:!0}):{async:!0};let f=r._zod.run({value:o,issues:[]},u);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new t(f.issues.map(m=>qn(m,u,Xn())))}:{success:!0,data:f.value}},l1=Kl(Yl),c1=/^[cC][^\s-]{8,}$/,u1=/^[0-9a-z]+$/,d1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,f1=/^[0-9a-vA-V]{20}$/,h1=/^[A-Za-z0-9]{27}$/,p1=/^[a-zA-Z0-9_-]{21}$/,m1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,g1=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Xs=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,x1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,y1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function w1(){return new RegExp(y1,"u")}const _1=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,v1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,C1=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,b1=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,E1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ql=/^[A-Za-z0-9_-]*$/,A1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,I1=/^\+(?:[0-9]){6,14}[0-9]$/,ec="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",S1=new RegExp(`^${ec}$`);function tc(t){const r="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${r}`:t.precision===0?`${r}:[0-5]\\d`:`${r}:[0-5]\\d\\.\\d{${t.precision}}`:`${r}(?::[0-5]\\d(?:\\.\\d+)?)?`}function T1(t){return new RegExp(`^${tc(t)}$`)}function N1(t){const r=tc({precision:t.precision}),o=["Z"];t.local&&o.push(""),t.offset&&o.push("([+-]\\d{2}:\\d{2})");const c=`${r}(?:${o.join("|")})`;return new RegExp(`^${ec}T(?:${c})$`)}const O1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},R1=/^\d+$/,k1=/^-?\d+(?:\.\d+)?/i,M1=/true|false/i,D1=/null/i,P1=/^[^A-Z]*$/,B1=/^[^a-z]*$/,tn=se("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),nc={number:"number",bigint:"bigint",object:"date"},rc=se("$ZodCheckLessThan",(t,r)=>{tn.init(t,r);const o=nc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.maximum:u.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<f&&(r.inclusive?u.maximum=r.value:u.exclusiveMaximum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value<=r.value:c.value<r.value)||c.issues.push({origin:o,code:"too_big",maximum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),ic=se("$ZodCheckGreaterThan",(t,r)=>{tn.init(t,r);const o=nc[typeof r.value];t._zod.onattach.push(c=>{const u=c._zod.bag,f=(r.inclusive?u.minimum:u.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>f&&(r.inclusive?u.minimum=r.value:u.exclusiveMinimum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value>=r.value:c.value>r.value)||c.issues.push({origin:o,code:"too_small",minimum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),L1=se("$ZodCheckMultipleOf",(t,r)=>{tn.init(t,r),t._zod.onattach.push(o=>{var c;(c=o._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=o=>{if(typeof o.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%r.value===BigInt(0):Hd(o.value,r.value)===0)||o.issues.push({origin:typeof o.value,code:"not_multiple_of",divisor:r.value,input:o.value,inst:t,continue:!r.abort})}}),F1=se("$ZodCheckNumberFormat",(t,r)=>{tn.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=Yd[r.format];t._zod.onattach.push(m=>{const x=m._zod.bag;x.format=r.format,x.minimum=u,x.maximum=f,o&&(x.pattern=R1)}),t._zod.check=m=>{const x=m.value;if(o){if(!Number.isInteger(x)){m.issues.push({expected:c,format:r.format,code:"invalid_type",input:x,inst:t});return}if(!Number.isSafeInteger(x)){x>0?m.issues.push({input:x,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort}):m.issues.push({input:x,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort});return}}x<u&&m.issues.push({origin:"number",input:x,code:"too_small",minimum:u,inclusive:!0,inst:t,continue:!r.abort}),x>f&&m.issues.push({origin:"number",input:x,code:"too_big",maximum:f,inst:t})}}),U1=se("$ZodCheckMaxLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<u&&(c._zod.bag.maximum=r.maximum)}),t._zod.check=c=>{const u=c.value;if(u.length<=r.maximum)return;const m=Wo(u);c.issues.push({origin:m,code:"too_big",maximum:r.maximum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),z1=se("$ZodCheckMinLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>u&&(c._zod.bag.minimum=r.minimum)}),t._zod.check=c=>{const u=c.value;if(u.length>=r.minimum)return;const m=Wo(u);c.issues.push({origin:m,code:"too_small",minimum:r.minimum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),$1=se("$ZodCheckLengthEquals",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Vo(u)&&u.length!==void 0}),t._zod.onattach.push(c=>{const u=c._zod.bag;u.minimum=r.length,u.maximum=r.length,u.length=r.length}),t._zod.check=c=>{const u=c.value,f=u.length;if(f===r.length)return;const m=Wo(u),x=f>r.length;c.issues.push({origin:m,...x?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Ui=se("$ZodCheckStringFormat",(t,r)=>{var o,c;tn.init(t,r),t._zod.onattach.push(u=>{const f=u._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(o=t._zod).check??(o.check=u=>{r.pattern.lastIndex=0,!r.pattern.test(u.value)&&u.issues.push({origin:"string",code:"invalid_format",format:r.format,input:u.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),V1=se("$ZodCheckRegex",(t,r)=>{Ui.init(t,r),t._zod.check=o=>{r.pattern.lastIndex=0,!r.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:"regex",input:o.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),Z1=se("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=P1),Ui.init(t,r)}),j1=se("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=B1),Ui.init(t,r)}),W1=se("$ZodCheckIncludes",(t,r)=>{tn.init(t,r);const o=ni(r.includes),c=new RegExp(typeof r.position=="number"?`^.{${r.position}}${o}`:o);r.pattern=c,t._zod.onattach.push(u=>{const f=u._zod.bag;f.patterns??(f.patterns=new Set),f.patterns.add(c)}),t._zod.check=u=>{u.value.includes(r.includes,r.position)||u.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:u.value,inst:t,continue:!r.abort})}}),H1=se("$ZodCheckStartsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`^${ni(r.prefix)}.*`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.startsWith(r.prefix)||c.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:r.prefix,input:c.value,inst:t,continue:!r.abort})}}),G1=se("$ZodCheckEndsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`.*${ni(r.suffix)}$`);r.pattern??(r.pattern=o),t._zod.onattach.push(c=>{const u=c._zod.bag;u.patterns??(u.patterns=new Set),u.patterns.add(o)}),t._zod.check=c=>{c.value.endsWith(r.suffix)||c.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:r.suffix,input:c.value,inst:t,continue:!r.abort})}}),X1=se("$ZodCheckOverwrite",(t,r)=>{tn.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class q1{constructor(r=[]){this.content=[],this.indent=0,this&&(this.args=r)}indented(r){this.indent+=1,r(this),this.indent-=1}write(r){if(typeof r=="function"){r(this,{execution:"sync"}),r(this,{execution:"async"});return}const c=r.split(`
|
|
4
|
+
`).filter(m=>m),u=Math.min(...c.map(m=>m.length-m.trimStart().length)),f=c.map(m=>m.slice(u)).map(m=>" ".repeat(this.indent*2)+m);for(const m of f)this.content.push(m)}compile(){const r=Function,o=this?.args,u=[...(this?.content??[""]).map(f=>` ${f}`)];return new r(...o,u.join(`
|
|
5
|
+
`))}}const Y1={major:4,minor:0,patch:0},ct=se("$ZodType",(t,r)=>{var o;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=Y1;const c=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&c.unshift(t);for(const u of c)for(const f of u._zod.onattach)f(t);if(c.length===0)(o=t._zod).deferred??(o.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const u=(f,m,x)=>{let _=Xr(f),g;for(const C of m){if(C._zod.def.when){if(!C._zod.def.when(f))continue}else if(_)continue;const A=f.issues.length,P=C._zod.check(f);if(P instanceof Promise&&x?.async===!1)throw new Yr;if(g||P instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await P,f.issues.length!==A&&(_||(_=Xr(f,A)))});else{if(f.issues.length===A)continue;_||(_=Xr(f,A))}}return g?g.then(()=>f):f};t._zod.run=(f,m)=>{const x=t._zod.parse(f,m);if(x instanceof Promise){if(m.async===!1)throw new Yr;return x.then(_=>u(_,c,m))}return u(x,c,m)}}t["~standard"]={validate:u=>{try{const f=a1(t,u);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return l1(t,u).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),Ho=se("$ZodString",(t,r)=>{ct.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??O1(t._zod.bag),t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=String(o.value)}catch{}return typeof o.value=="string"||o.issues.push({expected:"string",code:"invalid_type",input:o.value,inst:t}),o}}),yt=se("$ZodStringFormat",(t,r)=>{Ui.init(t,r),Ho.init(t,r)}),J1=se("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=g1),yt.init(t,r)}),K1=se("$ZodUUID",(t,r)=>{if(r.version){const c={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[r.version];if(c===void 0)throw new Error(`Invalid UUID version: "${r.version}"`);r.pattern??(r.pattern=Xs(c))}else r.pattern??(r.pattern=Xs());yt.init(t,r)}),Q1=se("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=x1),yt.init(t,r)}),e0=se("$ZodURL",(t,r)=>{yt.init(t,r),t._zod.check=o=>{try{const c=o.value,u=new URL(c),f=u.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(u.hostname)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:A1.source,input:o.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(u.protocol.endsWith(":")?u.protocol.slice(0,-1):u.protocol)||o.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:o.value,inst:t,continue:!r.abort})),!c.endsWith("/")&&f.endsWith("/")?o.value=f.slice(0,-1):o.value=f;return}catch{o.issues.push({code:"invalid_format",format:"url",input:o.value,inst:t,continue:!r.abort})}}}),t0=se("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=w1()),yt.init(t,r)}),n0=se("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=p1),yt.init(t,r)}),r0=se("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=c1),yt.init(t,r)}),i0=se("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=u1),yt.init(t,r)}),o0=se("$ZodULID",(t,r)=>{r.pattern??(r.pattern=d1),yt.init(t,r)}),s0=se("$ZodXID",(t,r)=>{r.pattern??(r.pattern=f1),yt.init(t,r)}),a0=se("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=h1),yt.init(t,r)}),l0=se("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=N1(r)),yt.init(t,r)}),c0=se("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=S1),yt.init(t,r)}),u0=se("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=T1(r)),yt.init(t,r)}),d0=se("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=m1),yt.init(t,r)}),f0=se("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=_1),yt.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv4"})}),h0=se("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=v1),yt.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv6"}),t._zod.check=o=>{try{new URL(`http://[${o.value}]`)}catch{o.issues.push({code:"invalid_format",format:"ipv6",input:o.value,inst:t,continue:!r.abort})}}}),p0=se("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=C1),yt.init(t,r)}),m0=se("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=b1),yt.init(t,r),t._zod.check=o=>{const[c,u]=o.value.split("/");try{if(!u)throw new Error;const f=Number(u);if(`${f}`!==u)throw new Error;if(f<0||f>128)throw new Error;new URL(`http://[${c}]`)}catch{o.issues.push({code:"invalid_format",format:"cidrv6",input:o.value,inst:t,continue:!r.abort})}}});function oc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const g0=se("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=E1),yt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64"}),t._zod.check=o=>{oc(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:t,continue:!r.abort})}});function x0(t){if(!Ql.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),o=r.padEnd(Math.ceil(r.length/4)*4,"=");return oc(o)}const y0=se("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=Ql),yt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64url"}),t._zod.check=o=>{x0(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:t,continue:!r.abort})}}),w0=se("$ZodE164",(t,r)=>{r.pattern??(r.pattern=I1),yt.init(t,r)});function _0(t,r=null){try{const o=t.split(".");if(o.length!==3)return!1;const[c]=o;if(!c)return!1;const u=JSON.parse(atob(c));return!("typ"in u&&u?.typ!=="JWT"||!u.alg||r&&(!("alg"in u)||u.alg!==r))}catch{return!1}}const v0=se("$ZodJWT",(t,r)=>{yt.init(t,r),t._zod.check=o=>{_0(o.value,r.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:t,continue:!r.abort})}}),sc=se("$ZodNumber",(t,r)=>{ct.init(t,r),t._zod.pattern=t._zod.bag.pattern??k1,t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=Number(o.value)}catch{}const u=o.value;if(typeof u=="number"&&!Number.isNaN(u)&&Number.isFinite(u))return o;const f=typeof u=="number"?Number.isNaN(u)?"NaN":Number.isFinite(u)?void 0:"Infinity":void 0;return o.issues.push({expected:"number",code:"invalid_type",input:u,inst:t,...f?{received:f}:{}}),o}}),C0=se("$ZodNumber",(t,r)=>{F1.init(t,r),sc.init(t,r)}),b0=se("$ZodBoolean",(t,r)=>{ct.init(t,r),t._zod.pattern=M1,t._zod.parse=(o,c)=>{if(r.coerce)try{o.value=!!o.value}catch{}const u=o.value;return typeof u=="boolean"||o.issues.push({expected:"boolean",code:"invalid_type",input:u,inst:t}),o}}),E0=se("$ZodNull",(t,r)=>{ct.init(t,r),t._zod.pattern=D1,t._zod.values=new Set([null]),t._zod.parse=(o,c)=>{const u=o.value;return u===null||o.issues.push({expected:"null",code:"invalid_type",input:u,inst:t}),o}}),A0=se("$ZodAny",(t,r)=>{ct.init(t,r),t._zod.parse=o=>o}),I0=se("$ZodUnknown",(t,r)=>{ct.init(t,r),t._zod.parse=o=>o}),S0=se("$ZodNever",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:t}),o)});function qs(t,r,o){t.issues.length&&r.issues.push(...ar(o,t.issues)),r.value[o]=t.value}const T0=se("$ZodArray",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!Array.isArray(u))return o.issues.push({expected:"array",code:"invalid_type",input:u,inst:t}),o;o.value=Array(u.length);const f=[];for(let m=0;m<u.length;m++){const x=u[m],_=r.element._zod.run({value:x,issues:[]},c);_ instanceof Promise?f.push(_.then(g=>qs(g,o,m))):qs(_,o,m)}return f.length?Promise.all(f).then(()=>o):o}});function _i(t,r,o){t.issues.length&&r.issues.push(...ar(o,t.issues)),r.value[o]=t.value}function Ys(t,r,o,c){t.issues.length?c[o]===void 0?o in c?r.value[o]=void 0:r.value[o]=t.value:r.issues.push(...ar(o,t.issues)):t.value===void 0?o in c&&(r.value[o]=void 0):r.value[o]=t.value}const N0=se("$ZodObject",(t,r)=>{ct.init(t,r);const o=$o(()=>{const A=Object.keys(r.shape);for(const O of A)if(!(r.shape[O]instanceof ct))throw new Error(`Invalid element at key "${O}": expected a Zod schema`);const P=qd(r.shape);return{shape:r.shape,keys:A,keySet:new Set(A),numKeys:A.length,optionalKeys:new Set(P)}});nt(t._zod,"propValues",()=>{const A=r.shape,P={};for(const O in A){const k=A[O]._zod;if(k.values){P[O]??(P[O]=new Set);for(const B of k.values)P[O].add(B)}}return P});const c=A=>{const P=new q1(["shape","payload","ctx"]),O=o.value,k=z=>{const $=Ur(z);return`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`};P.write("const input = payload.value;");const B=Object.create(null);let L=0;for(const z of O.keys)B[z]=`key_${L++}`;P.write("const newResult = {}");for(const z of O.keys)if(O.optionalKeys.has(z)){const $=B[z];P.write(`const ${$} = ${k(z)};`);const W=Ur(z);P.write(`
|
|
6
6
|
if (${$}.issues.length) {
|
|
7
|
-
if (input[${
|
|
8
|
-
if (${
|
|
9
|
-
newResult[${
|
|
7
|
+
if (input[${W}] === undefined) {
|
|
8
|
+
if (${W} in input) {
|
|
9
|
+
newResult[${W}] = undefined;
|
|
10
10
|
}
|
|
11
11
|
} else {
|
|
12
12
|
payload.issues = payload.issues.concat(
|
|
13
13
|
${$}.issues.map((iss) => ({
|
|
14
14
|
...iss,
|
|
15
|
-
path: iss.path ? [${
|
|
15
|
+
path: iss.path ? [${W}, ...iss.path] : [${W}],
|
|
16
16
|
}))
|
|
17
17
|
);
|
|
18
18
|
}
|
|
19
19
|
} else if (${$}.value === undefined) {
|
|
20
|
-
if (${
|
|
20
|
+
if (${W} in input) newResult[${W}] = undefined;
|
|
21
21
|
} else {
|
|
22
|
-
newResult[${
|
|
22
|
+
newResult[${W}] = ${$}.value;
|
|
23
23
|
}
|
|
24
|
-
`)}else{const $=
|
|
24
|
+
`)}else{const $=B[z];P.write(`const ${$} = ${k(z)};`),P.write(`
|
|
25
25
|
if (${$}.issues.length) payload.issues = payload.issues.concat(${$}.issues.map(iss => ({
|
|
26
26
|
...iss,
|
|
27
|
-
path: iss.path ? [${Ur(
|
|
28
|
-
})));`),B.write(`newResult[${Ur(Z)}] = ${$}.value`)}B.write("payload.value = newResult;"),B.write("return payload;");const Y=B.compile();return(Z,$)=>Y(A,Z,$)};let u;const f=Ri,p=!Wl.jitless,_=p&&Gd.value,g=r.catchall;let C;t._zod.parse=(A,B)=>{C??(C=o.value);const O=A.value;if(!f(O))return A.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),A;const k=[];if(p&&_&&B?.async===!1&&B.jitless!==!0)u||(u=c(r.shape)),A=u(A,B);else{A.value={};const $=C.shape;for(const H of C.keys){const re=$[H],j=re._zod.run({value:O[H],issues:[]},B),V=re._zod.optin==="optional"&&re._zod.optout==="optional";j instanceof Promise?k.push(j.then(z=>V?Ys(z,A,H,O):_i(z,A,H))):V?Ys(j,A,H,O):_i(j,A,H)}}if(!g)return k.length?Promise.all(k).then(()=>A):A;const P=[],L=C.keySet,Y=g._zod,Z=Y.def.type;for(const $ of Object.keys(O)){if(L.has($))continue;if(Z==="never"){P.push($);continue}const H=Y.run({value:O[$],issues:[]},B);H instanceof Promise?k.push(H.then(re=>_i(re,A,$))):_i(H,A,$)}return P.length&&A.issues.push({code:"unrecognized_keys",keys:P,input:O,inst:t}),k.length?Promise.all(k).then(()=>A):A}});function Js(t,r,o,c){for(const u of t)if(u.issues.length===0)return r.value=u.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:o,errors:t.map(u=>u.issues.map(f=>qn(f,c,Xn())))}),r}const ac=se("$ZodUnion",(t,r)=>{ct.init(t,r),nt(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),nt(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),nt(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),nt(t._zod,"pattern",()=>{if(r.options.every(o=>o._zod.pattern)){const o=r.options.map(c=>c._zod.pattern);return new RegExp(`^(${o.map(c=>Zo(c.source)).join("|")})$`)}}),t._zod.parse=(o,c)=>{let u=!1;const f=[];for(const p of r.options){const x=p._zod.run({value:o.value,issues:[]},c);if(x instanceof Promise)f.push(x),u=!0;else{if(x.issues.length===0)return x;f.push(x)}}return u?Promise.all(f).then(p=>Js(p,o,t,c)):Js(f,o,t,c)}}),O0=se("$ZodDiscriminatedUnion",(t,r)=>{ac.init(t,r);const o=t._zod.parse;nt(t._zod,"propValues",()=>{const u={};for(const f of r.options){const p=f._zod.propValues;if(!p||Object.keys(p).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(f)}"`);for(const[x,_]of Object.entries(p)){u[x]||(u[x]=new Set);for(const g of _)u[x].add(g)}}return u});const c=$o(()=>{const u=r.options,f=new Map;for(const p of u){const x=p._zod.propValues[r.discriminator];if(!x||x.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(p)}"`);for(const _ of x){if(f.has(_))throw new Error(`Duplicate discriminator value "${String(_)}"`);f.set(_,p)}}return f});t._zod.parse=(u,f)=>{const p=u.value;if(!Ri(p))return u.issues.push({code:"invalid_type",expected:"object",input:p,inst:t}),u;const x=c.value.get(p?.[r.discriminator]);return x?x._zod.run(u,f):r.unionFallback?o(u,f):(u.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:p,path:[r.discriminator],inst:t}),u)}}),R0=se("$ZodIntersection",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=o.value,f=r.left._zod.run({value:u,issues:[]},c),p=r.right._zod.run({value:u,issues:[]},c);return f instanceof Promise||p instanceof Promise?Promise.all([f,p]).then(([_,g])=>Ks(o,_,g)):Ks(o,f,p)}});function Io(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(ki(t)&&ki(r)){const o=Object.keys(r),c=Object.keys(t).filter(f=>o.indexOf(f)!==-1),u={...t,...r};for(const f of c){const p=Io(t[f],r[f]);if(!p.valid)return{valid:!1,mergeErrorPath:[f,...p.mergeErrorPath]};u[f]=p.data}return{valid:!0,data:u}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let c=0;c<t.length;c++){const u=t[c],f=r[c],p=Io(u,f);if(!p.valid)return{valid:!1,mergeErrorPath:[c,...p.mergeErrorPath]};o.push(p.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function Ks(t,r,o){if(r.issues.length&&t.issues.push(...r.issues),o.issues.length&&t.issues.push(...o.issues),Xr(t))return t;const c=Io(r.value,o.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const k0=se("$ZodRecord",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!ki(u))return o.issues.push({expected:"record",code:"invalid_type",input:u,inst:t}),o;const f=[];if(r.keyType._zod.values){const p=r.keyType._zod.values;o.value={};for(const _ of p)if(typeof _=="string"||typeof _=="number"||typeof _=="symbol"){const g=r.valueType._zod.run({value:u[_],issues:[]},c);g instanceof Promise?f.push(g.then(C=>{C.issues.length&&o.issues.push(...ar(_,C.issues)),o.value[_]=C.value})):(g.issues.length&&o.issues.push(...ar(_,g.issues)),o.value[_]=g.value)}let x;for(const _ in u)p.has(_)||(x=x??[],x.push(_));x&&x.length>0&&o.issues.push({code:"unrecognized_keys",input:u,inst:t,keys:x})}else{o.value={};for(const p of Reflect.ownKeys(u)){if(p==="__proto__")continue;const x=r.keyType._zod.run({value:p,issues:[]},c);if(x instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(x.issues.length){o.issues.push({origin:"record",code:"invalid_key",issues:x.issues.map(g=>qn(g,c,Xn())),input:p,path:[p],inst:t}),o.value[x.value]=x.value;continue}const _=r.valueType._zod.run({value:u[p],issues:[]},c);_ instanceof Promise?f.push(_.then(g=>{g.issues.length&&o.issues.push(...ar(p,g.issues)),o.value[x.value]=g.value})):(_.issues.length&&o.issues.push(...ar(p,_.issues)),o.value[x.value]=_.value)}}return f.length?Promise.all(f).then(()=>o):o}}),M0=se("$ZodEnum",(t,r)=>{ct.init(t,r);const o=Hl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Xd.has(typeof c)).map(c=>typeof c=="string"?ni(c):c.toString()).join("|")})$`),t._zod.parse=(c,u)=>{const f=c.value;return t._zod.values.has(f)||c.issues.push({code:"invalid_value",values:o,input:f,inst:t}),c}}),D0=se("$ZodLiteral",(t,r)=>{ct.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(o=>typeof o=="string"?ni(o):o?o.toString():String(o)).join("|")})$`),t._zod.parse=(o,c)=>{const u=o.value;return t._zod.values.has(u)||o.issues.push({code:"invalid_value",values:r.values,input:u,inst:t}),o}}),P0=se("$ZodTransform",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=r.transform(o.value,o);if(c.async)return(u instanceof Promise?u:Promise.resolve(u)).then(p=>(o.value=p,o));if(u instanceof Promise)throw new Yr;return o.value=u,o}}),B0=se("$ZodOptional",(t,r)=>{ct.init(t,r),t._zod.optin="optional",t._zod.optout="optional",nt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),nt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Zo(o.source)})?$`):void 0}),t._zod.parse=(o,c)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(o,c):o.value===void 0?o:r.innerType._zod.run(o,c)}),L0=se("$ZodNullable",(t,r)=>{ct.init(t,r),nt(t._zod,"optin",()=>r.innerType._zod.optin),nt(t._zod,"optout",()=>r.innerType._zod.optout),nt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Zo(o.source)}|null)$`):void 0}),nt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(o,c)=>o.value===null?o:r.innerType._zod.run(o,c)}),F0=se("$ZodDefault",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{if(o.value===void 0)return o.value=r.defaultValue,o;const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>Qs(f,r)):Qs(u,r)}});function Qs(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const U0=se("$ZodPrefault",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>(o.value===void 0&&(o.value=r.defaultValue),r.innerType._zod.run(o,c))}),z0=se("$ZodNonOptional",(t,r)=>{ct.init(t,r),nt(t._zod,"values",()=>{const o=r.innerType._zod.values;return o?new Set([...o].filter(c=>c!==void 0)):void 0}),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>ea(f,t)):ea(u,t)}});function ea(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}const $0=se("$ZodCatch",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"optout",()=>r.innerType._zod.optout),nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>(o.value=f.value,f.issues.length&&(o.value=r.catchValue({...o,error:{issues:f.issues.map(p=>qn(p,c,Xn()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>qn(f,c,Xn()))},input:o.value}),o.issues=[]),o)}}),V0=se("$ZodPipe",(t,r)=>{ct.init(t,r),nt(t._zod,"values",()=>r.in._zod.values),nt(t._zod,"optin",()=>r.in._zod.optin),nt(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(o,c)=>{const u=r.in._zod.run(o,c);return u instanceof Promise?u.then(f=>ta(f,r,c)):ta(u,r,c)}});function ta(t,r,o){return Xr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const Z0=se("$ZodReadonly",(t,r)=>{ct.init(t,r),nt(t._zod,"propValues",()=>r.innerType._zod.propValues),nt(t._zod,"values",()=>r.innerType._zod.values),nt(t._zod,"optin",()=>r.innerType._zod.optin),nt(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(na):na(u)}});function na(t){return t.value=Object.freeze(t.value),t}const j0=se("$ZodLazy",(t,r)=>{ct.init(t,r),nt(t._zod,"innerType",()=>r.getter()),nt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),nt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),nt(t._zod,"optin",()=>t._zod.innerType._zod.optin),nt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),W0=se("$ZodCustom",(t,r)=>{tn.init(t,r),ct.init(t,r),t._zod.parse=(o,c)=>o,t._zod.check=o=>{const c=o.value,u=r.fn(c);if(u instanceof Promise)return u.then(f=>ra(f,o,c,t));ra(u,o,c,t)}});function ra(t,r,o,c){if(!t){const u={code:"custom",input:o,inst:c,path:[...c._zod.def.path??[]],continue:!c._zod.def.abort};c._zod.def.params&&(u.params=c._zod.def.params),r.issues.push(Jr(u))}}class lc{constructor(){this._map=new Map,this._idmap=new Map}add(r,...o){const c=o[0];if(this._map.set(r,c),c&&typeof c=="object"&&"id"in c){if(this._idmap.has(c.id))throw new Error(`ID ${c.id} already exists in the registry`);this._idmap.set(c.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){const o=this._map.get(r);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(r),this}get(r){const o=r._zod.parent;if(o){const c={...this.get(o)??{}};return delete c.id,{...c,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}}function H0(){return new lc}const jr=H0();function G0(t,r){return new t({type:"string",...be(r)})}function X0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...be(r)})}function ia(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...be(r)})}function q0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...be(r)})}function Y0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...be(r)})}function J0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...be(r)})}function K0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...be(r)})}function Q0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...be(r)})}function ef(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...be(r)})}function tf(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...be(r)})}function nf(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...be(r)})}function rf(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...be(r)})}function of(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...be(r)})}function sf(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...be(r)})}function af(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...be(r)})}function lf(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...be(r)})}function cf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...be(r)})}function uf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...be(r)})}function df(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...be(r)})}function ff(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...be(r)})}function hf(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...be(r)})}function pf(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...be(r)})}function mf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...be(r)})}function gf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...be(r)})}function xf(t,r){return new t({type:"string",format:"date",check:"string_format",...be(r)})}function yf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...be(r)})}function wf(t,r){return new t({type:"string",format:"duration",check:"string_format",...be(r)})}function _f(t,r){return new t({type:"number",checks:[],...be(r)})}function vf(t,r){return new t({type:"number",coerce:!0,checks:[],...be(r)})}function Cf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...be(r)})}function bf(t,r){return new t({type:"boolean",...be(r)})}function Ef(t,r){return new t({type:"null",...be(r)})}function Af(t){return new t({type:"any"})}function If(t){return new t({type:"unknown"})}function Sf(t,r){return new t({type:"never",...be(r)})}function oa(t,r){return new rc({check:"less_than",...be(r),value:t,inclusive:!1})}function ho(t,r){return new rc({check:"less_than",...be(r),value:t,inclusive:!0})}function sa(t,r){return new ic({check:"greater_than",...be(r),value:t,inclusive:!1})}function po(t,r){return new ic({check:"greater_than",...be(r),value:t,inclusive:!0})}function aa(t,r){return new L1({check:"multiple_of",...be(r),value:t})}function cc(t,r){return new U1({check:"max_length",...be(r),maximum:t})}function Mi(t,r){return new z1({check:"min_length",...be(r),minimum:t})}function uc(t,r){return new $1({check:"length_equals",...be(r),length:t})}function Tf(t,r){return new V1({check:"string_format",format:"regex",...be(r),pattern:t})}function Nf(t){return new Z1({check:"string_format",format:"lowercase",...be(t)})}function Of(t){return new j1({check:"string_format",format:"uppercase",...be(t)})}function Rf(t,r){return new W1({check:"string_format",format:"includes",...be(r),includes:t})}function kf(t,r){return new H1({check:"string_format",format:"starts_with",...be(r),prefix:t})}function Mf(t,r){return new G1({check:"string_format",format:"ends_with",...be(r),suffix:t})}function ri(t){return new X1({check:"overwrite",tx:t})}function Df(t){return ri(r=>r.normalize(t))}function Pf(){return ri(t=>t.trim())}function Bf(){return ri(t=>t.toLowerCase())}function Lf(){return ri(t=>t.toUpperCase())}function Ff(t,r,o){return new t({type:"array",element:r,...be(o)})}function Uf(t,r,o){const c=be(o);return c.abort??(c.abort=!0),new t({type:"custom",check:"custom",fn:r,...c})}function zf(t,r,o){return new t({type:"custom",check:"custom",fn:r,...be(o)})}class la{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??jr,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,o={path:[],schemaPath:[]}){var c;const u=r._zod.def,f={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},p=this.seen.get(r);if(p)return p.count++,o.schemaPath.includes(r)&&(p.cycle=o.path),p.schema;const x={schema:{},count:1,cycle:void 0,path:o.path};this.seen.set(r,x);const _=r._zod.toJSONSchema?.();if(_)x.schema=_;else{const A={...o,schemaPath:[...o.schemaPath,r],path:o.path},B=r._zod.parent;if(B)x.ref=B,this.process(B,A),this.seen.get(B).isParent=!0;else{const O=x.schema;switch(u.type){case"string":{const k=O;k.type="string";const{minimum:P,maximum:L,format:Y,patterns:Z,contentEncoding:$}=r._zod.bag;if(typeof P=="number"&&(k.minLength=P),typeof L=="number"&&(k.maxLength=L),Y&&(k.format=f[Y]??Y,k.format===""&&delete k.format),$&&(k.contentEncoding=$),Z&&Z.size>0){const H=[...Z];H.length===1?k.pattern=H[0].source:H.length>1&&(x.schema.allOf=[...H.map(re=>({...this.target==="draft-7"?{type:"string"}:{},pattern:re.source}))])}break}case"number":{const k=O,{minimum:P,maximum:L,format:Y,multipleOf:Z,exclusiveMaximum:$,exclusiveMinimum:H}=r._zod.bag;typeof Y=="string"&&Y.includes("int")?k.type="integer":k.type="number",typeof H=="number"&&(k.exclusiveMinimum=H),typeof P=="number"&&(k.minimum=P,typeof H=="number"&&(H>=P?delete k.minimum:delete k.exclusiveMinimum)),typeof $=="number"&&(k.exclusiveMaximum=$),typeof L=="number"&&(k.maximum=L,typeof $=="number"&&($<=L?delete k.maximum:delete k.exclusiveMaximum)),typeof Z=="number"&&(k.multipleOf=Z);break}case"boolean":{const k=O;k.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{O.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{O.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const k=O,{minimum:P,maximum:L}=r._zod.bag;typeof P=="number"&&(k.minItems=P),typeof L=="number"&&(k.maxItems=L),k.type="array",k.items=this.process(u.element,{...A,path:[...A.path,"items"]});break}case"object":{const k=O;k.type="object",k.properties={};const P=u.shape;for(const Z in P)k.properties[Z]=this.process(P[Z],{...A,path:[...A.path,"properties",Z]});const L=new Set(Object.keys(P)),Y=new Set([...L].filter(Z=>{const $=u.shape[Z]._zod;return this.io==="input"?$.optin===void 0:$.optout===void 0}));Y.size>0&&(k.required=Array.from(Y)),u.catchall?._zod.def.type==="never"?k.additionalProperties=!1:u.catchall?u.catchall&&(k.additionalProperties=this.process(u.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(k.additionalProperties=!1);break}case"union":{const k=O;k.anyOf=u.options.map((P,L)=>this.process(P,{...A,path:[...A.path,"anyOf",L]}));break}case"intersection":{const k=O,P=this.process(u.left,{...A,path:[...A.path,"allOf",0]}),L=this.process(u.right,{...A,path:[...A.path,"allOf",1]}),Y=$=>"allOf"in $&&Object.keys($).length===1,Z=[...Y(P)?P.allOf:[P],...Y(L)?L.allOf:[L]];k.allOf=Z;break}case"tuple":{const k=O;k.type="array";const P=u.items.map((Z,$)=>this.process(Z,{...A,path:[...A.path,"prefixItems",$]}));if(this.target==="draft-2020-12"?k.prefixItems=P:k.items=P,u.rest){const Z=this.process(u.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?k.items=Z:k.additionalItems=Z}u.rest&&(k.items=this.process(u.rest,{...A,path:[...A.path,"items"]}));const{minimum:L,maximum:Y}=r._zod.bag;typeof L=="number"&&(k.minItems=L),typeof Y=="number"&&(k.maxItems=Y);break}case"record":{const k=O;k.type="object",k.propertyNames=this.process(u.keyType,{...A,path:[...A.path,"propertyNames"]}),k.additionalProperties=this.process(u.valueType,{...A,path:[...A.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const k=O,P=Hl(u.entries);P.every(L=>typeof L=="number")&&(k.type="number"),P.every(L=>typeof L=="string")&&(k.type="string"),k.enum=P;break}case"literal":{const k=O,P=[];for(const L of u.values)if(L===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof L=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");P.push(Number(L))}else P.push(L);if(P.length!==0)if(P.length===1){const L=P[0];k.type=L===null?"null":typeof L,k.const=L}else P.every(L=>typeof L=="number")&&(k.type="number"),P.every(L=>typeof L=="string")&&(k.type="string"),P.every(L=>typeof L=="boolean")&&(k.type="string"),P.every(L=>L===null)&&(k.type="null"),k.enum=P;break}case"file":{const k=O,P={type:"string",format:"binary",contentEncoding:"binary"},{minimum:L,maximum:Y,mime:Z}=r._zod.bag;L!==void 0&&(P.minLength=L),Y!==void 0&&(P.maxLength=Y),Z?Z.length===1?(P.contentMediaType=Z[0],Object.assign(k,P)):k.anyOf=Z.map($=>({...P,contentMediaType:$})):Object.assign(k,P);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const k=this.process(u.innerType,A);O.anyOf=[k,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,A),x.ref=u.innerType;break}case"success":{const k=O;k.type="boolean";break}case"default":{this.process(u.innerType,A),x.ref=u.innerType,O.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,A),x.ref=u.innerType,this.io==="input"&&(O._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,A),x.ref=u.innerType;let k;try{k=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}O.default=k;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const k=O,P=r._zod.pattern;if(!P)throw new Error("Pattern not found in template literal");k.type="string",k.pattern=P.source;break}case"pipe":{const k=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(k,A),x.ref=k;break}case"readonly":{this.process(u.innerType,A),x.ref=u.innerType,O.readOnly=!0;break}case"promise":{this.process(u.innerType,A),x.ref=u.innerType;break}case"optional":{this.process(u.innerType,A),x.ref=u.innerType;break}case"lazy":{const k=r._zod.innerType;this.process(k,A),x.ref=k;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const g=this.metadataRegistry.get(r);return g&&Object.assign(x.schema,g),this.io==="input"&&kt(r)&&(delete x.schema.examples,delete x.schema.default),this.io==="input"&&x.schema._prefault&&((c=x.schema).default??(c.default=x.schema._prefault)),delete x.schema._prefault,this.seen.get(r).schema}emit(r,o){const c={cycles:o?.cycles??"ref",reused:o?.reused??"inline",external:o?.external??void 0},u=this.seen.get(r);if(!u)throw new Error("Unprocessed schema. This is a bug in Zod.");const f=C=>{const A=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const P=c.external.registry.get(C[0])?.id,L=c.external.uri??(Z=>Z);if(P)return{ref:L(P)};const Y=C[1].defId??C[1].schema.id??`schema${this.counter++}`;return C[1].defId=Y,{defId:Y,ref:`${L("__shared")}#/${A}/${Y}`}}if(C[1]===u)return{ref:"#"};const O=`#/${A}/`,k=C[1].schema.id??`__schema${this.counter++}`;return{defId:k,ref:O+k}},p=C=>{if(C[1].schema.$ref)return;const A=C[1],{ref:B,defId:O}=f(C);A.def={...A.schema},O&&(A.defId=O);const k=A.schema;for(const P in k)delete k[P];k.$ref=B};if(c.cycles==="throw")for(const C of this.seen.entries()){const A=C[1];if(A.cycle)throw new Error(`Cycle detected: #/${A.cycle?.join("/")}/<root>
|
|
27
|
+
path: iss.path ? [${Ur(z)}, ...iss.path] : [${Ur(z)}]
|
|
28
|
+
})));`),P.write(`newResult[${Ur(z)}] = ${$}.value`)}P.write("payload.value = newResult;"),P.write("return payload;");const K=P.compile();return(z,$)=>K(A,z,$)};let u;const f=Ri,m=!Wl.jitless,_=m&&Gd.value,g=r.catchall;let C;t._zod.parse=(A,P)=>{C??(C=o.value);const O=A.value;if(!f(O))return A.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),A;const k=[];if(m&&_&&P?.async===!1&&P.jitless!==!0)u||(u=c(r.shape)),A=u(A,P);else{A.value={};const $=C.shape;for(const W of C.keys){const X=$[W],H=X._zod.run({value:O[W],issues:[]},P),V=X._zod.optin==="optional"&&X._zod.optout==="optional";H instanceof Promise?k.push(H.then(Z=>V?Ys(Z,A,W,O):_i(Z,A,W))):V?Ys(H,A,W,O):_i(H,A,W)}}if(!g)return k.length?Promise.all(k).then(()=>A):A;const B=[],L=C.keySet,K=g._zod,z=K.def.type;for(const $ of Object.keys(O)){if(L.has($))continue;if(z==="never"){B.push($);continue}const W=K.run({value:O[$],issues:[]},P);W instanceof Promise?k.push(W.then(X=>_i(X,A,$))):_i(W,A,$)}return B.length&&A.issues.push({code:"unrecognized_keys",keys:B,input:O,inst:t}),k.length?Promise.all(k).then(()=>A):A}});function Js(t,r,o,c){for(const u of t)if(u.issues.length===0)return r.value=u.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:o,errors:t.map(u=>u.issues.map(f=>qn(f,c,Xn())))}),r}const ac=se("$ZodUnion",(t,r)=>{ct.init(t,r),nt(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),nt(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),nt(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),nt(t._zod,"pattern",()=>{if(r.options.every(o=>o._zod.pattern)){const o=r.options.map(c=>c._zod.pattern);return new RegExp(`^(${o.map(c=>Zo(c.source)).join("|")})$`)}}),t._zod.parse=(o,c)=>{let u=!1;const f=[];for(const m of r.options){const x=m._zod.run({value:o.value,issues:[]},c);if(x instanceof Promise)f.push(x),u=!0;else{if(x.issues.length===0)return x;f.push(x)}}return u?Promise.all(f).then(m=>Js(m,o,t,c)):Js(f,o,t,c)}}),O0=se("$ZodDiscriminatedUnion",(t,r)=>{ac.init(t,r);const o=t._zod.parse;nt(t._zod,"propValues",()=>{const u={};for(const f of r.options){const m=f._zod.propValues;if(!m||Object.keys(m).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(f)}"`);for(const[x,_]of Object.entries(m)){u[x]||(u[x]=new Set);for(const g of _)u[x].add(g)}}return u});const c=$o(()=>{const u=r.options,f=new Map;for(const m of u){const x=m._zod.propValues[r.discriminator];if(!x||x.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(m)}"`);for(const _ of x){if(f.has(_))throw new Error(`Duplicate discriminator value "${String(_)}"`);f.set(_,m)}}return f});t._zod.parse=(u,f)=>{const m=u.value;if(!Ri(m))return u.issues.push({code:"invalid_type",expected:"object",input:m,inst:t}),u;const x=c.value.get(m?.[r.discriminator]);return x?x._zod.run(u,f):r.unionFallback?o(u,f):(u.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:m,path:[r.discriminator],inst:t}),u)}}),R0=se("$ZodIntersection",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=o.value,f=r.left._zod.run({value:u,issues:[]},c),m=r.right._zod.run({value:u,issues:[]},c);return f instanceof Promise||m instanceof Promise?Promise.all([f,m]).then(([_,g])=>Ks(o,_,g)):Ks(o,f,m)}});function Io(t,r){if(t===r)return{valid:!0,data:t};if(t instanceof Date&&r instanceof Date&&+t==+r)return{valid:!0,data:t};if(ki(t)&&ki(r)){const o=Object.keys(r),c=Object.keys(t).filter(f=>o.indexOf(f)!==-1),u={...t,...r};for(const f of c){const m=Io(t[f],r[f]);if(!m.valid)return{valid:!1,mergeErrorPath:[f,...m.mergeErrorPath]};u[f]=m.data}return{valid:!0,data:u}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};const o=[];for(let c=0;c<t.length;c++){const u=t[c],f=r[c],m=Io(u,f);if(!m.valid)return{valid:!1,mergeErrorPath:[c,...m.mergeErrorPath]};o.push(m.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function Ks(t,r,o){if(r.issues.length&&t.issues.push(...r.issues),o.issues.length&&t.issues.push(...o.issues),Xr(t))return t;const c=Io(r.value,o.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const k0=se("$ZodRecord",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!ki(u))return o.issues.push({expected:"record",code:"invalid_type",input:u,inst:t}),o;const f=[];if(r.keyType._zod.values){const m=r.keyType._zod.values;o.value={};for(const _ of m)if(typeof _=="string"||typeof _=="number"||typeof _=="symbol"){const g=r.valueType._zod.run({value:u[_],issues:[]},c);g instanceof Promise?f.push(g.then(C=>{C.issues.length&&o.issues.push(...ar(_,C.issues)),o.value[_]=C.value})):(g.issues.length&&o.issues.push(...ar(_,g.issues)),o.value[_]=g.value)}let x;for(const _ in u)m.has(_)||(x=x??[],x.push(_));x&&x.length>0&&o.issues.push({code:"unrecognized_keys",input:u,inst:t,keys:x})}else{o.value={};for(const m of Reflect.ownKeys(u)){if(m==="__proto__")continue;const x=r.keyType._zod.run({value:m,issues:[]},c);if(x instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(x.issues.length){o.issues.push({origin:"record",code:"invalid_key",issues:x.issues.map(g=>qn(g,c,Xn())),input:m,path:[m],inst:t}),o.value[x.value]=x.value;continue}const _=r.valueType._zod.run({value:u[m],issues:[]},c);_ instanceof Promise?f.push(_.then(g=>{g.issues.length&&o.issues.push(...ar(m,g.issues)),o.value[x.value]=g.value})):(_.issues.length&&o.issues.push(...ar(m,_.issues)),o.value[x.value]=_.value)}}return f.length?Promise.all(f).then(()=>o):o}}),M0=se("$ZodEnum",(t,r)=>{ct.init(t,r);const o=Hl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Xd.has(typeof c)).map(c=>typeof c=="string"?ni(c):c.toString()).join("|")})$`),t._zod.parse=(c,u)=>{const f=c.value;return t._zod.values.has(f)||c.issues.push({code:"invalid_value",values:o,input:f,inst:t}),c}}),D0=se("$ZodLiteral",(t,r)=>{ct.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(o=>typeof o=="string"?ni(o):o?o.toString():String(o)).join("|")})$`),t._zod.parse=(o,c)=>{const u=o.value;return t._zod.values.has(u)||o.issues.push({code:"invalid_value",values:r.values,input:u,inst:t}),o}}),P0=se("$ZodTransform",(t,r)=>{ct.init(t,r),t._zod.parse=(o,c)=>{const u=r.transform(o.value,o);if(c.async)return(u instanceof Promise?u:Promise.resolve(u)).then(m=>(o.value=m,o));if(u instanceof Promise)throw new Yr;return o.value=u,o}}),B0=se("$ZodOptional",(t,r)=>{ct.init(t,r),t._zod.optin="optional",t._zod.optout="optional",nt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),nt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Zo(o.source)})?$`):void 0}),t._zod.parse=(o,c)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(o,c):o.value===void 0?o:r.innerType._zod.run(o,c)}),L0=se("$ZodNullable",(t,r)=>{ct.init(t,r),nt(t._zod,"optin",()=>r.innerType._zod.optin),nt(t._zod,"optout",()=>r.innerType._zod.optout),nt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Zo(o.source)}|null)$`):void 0}),nt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(o,c)=>o.value===null?o:r.innerType._zod.run(o,c)}),F0=se("$ZodDefault",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{if(o.value===void 0)return o.value=r.defaultValue,o;const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>Qs(f,r)):Qs(u,r)}});function Qs(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const U0=se("$ZodPrefault",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>(o.value===void 0&&(o.value=r.defaultValue),r.innerType._zod.run(o,c))}),z0=se("$ZodNonOptional",(t,r)=>{ct.init(t,r),nt(t._zod,"values",()=>{const o=r.innerType._zod.values;return o?new Set([...o].filter(c=>c!==void 0)):void 0}),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>ea(f,t)):ea(u,t)}});function ea(t,r){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:r}),t}const $0=se("$ZodCatch",(t,r)=>{ct.init(t,r),t._zod.optin="optional",nt(t._zod,"optout",()=>r.innerType._zod.optout),nt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(f=>(o.value=f.value,f.issues.length&&(o.value=r.catchValue({...o,error:{issues:f.issues.map(m=>qn(m,c,Xn()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>qn(f,c,Xn()))},input:o.value}),o.issues=[]),o)}}),V0=se("$ZodPipe",(t,r)=>{ct.init(t,r),nt(t._zod,"values",()=>r.in._zod.values),nt(t._zod,"optin",()=>r.in._zod.optin),nt(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(o,c)=>{const u=r.in._zod.run(o,c);return u instanceof Promise?u.then(f=>ta(f,r,c)):ta(u,r,c)}});function ta(t,r,o){return Xr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const Z0=se("$ZodReadonly",(t,r)=>{ct.init(t,r),nt(t._zod,"propValues",()=>r.innerType._zod.propValues),nt(t._zod,"values",()=>r.innerType._zod.values),nt(t._zod,"optin",()=>r.innerType._zod.optin),nt(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(o,c)=>{const u=r.innerType._zod.run(o,c);return u instanceof Promise?u.then(na):na(u)}});function na(t){return t.value=Object.freeze(t.value),t}const j0=se("$ZodLazy",(t,r)=>{ct.init(t,r),nt(t._zod,"innerType",()=>r.getter()),nt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),nt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),nt(t._zod,"optin",()=>t._zod.innerType._zod.optin),nt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),W0=se("$ZodCustom",(t,r)=>{tn.init(t,r),ct.init(t,r),t._zod.parse=(o,c)=>o,t._zod.check=o=>{const c=o.value,u=r.fn(c);if(u instanceof Promise)return u.then(f=>ra(f,o,c,t));ra(u,o,c,t)}});function ra(t,r,o,c){if(!t){const u={code:"custom",input:o,inst:c,path:[...c._zod.def.path??[]],continue:!c._zod.def.abort};c._zod.def.params&&(u.params=c._zod.def.params),r.issues.push(Jr(u))}}class lc{constructor(){this._map=new Map,this._idmap=new Map}add(r,...o){const c=o[0];if(this._map.set(r,c),c&&typeof c=="object"&&"id"in c){if(this._idmap.has(c.id))throw new Error(`ID ${c.id} already exists in the registry`);this._idmap.set(c.id,r)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(r){const o=this._map.get(r);return o&&typeof o=="object"&&"id"in o&&this._idmap.delete(o.id),this._map.delete(r),this}get(r){const o=r._zod.parent;if(o){const c={...this.get(o)??{}};return delete c.id,{...c,...this._map.get(r)}}return this._map.get(r)}has(r){return this._map.has(r)}}function H0(){return new lc}const jr=H0();function G0(t,r){return new t({type:"string",...be(r)})}function X0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...be(r)})}function ia(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...be(r)})}function q0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...be(r)})}function Y0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...be(r)})}function J0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...be(r)})}function K0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...be(r)})}function Q0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...be(r)})}function ef(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...be(r)})}function tf(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...be(r)})}function nf(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...be(r)})}function rf(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...be(r)})}function of(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...be(r)})}function sf(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...be(r)})}function af(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...be(r)})}function lf(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...be(r)})}function cf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...be(r)})}function uf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...be(r)})}function df(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...be(r)})}function ff(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...be(r)})}function hf(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...be(r)})}function pf(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...be(r)})}function mf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...be(r)})}function gf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...be(r)})}function xf(t,r){return new t({type:"string",format:"date",check:"string_format",...be(r)})}function yf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...be(r)})}function wf(t,r){return new t({type:"string",format:"duration",check:"string_format",...be(r)})}function _f(t,r){return new t({type:"number",checks:[],...be(r)})}function vf(t,r){return new t({type:"number",coerce:!0,checks:[],...be(r)})}function Cf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...be(r)})}function bf(t,r){return new t({type:"boolean",...be(r)})}function Ef(t,r){return new t({type:"null",...be(r)})}function Af(t){return new t({type:"any"})}function If(t){return new t({type:"unknown"})}function Sf(t,r){return new t({type:"never",...be(r)})}function oa(t,r){return new rc({check:"less_than",...be(r),value:t,inclusive:!1})}function ho(t,r){return new rc({check:"less_than",...be(r),value:t,inclusive:!0})}function sa(t,r){return new ic({check:"greater_than",...be(r),value:t,inclusive:!1})}function po(t,r){return new ic({check:"greater_than",...be(r),value:t,inclusive:!0})}function aa(t,r){return new L1({check:"multiple_of",...be(r),value:t})}function cc(t,r){return new U1({check:"max_length",...be(r),maximum:t})}function Mi(t,r){return new z1({check:"min_length",...be(r),minimum:t})}function uc(t,r){return new $1({check:"length_equals",...be(r),length:t})}function Tf(t,r){return new V1({check:"string_format",format:"regex",...be(r),pattern:t})}function Nf(t){return new Z1({check:"string_format",format:"lowercase",...be(t)})}function Of(t){return new j1({check:"string_format",format:"uppercase",...be(t)})}function Rf(t,r){return new W1({check:"string_format",format:"includes",...be(r),includes:t})}function kf(t,r){return new H1({check:"string_format",format:"starts_with",...be(r),prefix:t})}function Mf(t,r){return new G1({check:"string_format",format:"ends_with",...be(r),suffix:t})}function ri(t){return new X1({check:"overwrite",tx:t})}function Df(t){return ri(r=>r.normalize(t))}function Pf(){return ri(t=>t.trim())}function Bf(){return ri(t=>t.toLowerCase())}function Lf(){return ri(t=>t.toUpperCase())}function Ff(t,r,o){return new t({type:"array",element:r,...be(o)})}function Uf(t,r,o){const c=be(o);return c.abort??(c.abort=!0),new t({type:"custom",check:"custom",fn:r,...c})}function zf(t,r,o){return new t({type:"custom",check:"custom",fn:r,...be(o)})}class la{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??jr,this.target=r?.target??"draft-2020-12",this.unrepresentable=r?.unrepresentable??"throw",this.override=r?.override??(()=>{}),this.io=r?.io??"output",this.seen=new Map}process(r,o={path:[],schemaPath:[]}){var c;const u=r._zod.def,f={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},m=this.seen.get(r);if(m)return m.count++,o.schemaPath.includes(r)&&(m.cycle=o.path),m.schema;const x={schema:{},count:1,cycle:void 0,path:o.path};this.seen.set(r,x);const _=r._zod.toJSONSchema?.();if(_)x.schema=_;else{const A={...o,schemaPath:[...o.schemaPath,r],path:o.path},P=r._zod.parent;if(P)x.ref=P,this.process(P,A),this.seen.get(P).isParent=!0;else{const O=x.schema;switch(u.type){case"string":{const k=O;k.type="string";const{minimum:B,maximum:L,format:K,patterns:z,contentEncoding:$}=r._zod.bag;if(typeof B=="number"&&(k.minLength=B),typeof L=="number"&&(k.maxLength=L),K&&(k.format=f[K]??K,k.format===""&&delete k.format),$&&(k.contentEncoding=$),z&&z.size>0){const W=[...z];W.length===1?k.pattern=W[0].source:W.length>1&&(x.schema.allOf=[...W.map(X=>({...this.target==="draft-7"?{type:"string"}:{},pattern:X.source}))])}break}case"number":{const k=O,{minimum:B,maximum:L,format:K,multipleOf:z,exclusiveMaximum:$,exclusiveMinimum:W}=r._zod.bag;typeof K=="string"&&K.includes("int")?k.type="integer":k.type="number",typeof W=="number"&&(k.exclusiveMinimum=W),typeof B=="number"&&(k.minimum=B,typeof W=="number"&&(W>=B?delete k.minimum:delete k.exclusiveMinimum)),typeof $=="number"&&(k.exclusiveMaximum=$),typeof L=="number"&&(k.maximum=L,typeof $=="number"&&($<=L?delete k.maximum:delete k.exclusiveMaximum)),typeof z=="number"&&(k.multipleOf=z);break}case"boolean":{const k=O;k.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{O.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{O.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const k=O,{minimum:B,maximum:L}=r._zod.bag;typeof B=="number"&&(k.minItems=B),typeof L=="number"&&(k.maxItems=L),k.type="array",k.items=this.process(u.element,{...A,path:[...A.path,"items"]});break}case"object":{const k=O;k.type="object",k.properties={};const B=u.shape;for(const z in B)k.properties[z]=this.process(B[z],{...A,path:[...A.path,"properties",z]});const L=new Set(Object.keys(B)),K=new Set([...L].filter(z=>{const $=u.shape[z]._zod;return this.io==="input"?$.optin===void 0:$.optout===void 0}));K.size>0&&(k.required=Array.from(K)),u.catchall?._zod.def.type==="never"?k.additionalProperties=!1:u.catchall?u.catchall&&(k.additionalProperties=this.process(u.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(k.additionalProperties=!1);break}case"union":{const k=O;k.anyOf=u.options.map((B,L)=>this.process(B,{...A,path:[...A.path,"anyOf",L]}));break}case"intersection":{const k=O,B=this.process(u.left,{...A,path:[...A.path,"allOf",0]}),L=this.process(u.right,{...A,path:[...A.path,"allOf",1]}),K=$=>"allOf"in $&&Object.keys($).length===1,z=[...K(B)?B.allOf:[B],...K(L)?L.allOf:[L]];k.allOf=z;break}case"tuple":{const k=O;k.type="array";const B=u.items.map((z,$)=>this.process(z,{...A,path:[...A.path,"prefixItems",$]}));if(this.target==="draft-2020-12"?k.prefixItems=B:k.items=B,u.rest){const z=this.process(u.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?k.items=z:k.additionalItems=z}u.rest&&(k.items=this.process(u.rest,{...A,path:[...A.path,"items"]}));const{minimum:L,maximum:K}=r._zod.bag;typeof L=="number"&&(k.minItems=L),typeof K=="number"&&(k.maxItems=K);break}case"record":{const k=O;k.type="object",k.propertyNames=this.process(u.keyType,{...A,path:[...A.path,"propertyNames"]}),k.additionalProperties=this.process(u.valueType,{...A,path:[...A.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const k=O,B=Hl(u.entries);B.every(L=>typeof L=="number")&&(k.type="number"),B.every(L=>typeof L=="string")&&(k.type="string"),k.enum=B;break}case"literal":{const k=O,B=[];for(const L of u.values)if(L===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof L=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");B.push(Number(L))}else B.push(L);if(B.length!==0)if(B.length===1){const L=B[0];k.type=L===null?"null":typeof L,k.const=L}else B.every(L=>typeof L=="number")&&(k.type="number"),B.every(L=>typeof L=="string")&&(k.type="string"),B.every(L=>typeof L=="boolean")&&(k.type="string"),B.every(L=>L===null)&&(k.type="null"),k.enum=B;break}case"file":{const k=O,B={type:"string",format:"binary",contentEncoding:"binary"},{minimum:L,maximum:K,mime:z}=r._zod.bag;L!==void 0&&(B.minLength=L),K!==void 0&&(B.maxLength=K),z?z.length===1?(B.contentMediaType=z[0],Object.assign(k,B)):k.anyOf=z.map($=>({...B,contentMediaType:$})):Object.assign(k,B);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const k=this.process(u.innerType,A);O.anyOf=[k,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,A),x.ref=u.innerType;break}case"success":{const k=O;k.type="boolean";break}case"default":{this.process(u.innerType,A),x.ref=u.innerType,O.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,A),x.ref=u.innerType,this.io==="input"&&(O._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,A),x.ref=u.innerType;let k;try{k=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}O.default=k;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const k=O,B=r._zod.pattern;if(!B)throw new Error("Pattern not found in template literal");k.type="string",k.pattern=B.source;break}case"pipe":{const k=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(k,A),x.ref=k;break}case"readonly":{this.process(u.innerType,A),x.ref=u.innerType,O.readOnly=!0;break}case"promise":{this.process(u.innerType,A),x.ref=u.innerType;break}case"optional":{this.process(u.innerType,A),x.ref=u.innerType;break}case"lazy":{const k=r._zod.innerType;this.process(k,A),x.ref=k;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const g=this.metadataRegistry.get(r);return g&&Object.assign(x.schema,g),this.io==="input"&&kt(r)&&(delete x.schema.examples,delete x.schema.default),this.io==="input"&&x.schema._prefault&&((c=x.schema).default??(c.default=x.schema._prefault)),delete x.schema._prefault,this.seen.get(r).schema}emit(r,o){const c={cycles:o?.cycles??"ref",reused:o?.reused??"inline",external:o?.external??void 0},u=this.seen.get(r);if(!u)throw new Error("Unprocessed schema. This is a bug in Zod.");const f=C=>{const A=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const B=c.external.registry.get(C[0])?.id,L=c.external.uri??(z=>z);if(B)return{ref:L(B)};const K=C[1].defId??C[1].schema.id??`schema${this.counter++}`;return C[1].defId=K,{defId:K,ref:`${L("__shared")}#/${A}/${K}`}}if(C[1]===u)return{ref:"#"};const O=`#/${A}/`,k=C[1].schema.id??`__schema${this.counter++}`;return{defId:k,ref:O+k}},m=C=>{if(C[1].schema.$ref)return;const A=C[1],{ref:P,defId:O}=f(C);A.def={...A.schema},O&&(A.defId=O);const k=A.schema;for(const B in k)delete k[B];k.$ref=P};if(c.cycles==="throw")for(const C of this.seen.entries()){const A=C[1];if(A.cycle)throw new Error(`Cycle detected: #/${A.cycle?.join("/")}/<root>
|
|
29
29
|
|
|
30
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const C of this.seen.entries()){const A=C[1];if(r===C[0]){p(C);continue}if(c.external){const O=c.external.registry.get(C[0])?.id;if(r!==C[0]&&O){p(C);continue}}if(this.metadataRegistry.get(C[0])?.id){p(C);continue}if(A.cycle){p(C);continue}if(A.count>1&&c.reused==="ref"){p(C);continue}}const x=(C,A)=>{const B=this.seen.get(C),O=B.def??B.schema,k={...O};if(B.ref===null)return;const P=B.ref;if(B.ref=null,P){x(P,A);const L=this.seen.get(P).schema;L.$ref&&A.target==="draft-7"?(O.allOf=O.allOf??[],O.allOf.push(L)):(Object.assign(O,L),Object.assign(O,k))}B.isParent||this.override({zodSchema:C,jsonSchema:O,path:B.path??[]})};for(const C of[...this.seen.entries()].reverse())x(C[0],{target:this.target});const _={};if(this.target==="draft-2020-12"?_.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?_.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const C=c.external.registry.get(r)?.id;if(!C)throw new Error("Schema is missing an `id` property");_.$id=c.external.uri(C)}Object.assign(_,u.def);const g=c.external?.defs??{};for(const C of this.seen.entries()){const A=C[1];A.def&&A.defId&&(g[A.defId]=A.def)}c.external||Object.keys(g).length>0&&(this.target==="draft-2020-12"?_.$defs=g:_.definitions=g);try{return JSON.parse(JSON.stringify(_))}catch{throw new Error("Error converting schema to JSON.")}}}function $f(t,r){if(t instanceof lc){const c=new la(r),u={};for(const x of t._idmap.entries()){const[_,g]=x;c.process(g)}const f={},p={registry:t,uri:r?.uri,defs:u};for(const x of t._idmap.entries()){const[_,g]=x;f[_]=c.emit(g,{...r,external:p})}if(Object.keys(u).length>0){const x=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[x]:u}}return{schemas:f}}const o=new la(r);return o.process(t),o.emit(t,r)}function kt(t,r){const o=r??{seen:new Set};if(o.seen.has(t))return!1;o.seen.add(t);const u=t._zod.def;switch(u.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return kt(u.element,o);case"object":{for(const f in u.shape)if(kt(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(kt(f,o))return!0;return!1}case"intersection":return kt(u.left,o)||kt(u.right,o);case"tuple":{for(const f of u.items)if(kt(f,o))return!0;return!!(u.rest&&kt(u.rest,o))}case"record":return kt(u.keyType,o)||kt(u.valueType,o);case"map":return kt(u.keyType,o)||kt(u.valueType,o);case"set":return kt(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return kt(u.innerType,o);case"lazy":return kt(u.getter(),o);case"default":return kt(u.innerType,o);case"prefault":return kt(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return kt(u.in,o)||kt(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const Vf=se("ZodISODateTime",(t,r)=>{l0.init(t,r),Et.init(t,r)});function Zf(t){return gf(Vf,t)}const jf=se("ZodISODate",(t,r)=>{c0.init(t,r),Et.init(t,r)});function Wf(t){return xf(jf,t)}const Hf=se("ZodISOTime",(t,r)=>{u0.init(t,r),Et.init(t,r)});function Gf(t){return yf(Hf,t)}const Xf=se("ZodISODuration",(t,r)=>{d0.init(t,r),Et.init(t,r)});function qf(t){return wf(Xf,t)}const Yf=(t,r)=>{ql.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>i1(t,o)},flatten:{value:o=>r1(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},zi=se("ZodError",Yf,{Parent:Error}),Jf=o1(zi),Kf=s1(zi),Qf=Jl(zi),dc=Kl(zi),ht=se("ZodType",(t,r)=>(ct.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...o)=>t.clone({...r,checks:[...r.checks??[],...o.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(o,c)=>dr(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>Jf(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Qf(t,o,c),t.parseAsync=async(o,c)=>Kf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>dc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(Xh(o,c)),t.superRefine=o=>t.check(qh(o)),t.overwrite=o=>t.check(ri(o)),t.optional=()=>da(t),t.nullable=()=>fa(t),t.nullish=()=>da(fa(t)),t.nonoptional=o=>Uh(t,o),t.array=()=>ye(t),t.or=o=>Pe([t,o]),t.and=o=>Nh(t,o),t.transform=o=>ha(t,Mh(o)),t.default=o=>Bh(t,o),t.prefault=o=>Fh(t,o),t.catch=o=>$h(t,o),t.pipe=o=>ha(t,o),t.readonly=()=>jh(t),t.describe=o=>{const c=t.clone();return jr.add(c,{description:o}),c},Object.defineProperty(t,"description",{get(){return jr.get(t)?.description},configurable:!0}),t.meta=(...o)=>{if(o.length===0)return jr.get(t);const c=t.clone();return jr.add(c,o[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),fc=se("_ZodString",(t,r)=>{Ho.init(t,r),ht.init(t,r);const o=t._zod.bag;t.format=o.format??null,t.minLength=o.minimum??null,t.maxLength=o.maximum??null,t.regex=(...c)=>t.check(Tf(...c)),t.includes=(...c)=>t.check(Rf(...c)),t.startsWith=(...c)=>t.check(kf(...c)),t.endsWith=(...c)=>t.check(Mf(...c)),t.min=(...c)=>t.check(Mi(...c)),t.max=(...c)=>t.check(cc(...c)),t.length=(...c)=>t.check(uc(...c)),t.nonempty=(...c)=>t.check(Mi(1,...c)),t.lowercase=c=>t.check(Nf(c)),t.uppercase=c=>t.check(Of(c)),t.trim=()=>t.check(Pf()),t.normalize=(...c)=>t.check(Df(...c)),t.toLowerCase=()=>t.check(Bf()),t.toUpperCase=()=>t.check(Lf())}),eh=se("ZodString",(t,r)=>{Ho.init(t,r),fc.init(t,r),t.email=o=>t.check(X0(th,o)),t.url=o=>t.check(Q0(nh,o)),t.jwt=o=>t.check(mf(xh,o)),t.emoji=o=>t.check(ef(rh,o)),t.guid=o=>t.check(ia(ca,o)),t.uuid=o=>t.check(q0(vi,o)),t.uuidv4=o=>t.check(Y0(vi,o)),t.uuidv6=o=>t.check(J0(vi,o)),t.uuidv7=o=>t.check(K0(vi,o)),t.nanoid=o=>t.check(tf(ih,o)),t.guid=o=>t.check(ia(ca,o)),t.cuid=o=>t.check(nf(oh,o)),t.cuid2=o=>t.check(rf(sh,o)),t.ulid=o=>t.check(of(ah,o)),t.base64=o=>t.check(ff(ph,o)),t.base64url=o=>t.check(hf(mh,o)),t.xid=o=>t.check(sf(lh,o)),t.ksuid=o=>t.check(af(ch,o)),t.ipv4=o=>t.check(lf(uh,o)),t.ipv6=o=>t.check(cf(dh,o)),t.cidrv4=o=>t.check(uf(fh,o)),t.cidrv6=o=>t.check(df(hh,o)),t.e164=o=>t.check(pf(gh,o)),t.datetime=o=>t.check(Zf(o)),t.date=o=>t.check(Wf(o)),t.time=o=>t.check(Gf(o)),t.duration=o=>t.check(qf(o))});function w(t){return G0(eh,t)}const Et=se("ZodStringFormat",(t,r)=>{yt.init(t,r),fc.init(t,r)}),th=se("ZodEmail",(t,r)=>{Q1.init(t,r),Et.init(t,r)}),ca=se("ZodGUID",(t,r)=>{J1.init(t,r),Et.init(t,r)}),vi=se("ZodUUID",(t,r)=>{K1.init(t,r),Et.init(t,r)}),nh=se("ZodURL",(t,r)=>{e0.init(t,r),Et.init(t,r)}),rh=se("ZodEmoji",(t,r)=>{t0.init(t,r),Et.init(t,r)}),ih=se("ZodNanoID",(t,r)=>{n0.init(t,r),Et.init(t,r)}),oh=se("ZodCUID",(t,r)=>{r0.init(t,r),Et.init(t,r)}),sh=se("ZodCUID2",(t,r)=>{i0.init(t,r),Et.init(t,r)}),ah=se("ZodULID",(t,r)=>{o0.init(t,r),Et.init(t,r)}),lh=se("ZodXID",(t,r)=>{s0.init(t,r),Et.init(t,r)}),ch=se("ZodKSUID",(t,r)=>{a0.init(t,r),Et.init(t,r)}),uh=se("ZodIPv4",(t,r)=>{f0.init(t,r),Et.init(t,r)}),dh=se("ZodIPv6",(t,r)=>{h0.init(t,r),Et.init(t,r)}),fh=se("ZodCIDRv4",(t,r)=>{p0.init(t,r),Et.init(t,r)}),hh=se("ZodCIDRv6",(t,r)=>{m0.init(t,r),Et.init(t,r)}),ph=se("ZodBase64",(t,r)=>{g0.init(t,r),Et.init(t,r)}),mh=se("ZodBase64URL",(t,r)=>{y0.init(t,r),Et.init(t,r)}),gh=se("ZodE164",(t,r)=>{w0.init(t,r),Et.init(t,r)}),xh=se("ZodJWT",(t,r)=>{v0.init(t,r),Et.init(t,r)}),Go=se("ZodNumber",(t,r)=>{sc.init(t,r),ht.init(t,r),t.gt=(c,u)=>t.check(sa(c,u)),t.gte=(c,u)=>t.check(po(c,u)),t.min=(c,u)=>t.check(po(c,u)),t.lt=(c,u)=>t.check(oa(c,u)),t.lte=(c,u)=>t.check(ho(c,u)),t.max=(c,u)=>t.check(ho(c,u)),t.int=c=>t.check(ua(c)),t.safe=c=>t.check(ua(c)),t.positive=c=>t.check(sa(0,c)),t.nonnegative=c=>t.check(po(0,c)),t.negative=c=>t.check(oa(0,c)),t.nonpositive=c=>t.check(ho(0,c)),t.multipleOf=(c,u)=>t.check(aa(c,u)),t.step=(c,u)=>t.check(aa(c,u)),t.finite=()=>t;const o=t._zod.bag;t.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),t.isFinite=!0,t.format=o.format??null});function Q(t){return _f(Go,t)}const yh=se("ZodNumberFormat",(t,r)=>{C0.init(t,r),Go.init(t,r)});function ua(t){return Cf(yh,t)}const wh=se("ZodBoolean",(t,r)=>{b0.init(t,r),ht.init(t,r)});function Tt(t){return bf(wh,t)}const _h=se("ZodNull",(t,r)=>{E0.init(t,r),ht.init(t,r)});function hc(t){return Ef(_h,t)}const vh=se("ZodAny",(t,r)=>{A0.init(t,r),ht.init(t,r)});function fr(){return Af(vh)}const Ch=se("ZodUnknown",(t,r)=>{I0.init(t,r),ht.init(t,r)});function Tr(){return If(Ch)}const bh=se("ZodNever",(t,r)=>{S0.init(t,r),ht.init(t,r)});function Eh(t){return Sf(bh,t)}const Ah=se("ZodArray",(t,r)=>{T0.init(t,r),ht.init(t,r),t.element=r.element,t.min=(o,c)=>t.check(Mi(o,c)),t.nonempty=o=>t.check(Mi(1,o)),t.max=(o,c)=>t.check(cc(o,c)),t.length=(o,c)=>t.check(uc(o,c)),t.unwrap=()=>t.element});function ye(t,r){return Ff(Ah,t,r)}const Ih=se("ZodObject",(t,r)=>{N0.init(t,r),ht.init(t,r),nt(t,"shape",()=>r.shape),t.keyof=()=>Le(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Tr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Tr()}),t.strict=()=>t.clone({...t._zod.def,catchall:Eh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Qd(t,o),t.merge=o=>e1(t,o),t.pick=o=>Jd(t,o),t.omit=o=>Kd(t,o),t.partial=(...o)=>t1(mc,t,o[0]),t.required=(...o)=>n1(gc,t,o[0])});function S(t,r){const o={type:"object",get shape(){return jo(this,"shape",{...t}),this.shape},...be(r)};return new Ih(o)}const pc=se("ZodUnion",(t,r)=>{ac.init(t,r),ht.init(t,r),t.options=r.options});function Pe(t,r){return new pc({type:"union",options:t,...be(r)})}const Sh=se("ZodDiscriminatedUnion",(t,r)=>{pc.init(t,r),O0.init(t,r)});function lt(t,r,o){return new Sh({type:"union",options:r,discriminator:t,...be(o)})}const Th=se("ZodIntersection",(t,r)=>{R0.init(t,r),ht.init(t,r)});function Nh(t,r){return new Th({type:"intersection",left:t,right:r})}const Oh=se("ZodRecord",(t,r)=>{k0.init(t,r),ht.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function gt(t,r,o){return new Oh({type:"record",keyType:t,valueType:r,...be(o)})}const So=se("ZodEnum",(t,r)=>{M0.init(t,r),ht.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const o=new Set(Object.keys(r.entries));t.extract=(c,u)=>{const f={};for(const p of c)if(o.has(p))f[p]=r.entries[p];else throw new Error(`Key ${p} not found in enum`);return new So({...r,checks:[],...be(u),entries:f})},t.exclude=(c,u)=>{const f={...r.entries};for(const p of c)if(o.has(p))delete f[p];else throw new Error(`Key ${p} not found in enum`);return new So({...r,checks:[],...be(u),entries:f})}});function Le(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new So({type:"enum",entries:o,...be(r)})}const Rh=se("ZodLiteral",(t,r)=>{D0.init(t,r),ht.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function G(t,r){return new Rh({type:"literal",values:Array.isArray(t)?t:[t],...be(r)})}const kh=se("ZodTransform",(t,r)=>{P0.init(t,r),ht.init(t,r),t._zod.parse=(o,c)=>{o.addIssue=f=>{if(typeof f=="string")o.issues.push(Jr(f,o.value,r));else{const p=f;p.fatal&&(p.continue=!1),p.code??(p.code="custom"),p.input??(p.input=o.value),p.inst??(p.inst=t),p.continue??(p.continue=!0),o.issues.push(Jr(p))}};const u=r.transform(o.value,o);return u instanceof Promise?u.then(f=>(o.value=f,o)):(o.value=u,o)}});function Mh(t){return new kh({type:"transform",transform:t})}const mc=se("ZodOptional",(t,r)=>{B0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function da(t){return new mc({type:"optional",innerType:t})}const Dh=se("ZodNullable",(t,r)=>{L0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function fa(t){return new Dh({type:"nullable",innerType:t})}const Ph=se("ZodDefault",(t,r)=>{F0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Bh(t,r){return new Ph({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Lh=se("ZodPrefault",(t,r)=>{U0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Fh(t,r){return new Lh({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const gc=se("ZodNonOptional",(t,r)=>{z0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Uh(t,r){return new gc({type:"nonoptional",innerType:t,...be(r)})}const zh=se("ZodCatch",(t,r)=>{$0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function $h(t,r){return new zh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Vh=se("ZodPipe",(t,r)=>{V0.init(t,r),ht.init(t,r),t.in=r.in,t.out=r.out});function ha(t,r){return new Vh({type:"pipe",in:t,out:r})}const Zh=se("ZodReadonly",(t,r)=>{Z0.init(t,r),ht.init(t,r)});function jh(t){return new Zh({type:"readonly",innerType:t})}const Wh=se("ZodLazy",(t,r)=>{j0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Xo(t){return new Wh({type:"lazy",getter:t})}const qo=se("ZodCustom",(t,r)=>{W0.init(t,r),ht.init(t,r)});function Hh(t){const r=new tn({check:"custom"});return r._zod.check=t,r}function Gh(t,r){return Uf(qo,t??(()=>!0),r)}function Xh(t,r={}){return zf(qo,t,r)}function qh(t){const r=Hh(o=>(o.addIssue=c=>{if(typeof c=="string")o.issues.push(Jr(c,o.value,r._zod.def));else{const u=c;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=o.value),u.inst??(u.inst=r),u.continue??(u.continue=!r._zod.def.abort),o.issues.push(Jr(u))}},t(o.value,o)));return r}function Di(t,r={error:`Input not instance of ${t.name}`}){const o=new qo({type:"custom",check:"custom",fn:c=>c instanceof t,abort:!0,...be(r)});return o._zod.bag.Class=t,o}function Yh(t){return vf(Go,t)}var De;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(De||(De={}));class pa extends Error{constructor(r,o){super(r),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function mo(t){}function Jh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=mo,onError:o=mo,onRetry:c=mo,onComment:u}=t;let f="",p=!0,x,_="",g="";function C(P){const L=p?P.replace(/^\xEF\xBB\xBF/,""):P,[Y,Z]=Kh(`${f}${L}`);for(const $ of Y)A($);f=Z,p=!1}function A(P){if(P===""){O();return}if(P.startsWith(":")){u&&u(P.slice(P.startsWith(": ")?2:1));return}const L=P.indexOf(":");if(L!==-1){const Y=P.slice(0,L),Z=P[L+1]===" "?2:1,$=P.slice(L+Z);B(Y,$,P);return}B(P,"",P)}function B(P,L,Y){switch(P){case"event":g=L;break;case"data":_=`${_}${L}
|
|
31
|
-
`;break;case"id":x=L.includes("\0")?void 0:L;break;case"retry":/^\d+$/.test(L)?c(parseInt(L,10)):o(new pa(`Invalid \`retry\` value: "${L}"`,{type:"invalid-retry",value:L,line:
|
|
32
|
-
`)?_.slice(0,-1):_}),x=void 0,_="",g=""}function k(
|
|
33
|
-
`,c);let
|
|
34
|
-
`&&c++}}return[r,o]}class xc extends TransformStream{constructor({onError:r,onRetry:o,onComment:c}={}){let u;super({start(f){u=Jh({onEvent:p=>{f.enqueue(p)},onError(p){r==="terminate"?f.error(p):typeof r=="function"&&r(p)},onRetry:o,onComment:c})},transform(f){u.feed(f)}})}}function vn(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Qh({tools:t=[],providerToolNames:r,resolveProviderToolName:o}){var c;const u={},f={};for(const p of t)if(p.type==="provider"){const x=(c=o?.(p))!=null?c:p.id in r?r[p.id]:void 0;if(x==null)continue;u[p.name]=x,f[x]=p.name}return{toProviderToolName:p=>{var x;return(x=u[p])!=null?x:p},toCustomToolName:p=>{var x;return(x=f[p])!=null?x:p}}}var ep=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ii(t){return Object.fromEntries([...t.headers])}var{btoa:tp,atob:np}=globalThis;function Yo(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=np(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function rp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return tp(r)}function Ar(t){return t instanceof Uint8Array?rp(t):t}function ip(t,r={}){const{useArrayBrackets:o=!0}=r,c=new FormData;for(const[u,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(u,f[0]);continue}const p=o?`${u}[]`:u;for(const x of f)c.append(p,x);continue}c.append(u,f)}return c}var yc="AI_DownloadError",wc=`vercel.ai.error.${yc}`,op=Symbol.for(wc),ma,ga,wn=class extends(ga=xt,ma=op,ga){constructor({url:t,statusCode:r,statusText:o,cause:c,message:u=c==null?`Failed to download ${t}: ${r} ${o}`:`Failed to download ${t}: ${c}`}){super({name:yc,message:u,cause:c}),this[ma]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return xt.hasMarker(t,wc)}},_c=2*1024*1024*1024;async function sp({response:t,url:r,maxBytes:o=_c}){const c=t.headers.get("content-length");if(c!=null){const C=parseInt(c,10);if(!isNaN(C)&&C>o)throw new wn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes (Content-Length: ${C}).`})}const u=t.body;if(u==null)return new Uint8Array(0);const f=u.getReader(),p=[];let x=0;try{for(;;){const{done:C,value:A}=await f.read();if(C)break;if(x+=A.length,x>o)throw new wn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});p.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const _=new Uint8Array(x);let g=0;for(const C of p)_.set(C,g),g+=C.length;return _}function ap(t){let r;try{r=new URL(t)}catch{throw new wn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new wn({url:t,message:`URL scheme must be http or https, got ${r.protocol}`});const o=r.hostname;if(!o)throw new wn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new wn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if(lp(c))throw new wn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(vc(o)){if(To(o))throw new wn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function vc(t){const r=t.split(".");return r.length!==4?!1:r.every(o=>{const c=Number(o);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===o})}function To(t){const r=t.split(".").map(Number),[o,c]=r;return o===0||o===10||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===168}function lp(t){const r=t.toLowerCase();if(r==="::1"||r==="::")return!0;if(r.startsWith("::ffff:")){const o=r.slice(7);if(vc(o))return To(o);const c=o.split(":");if(c.length===2){const u=parseInt(c[0],16),f=parseInt(c[1],16);if(!isNaN(u)&&!isNaN(f)){const p=u>>8&255,x=u&255,_=f>>8&255,g=f&255;return To(`${p}.${x}.${_}.${g}`)}}}return!!(r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"))}async function Cc(t,r){var o,c;ap(t);try{const u=await fetch(t,{signal:r?.abortSignal});if(!u.ok)throw new wn({url:t,statusCode:u.status,statusText:u.statusText});const f=await sp({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:_c}),p=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],p?{type:p}:void 0)}catch(u){throw wn.isInstance(u)?u:new wn({url:t,cause:u})}}var oi=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,p=new Array(r);for(let x=0;x<r;x++)p[x]=o[Math.random()*f|0];return p.join("")};if(t==null)return u;if(o.includes(c))throw new Ol({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},qt=oi();function No(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var cp=["fetch failed","failed to fetch"],up=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function dp(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&up.includes(r))}function fp({error:t,url:r,requestBodyValues:o}){if(No(t))return t;if(t instanceof TypeError&&cp.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new sn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return dp(t)?new sn({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function hp(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function pp(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function bc(t,...r){const o=new Headers(pp(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var mp="4.0.19";function xa(t){return t!=null}function gp({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new yi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new yi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function xp({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function yp(t){var r;const[o,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var wp=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,_p=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ya(t){const r=JSON.parse(t);return r===null||typeof r!="object"||wp.test(t)===!1&&_p.test(t)===!1?r:vp(r)}function vp(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function Jo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return ya(t)}try{return ya(t)}finally{Error.stackTraceLimit=r}}function Ko(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:o}=t;if(o!=null)for(const c of Object.keys(o))o[c]=or(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(or):or(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(or)),t.allOf!=null&&(t.allOf=t.allOf.map(or)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(or));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=or(r[o]);return t}function or(t){return typeof t=="boolean"?t:Ko(t)}var Cp=Symbol("Let zodToJsonSchema decide on which parser to use"),wa={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},bp=t=>typeof t=="string"?{...wa,name:t}:{...wa,...t};function cn(){return{}}function Ep(t,r){var o,c,u;const f={type:"array"};return(o=t.type)!=null&&o._def&&((u=(c=t.type)==null?void 0:c._def)==null?void 0:u.typeName)!==De.ZodAny&&(f.items=rt(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function Ap(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function Ip(){return{type:"boolean"}}function Ec(t,r){return rt(t.type._def,r)}var Sp=(t,r)=>rt(t.innerType._def,r);function Ac(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>Ac(t,r,u))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Tp(t)}}var Tp=t=>{const r={type:"integer",format:"unix-time"};for(const o of t.checks)switch(o.kind){case"min":r.minimum=o.value;break;case"max":r.maximum=o.value;break}return r};function Np(t,r){return{...rt(t.innerType._def,r),default:t.defaultValue()}}function Op(t,r){return r.effectStrategy==="input"?rt(t.schema._def,r):cn()}function Rp(t){return{type:"string",enum:Array.from(t.values)}}var kp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Mp(t,r){const o=[rt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),rt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(kp(u))c.push(...u.allOf);else{let f=u;if("additionalProperties"in u&&u.additionalProperties===!1){const{additionalProperties:p,...x}=u;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Dp(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var go=void 0,xn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(go===void 0&&(go=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),go),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ic(t,r){const o={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value;break;case"max":o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":yn(o,"email",c.message,r);break;case"format:idn-email":yn(o,"idn-email",c.message,r);break;case"pattern:zod":Xt(o,xn.email,c.message,r);break}break;case"url":yn(o,"uri",c.message,r);break;case"uuid":yn(o,"uuid",c.message,r);break;case"regex":Xt(o,c.regex,c.message,r);break;case"cuid":Xt(o,xn.cuid,c.message,r);break;case"cuid2":Xt(o,xn.cuid2,c.message,r);break;case"startsWith":Xt(o,RegExp(`^${xo(c.value,r)}`),c.message,r);break;case"endsWith":Xt(o,RegExp(`${xo(c.value,r)}$`),c.message,r);break;case"datetime":yn(o,"date-time",c.message,r);break;case"date":yn(o,"date",c.message,r);break;case"time":yn(o,"time",c.message,r);break;case"duration":yn(o,"duration",c.message,r);break;case"length":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value,o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"includes":{Xt(o,RegExp(xo(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&yn(o,"ipv4",c.message,r),c.version!=="v4"&&yn(o,"ipv6",c.message,r);break}case"base64url":Xt(o,xn.base64url,c.message,r);break;case"jwt":Xt(o,xn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Xt(o,xn.ipv4Cidr,c.message,r),c.version!=="v4"&&Xt(o,xn.ipv6Cidr,c.message,r);break}case"emoji":Xt(o,xn.emoji(),c.message,r);break;case"ulid":{Xt(o,xn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{yn(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Xt(o,xn.base64,c.message,r);break}}break}case"nanoid":Xt(o,xn.nanoid,c.message,r)}return o}function xo(t,r){return r.patternStrategy==="escape"?Bp(t):t}var Pp=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Bp(t){let r="";for(let o=0;o<t.length;o++)Pp.has(t[o])||(r+="\\"),r+=t[o];return r}function yn(t,r,o,c){var u;t.format||(u=t.anyOf)!=null&&u.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...o&&c.errorMessages&&{errorMessage:{format:o}}})):t.format=r}function Xt(t,r,o,c){var u;t.pattern||(u=t.allOf)!=null&&u.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:_a(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=_a(r,c)}function _a(t,r){var o;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},u=c.i?t.source.toLowerCase():t.source;let f="",p=!1,x=!1,_=!1;for(let g=0;g<u.length;g++){if(p){f+=u[g],p=!1;continue}if(c.i){if(x){if(u[g].match(/[a-z]/)){_?(f+=u[g],f+=`${u[g-2]}-${u[g]}`.toUpperCase(),_=!1):u[g+1]==="-"&&((o=u[g+2])!=null&&o.match(/[a-z]/))?(f+=u[g],_=!0):f+=`${u[g]}${u[g].toUpperCase()}`;continue}}else if(u[g].match(/[a-z]/)){f+=`[${u[g]}${u[g].toUpperCase()}]`;continue}}if(c.m){if(u[g]==="^"){f+=`(^|(?<=[\r
|
|
30
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const C of this.seen.entries()){const A=C[1];if(r===C[0]){m(C);continue}if(c.external){const O=c.external.registry.get(C[0])?.id;if(r!==C[0]&&O){m(C);continue}}if(this.metadataRegistry.get(C[0])?.id){m(C);continue}if(A.cycle){m(C);continue}if(A.count>1&&c.reused==="ref"){m(C);continue}}const x=(C,A)=>{const P=this.seen.get(C),O=P.def??P.schema,k={...O};if(P.ref===null)return;const B=P.ref;if(P.ref=null,B){x(B,A);const L=this.seen.get(B).schema;L.$ref&&A.target==="draft-7"?(O.allOf=O.allOf??[],O.allOf.push(L)):(Object.assign(O,L),Object.assign(O,k))}P.isParent||this.override({zodSchema:C,jsonSchema:O,path:P.path??[]})};for(const C of[...this.seen.entries()].reverse())x(C[0],{target:this.target});const _={};if(this.target==="draft-2020-12"?_.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?_.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const C=c.external.registry.get(r)?.id;if(!C)throw new Error("Schema is missing an `id` property");_.$id=c.external.uri(C)}Object.assign(_,u.def);const g=c.external?.defs??{};for(const C of this.seen.entries()){const A=C[1];A.def&&A.defId&&(g[A.defId]=A.def)}c.external||Object.keys(g).length>0&&(this.target==="draft-2020-12"?_.$defs=g:_.definitions=g);try{return JSON.parse(JSON.stringify(_))}catch{throw new Error("Error converting schema to JSON.")}}}function $f(t,r){if(t instanceof lc){const c=new la(r),u={};for(const x of t._idmap.entries()){const[_,g]=x;c.process(g)}const f={},m={registry:t,uri:r?.uri,defs:u};for(const x of t._idmap.entries()){const[_,g]=x;f[_]=c.emit(g,{...r,external:m})}if(Object.keys(u).length>0){const x=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[x]:u}}return{schemas:f}}const o=new la(r);return o.process(t),o.emit(t,r)}function kt(t,r){const o=r??{seen:new Set};if(o.seen.has(t))return!1;o.seen.add(t);const u=t._zod.def;switch(u.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return kt(u.element,o);case"object":{for(const f in u.shape)if(kt(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(kt(f,o))return!0;return!1}case"intersection":return kt(u.left,o)||kt(u.right,o);case"tuple":{for(const f of u.items)if(kt(f,o))return!0;return!!(u.rest&&kt(u.rest,o))}case"record":return kt(u.keyType,o)||kt(u.valueType,o);case"map":return kt(u.keyType,o)||kt(u.valueType,o);case"set":return kt(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return kt(u.innerType,o);case"lazy":return kt(u.getter(),o);case"default":return kt(u.innerType,o);case"prefault":return kt(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return kt(u.in,o)||kt(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const Vf=se("ZodISODateTime",(t,r)=>{l0.init(t,r),Et.init(t,r)});function Zf(t){return gf(Vf,t)}const jf=se("ZodISODate",(t,r)=>{c0.init(t,r),Et.init(t,r)});function Wf(t){return xf(jf,t)}const Hf=se("ZodISOTime",(t,r)=>{u0.init(t,r),Et.init(t,r)});function Gf(t){return yf(Hf,t)}const Xf=se("ZodISODuration",(t,r)=>{d0.init(t,r),Et.init(t,r)});function qf(t){return wf(Xf,t)}const Yf=(t,r)=>{ql.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>i1(t,o)},flatten:{value:o=>r1(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},zi=se("ZodError",Yf,{Parent:Error}),Jf=o1(zi),Kf=s1(zi),Qf=Jl(zi),dc=Kl(zi),ht=se("ZodType",(t,r)=>(ct.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...o)=>t.clone({...r,checks:[...r.checks??[],...o.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(o,c)=>dr(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>Jf(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Qf(t,o,c),t.parseAsync=async(o,c)=>Kf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>dc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(Xh(o,c)),t.superRefine=o=>t.check(qh(o)),t.overwrite=o=>t.check(ri(o)),t.optional=()=>da(t),t.nullable=()=>fa(t),t.nullish=()=>da(fa(t)),t.nonoptional=o=>Uh(t,o),t.array=()=>ye(t),t.or=o=>Pe([t,o]),t.and=o=>Nh(t,o),t.transform=o=>ha(t,Mh(o)),t.default=o=>Bh(t,o),t.prefault=o=>Fh(t,o),t.catch=o=>$h(t,o),t.pipe=o=>ha(t,o),t.readonly=()=>jh(t),t.describe=o=>{const c=t.clone();return jr.add(c,{description:o}),c},Object.defineProperty(t,"description",{get(){return jr.get(t)?.description},configurable:!0}),t.meta=(...o)=>{if(o.length===0)return jr.get(t);const c=t.clone();return jr.add(c,o[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),fc=se("_ZodString",(t,r)=>{Ho.init(t,r),ht.init(t,r);const o=t._zod.bag;t.format=o.format??null,t.minLength=o.minimum??null,t.maxLength=o.maximum??null,t.regex=(...c)=>t.check(Tf(...c)),t.includes=(...c)=>t.check(Rf(...c)),t.startsWith=(...c)=>t.check(kf(...c)),t.endsWith=(...c)=>t.check(Mf(...c)),t.min=(...c)=>t.check(Mi(...c)),t.max=(...c)=>t.check(cc(...c)),t.length=(...c)=>t.check(uc(...c)),t.nonempty=(...c)=>t.check(Mi(1,...c)),t.lowercase=c=>t.check(Nf(c)),t.uppercase=c=>t.check(Of(c)),t.trim=()=>t.check(Pf()),t.normalize=(...c)=>t.check(Df(...c)),t.toLowerCase=()=>t.check(Bf()),t.toUpperCase=()=>t.check(Lf())}),eh=se("ZodString",(t,r)=>{Ho.init(t,r),fc.init(t,r),t.email=o=>t.check(X0(th,o)),t.url=o=>t.check(Q0(nh,o)),t.jwt=o=>t.check(mf(xh,o)),t.emoji=o=>t.check(ef(rh,o)),t.guid=o=>t.check(ia(ca,o)),t.uuid=o=>t.check(q0(vi,o)),t.uuidv4=o=>t.check(Y0(vi,o)),t.uuidv6=o=>t.check(J0(vi,o)),t.uuidv7=o=>t.check(K0(vi,o)),t.nanoid=o=>t.check(tf(ih,o)),t.guid=o=>t.check(ia(ca,o)),t.cuid=o=>t.check(nf(oh,o)),t.cuid2=o=>t.check(rf(sh,o)),t.ulid=o=>t.check(of(ah,o)),t.base64=o=>t.check(ff(ph,o)),t.base64url=o=>t.check(hf(mh,o)),t.xid=o=>t.check(sf(lh,o)),t.ksuid=o=>t.check(af(ch,o)),t.ipv4=o=>t.check(lf(uh,o)),t.ipv6=o=>t.check(cf(dh,o)),t.cidrv4=o=>t.check(uf(fh,o)),t.cidrv6=o=>t.check(df(hh,o)),t.e164=o=>t.check(pf(gh,o)),t.datetime=o=>t.check(Zf(o)),t.date=o=>t.check(Wf(o)),t.time=o=>t.check(Gf(o)),t.duration=o=>t.check(qf(o))});function w(t){return G0(eh,t)}const Et=se("ZodStringFormat",(t,r)=>{yt.init(t,r),fc.init(t,r)}),th=se("ZodEmail",(t,r)=>{Q1.init(t,r),Et.init(t,r)}),ca=se("ZodGUID",(t,r)=>{J1.init(t,r),Et.init(t,r)}),vi=se("ZodUUID",(t,r)=>{K1.init(t,r),Et.init(t,r)}),nh=se("ZodURL",(t,r)=>{e0.init(t,r),Et.init(t,r)}),rh=se("ZodEmoji",(t,r)=>{t0.init(t,r),Et.init(t,r)}),ih=se("ZodNanoID",(t,r)=>{n0.init(t,r),Et.init(t,r)}),oh=se("ZodCUID",(t,r)=>{r0.init(t,r),Et.init(t,r)}),sh=se("ZodCUID2",(t,r)=>{i0.init(t,r),Et.init(t,r)}),ah=se("ZodULID",(t,r)=>{o0.init(t,r),Et.init(t,r)}),lh=se("ZodXID",(t,r)=>{s0.init(t,r),Et.init(t,r)}),ch=se("ZodKSUID",(t,r)=>{a0.init(t,r),Et.init(t,r)}),uh=se("ZodIPv4",(t,r)=>{f0.init(t,r),Et.init(t,r)}),dh=se("ZodIPv6",(t,r)=>{h0.init(t,r),Et.init(t,r)}),fh=se("ZodCIDRv4",(t,r)=>{p0.init(t,r),Et.init(t,r)}),hh=se("ZodCIDRv6",(t,r)=>{m0.init(t,r),Et.init(t,r)}),ph=se("ZodBase64",(t,r)=>{g0.init(t,r),Et.init(t,r)}),mh=se("ZodBase64URL",(t,r)=>{y0.init(t,r),Et.init(t,r)}),gh=se("ZodE164",(t,r)=>{w0.init(t,r),Et.init(t,r)}),xh=se("ZodJWT",(t,r)=>{v0.init(t,r),Et.init(t,r)}),Go=se("ZodNumber",(t,r)=>{sc.init(t,r),ht.init(t,r),t.gt=(c,u)=>t.check(sa(c,u)),t.gte=(c,u)=>t.check(po(c,u)),t.min=(c,u)=>t.check(po(c,u)),t.lt=(c,u)=>t.check(oa(c,u)),t.lte=(c,u)=>t.check(ho(c,u)),t.max=(c,u)=>t.check(ho(c,u)),t.int=c=>t.check(ua(c)),t.safe=c=>t.check(ua(c)),t.positive=c=>t.check(sa(0,c)),t.nonnegative=c=>t.check(po(0,c)),t.negative=c=>t.check(oa(0,c)),t.nonpositive=c=>t.check(ho(0,c)),t.multipleOf=(c,u)=>t.check(aa(c,u)),t.step=(c,u)=>t.check(aa(c,u)),t.finite=()=>t;const o=t._zod.bag;t.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),t.isFinite=!0,t.format=o.format??null});function ee(t){return _f(Go,t)}const yh=se("ZodNumberFormat",(t,r)=>{C0.init(t,r),Go.init(t,r)});function ua(t){return Cf(yh,t)}const wh=se("ZodBoolean",(t,r)=>{b0.init(t,r),ht.init(t,r)});function Tt(t){return bf(wh,t)}const _h=se("ZodNull",(t,r)=>{E0.init(t,r),ht.init(t,r)});function hc(t){return Ef(_h,t)}const vh=se("ZodAny",(t,r)=>{A0.init(t,r),ht.init(t,r)});function fr(){return Af(vh)}const Ch=se("ZodUnknown",(t,r)=>{I0.init(t,r),ht.init(t,r)});function Tr(){return If(Ch)}const bh=se("ZodNever",(t,r)=>{S0.init(t,r),ht.init(t,r)});function Eh(t){return Sf(bh,t)}const Ah=se("ZodArray",(t,r)=>{T0.init(t,r),ht.init(t,r),t.element=r.element,t.min=(o,c)=>t.check(Mi(o,c)),t.nonempty=o=>t.check(Mi(1,o)),t.max=(o,c)=>t.check(cc(o,c)),t.length=(o,c)=>t.check(uc(o,c)),t.unwrap=()=>t.element});function ye(t,r){return Ff(Ah,t,r)}const Ih=se("ZodObject",(t,r)=>{N0.init(t,r),ht.init(t,r),nt(t,"shape",()=>r.shape),t.keyof=()=>Le(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Tr()}),t.loose=()=>t.clone({...t._zod.def,catchall:Tr()}),t.strict=()=>t.clone({...t._zod.def,catchall:Eh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Qd(t,o),t.merge=o=>e1(t,o),t.pick=o=>Jd(t,o),t.omit=o=>Kd(t,o),t.partial=(...o)=>t1(mc,t,o[0]),t.required=(...o)=>n1(gc,t,o[0])});function S(t,r){const o={type:"object",get shape(){return jo(this,"shape",{...t}),this.shape},...be(r)};return new Ih(o)}const pc=se("ZodUnion",(t,r)=>{ac.init(t,r),ht.init(t,r),t.options=r.options});function Pe(t,r){return new pc({type:"union",options:t,...be(r)})}const Sh=se("ZodDiscriminatedUnion",(t,r)=>{pc.init(t,r),O0.init(t,r)});function lt(t,r,o){return new Sh({type:"union",options:r,discriminator:t,...be(o)})}const Th=se("ZodIntersection",(t,r)=>{R0.init(t,r),ht.init(t,r)});function Nh(t,r){return new Th({type:"intersection",left:t,right:r})}const Oh=se("ZodRecord",(t,r)=>{k0.init(t,r),ht.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function gt(t,r,o){return new Oh({type:"record",keyType:t,valueType:r,...be(o)})}const So=se("ZodEnum",(t,r)=>{M0.init(t,r),ht.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const o=new Set(Object.keys(r.entries));t.extract=(c,u)=>{const f={};for(const m of c)if(o.has(m))f[m]=r.entries[m];else throw new Error(`Key ${m} not found in enum`);return new So({...r,checks:[],...be(u),entries:f})},t.exclude=(c,u)=>{const f={...r.entries};for(const m of c)if(o.has(m))delete f[m];else throw new Error(`Key ${m} not found in enum`);return new So({...r,checks:[],...be(u),entries:f})}});function Le(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new So({type:"enum",entries:o,...be(r)})}const Rh=se("ZodLiteral",(t,r)=>{D0.init(t,r),ht.init(t,r),t.values=new Set(r.values),Object.defineProperty(t,"value",{get(){if(r.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return r.values[0]}})});function G(t,r){return new Rh({type:"literal",values:Array.isArray(t)?t:[t],...be(r)})}const kh=se("ZodTransform",(t,r)=>{P0.init(t,r),ht.init(t,r),t._zod.parse=(o,c)=>{o.addIssue=f=>{if(typeof f=="string")o.issues.push(Jr(f,o.value,r));else{const m=f;m.fatal&&(m.continue=!1),m.code??(m.code="custom"),m.input??(m.input=o.value),m.inst??(m.inst=t),m.continue??(m.continue=!0),o.issues.push(Jr(m))}};const u=r.transform(o.value,o);return u instanceof Promise?u.then(f=>(o.value=f,o)):(o.value=u,o)}});function Mh(t){return new kh({type:"transform",transform:t})}const mc=se("ZodOptional",(t,r)=>{B0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function da(t){return new mc({type:"optional",innerType:t})}const Dh=se("ZodNullable",(t,r)=>{L0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function fa(t){return new Dh({type:"nullable",innerType:t})}const Ph=se("ZodDefault",(t,r)=>{F0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Bh(t,r){return new Ph({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Lh=se("ZodPrefault",(t,r)=>{U0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Fh(t,r){return new Lh({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const gc=se("ZodNonOptional",(t,r)=>{z0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Uh(t,r){return new gc({type:"nonoptional",innerType:t,...be(r)})}const zh=se("ZodCatch",(t,r)=>{$0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function $h(t,r){return new zh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Vh=se("ZodPipe",(t,r)=>{V0.init(t,r),ht.init(t,r),t.in=r.in,t.out=r.out});function ha(t,r){return new Vh({type:"pipe",in:t,out:r})}const Zh=se("ZodReadonly",(t,r)=>{Z0.init(t,r),ht.init(t,r)});function jh(t){return new Zh({type:"readonly",innerType:t})}const Wh=se("ZodLazy",(t,r)=>{j0.init(t,r),ht.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Xo(t){return new Wh({type:"lazy",getter:t})}const qo=se("ZodCustom",(t,r)=>{W0.init(t,r),ht.init(t,r)});function Hh(t){const r=new tn({check:"custom"});return r._zod.check=t,r}function Gh(t,r){return Uf(qo,t??(()=>!0),r)}function Xh(t,r={}){return zf(qo,t,r)}function qh(t){const r=Hh(o=>(o.addIssue=c=>{if(typeof c=="string")o.issues.push(Jr(c,o.value,r._zod.def));else{const u=c;u.fatal&&(u.continue=!1),u.code??(u.code="custom"),u.input??(u.input=o.value),u.inst??(u.inst=r),u.continue??(u.continue=!r._zod.def.abort),o.issues.push(Jr(u))}},t(o.value,o)));return r}function Di(t,r={error:`Input not instance of ${t.name}`}){const o=new qo({type:"custom",check:"custom",fn:c=>c instanceof t,abort:!0,...be(r)});return o._zod.bag.Class=t,o}function Yh(t){return vf(Go,t)}var De;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(De||(De={}));class pa extends Error{constructor(r,o){super(r),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function mo(t){}function Jh(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=mo,onError:o=mo,onRetry:c=mo,onComment:u}=t;let f="",m=!0,x,_="",g="";function C(B){const L=m?B.replace(/^\xEF\xBB\xBF/,""):B,[K,z]=Kh(`${f}${L}`);for(const $ of K)A($);f=z,m=!1}function A(B){if(B===""){O();return}if(B.startsWith(":")){u&&u(B.slice(B.startsWith(": ")?2:1));return}const L=B.indexOf(":");if(L!==-1){const K=B.slice(0,L),z=B[L+1]===" "?2:1,$=B.slice(L+z);P(K,$,B);return}P(B,"",B)}function P(B,L,K){switch(B){case"event":g=L;break;case"data":_=`${_}${L}
|
|
31
|
+
`;break;case"id":x=L.includes("\0")?void 0:L;break;case"retry":/^\d+$/.test(L)?c(parseInt(L,10)):o(new pa(`Invalid \`retry\` value: "${L}"`,{type:"invalid-retry",value:L,line:K}));break;default:o(new pa(`Unknown field "${B.length>20?`${B.slice(0,20)}…`:B}"`,{type:"unknown-field",field:B,value:L,line:K}));break}}function O(){_.length>0&&r({id:x,event:g||void 0,data:_.endsWith(`
|
|
32
|
+
`)?_.slice(0,-1):_}),x=void 0,_="",g=""}function k(B={}){f&&B.consume&&A(f),m=!0,x=void 0,_="",g="",f=""}return{feed:C,reset:k}}function Kh(t){const r=[];let o="",c=0;for(;c<t.length;){const u=t.indexOf("\r",c),f=t.indexOf(`
|
|
33
|
+
`,c);let m=-1;if(u!==-1&&f!==-1?m=Math.min(u,f):u!==-1?u===t.length-1?m=-1:m=u:f!==-1&&(m=f),m===-1){o=t.slice(c);break}else{const x=t.slice(c,m);r.push(x),c=m+1,t[c-1]==="\r"&&t[c]===`
|
|
34
|
+
`&&c++}}return[r,o]}class xc extends TransformStream{constructor({onError:r,onRetry:o,onComment:c}={}){let u;super({start(f){u=Jh({onEvent:m=>{f.enqueue(m)},onError(m){r==="terminate"?f.error(m):typeof r=="function"&&r(m)},onRetry:o,onComment:c})},transform(f){u.feed(f)}})}}function vn(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Qh({tools:t=[],providerToolNames:r,resolveProviderToolName:o}){var c;const u={},f={};for(const m of t)if(m.type==="provider"){const x=(c=o?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(x==null)continue;u[m.name]=x,f[x]=m.name}return{toProviderToolName:m=>{var x;return(x=u[m])!=null?x:m},toCustomToolName:m=>{var x;return(x=f[m])!=null?x:m}}}var ep=class{constructor(){this.status={type:"pending"},this._resolve=void 0,this._reject=void 0}get promise(){return this._promise?this._promise:(this._promise=new Promise((t,r)=>{this.status.type==="resolved"?t(this.status.value):this.status.type==="rejected"&&r(this.status.error),this._resolve=t,this._reject=r}),this._promise)}resolve(t){var r;this.status={type:"resolved",value:t},this._promise&&((r=this._resolve)==null||r.call(this,t))}reject(t){var r;this.status={type:"rejected",error:t},this._promise&&((r=this._reject)==null||r.call(this,t))}isResolved(){return this.status.type==="resolved"}isRejected(){return this.status.type==="rejected"}isPending(){return this.status.type==="pending"}};function ii(t){return Object.fromEntries([...t.headers])}var{btoa:tp,atob:np}=globalThis;function Yo(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=np(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function rp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return tp(r)}function Ar(t){return t instanceof Uint8Array?rp(t):t}function ip(t,r={}){const{useArrayBrackets:o=!0}=r,c=new FormData;for(const[u,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(u,f[0]);continue}const m=o?`${u}[]`:u;for(const x of f)c.append(m,x);continue}c.append(u,f)}return c}var yc="AI_DownloadError",wc=`vercel.ai.error.${yc}`,op=Symbol.for(wc),ma,ga,wn=class extends(ga=xt,ma=op,ga){constructor({url:t,statusCode:r,statusText:o,cause:c,message:u=c==null?`Failed to download ${t}: ${r} ${o}`:`Failed to download ${t}: ${c}`}){super({name:yc,message:u,cause:c}),this[ma]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return xt.hasMarker(t,wc)}},_c=2*1024*1024*1024;async function sp({response:t,url:r,maxBytes:o=_c}){const c=t.headers.get("content-length");if(c!=null){const C=parseInt(c,10);if(!isNaN(C)&&C>o)throw new wn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes (Content-Length: ${C}).`})}const u=t.body;if(u==null)return new Uint8Array(0);const f=u.getReader(),m=[];let x=0;try{for(;;){const{done:C,value:A}=await f.read();if(C)break;if(x+=A.length,x>o)throw new wn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const _=new Uint8Array(x);let g=0;for(const C of m)_.set(C,g),g+=C.length;return _}function ap(t){let r;try{r=new URL(t)}catch{throw new wn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new wn({url:t,message:`URL scheme must be http or https, got ${r.protocol}`});const o=r.hostname;if(!o)throw new wn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new wn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if(lp(c))throw new wn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(vc(o)){if(To(o))throw new wn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function vc(t){const r=t.split(".");return r.length!==4?!1:r.every(o=>{const c=Number(o);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===o})}function To(t){const r=t.split(".").map(Number),[o,c]=r;return o===0||o===10||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===168}function lp(t){const r=t.toLowerCase();if(r==="::1"||r==="::")return!0;if(r.startsWith("::ffff:")){const o=r.slice(7);if(vc(o))return To(o);const c=o.split(":");if(c.length===2){const u=parseInt(c[0],16),f=parseInt(c[1],16);if(!isNaN(u)&&!isNaN(f)){const m=u>>8&255,x=u&255,_=f>>8&255,g=f&255;return To(`${m}.${x}.${_}.${g}`)}}}return!!(r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"))}async function Cc(t,r){var o,c;ap(t);try{const u=await fetch(t,{signal:r?.abortSignal});if(!u.ok)throw new wn({url:t,statusCode:u.status,statusText:u.statusText});const f=await sp({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:_c}),m=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(u){throw wn.isInstance(u)?u:new wn({url:t,cause:u})}}var oi=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Ol({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},qt=oi();function No(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var cp=["fetch failed","failed to fetch"],up=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function dp(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&up.includes(r))}function fp({error:t,url:r,requestBodyValues:o}){if(No(t))return t;if(t instanceof TypeError&&cp.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new sn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return dp(t)?new sn({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function hp(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function pp(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function bc(t,...r){const o=new Headers(pp(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var mp="4.0.19";function xa(t){return t!=null}function gp({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new yi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new yi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function xp({settingValue:t,environmentVariableName:r}){if(typeof t=="string")return t;if(!(t!=null||typeof process>"u")&&(t=process.env[r],!(t==null||typeof t!="string")))return t}function yp(t){var r;const[o,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var wp=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,_p=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ya(t){const r=JSON.parse(t);return r===null||typeof r!="object"||wp.test(t)===!1&&_p.test(t)===!1?r:vp(r)}function vp(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function Jo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return ya(t)}try{return ya(t)}finally{Error.stackTraceLimit=r}}function Ko(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:o}=t;if(o!=null)for(const c of Object.keys(o))o[c]=or(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(or):or(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(or)),t.allOf!=null&&(t.allOf=t.allOf.map(or)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(or));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=or(r[o]);return t}function or(t){return typeof t=="boolean"?t:Ko(t)}var Cp=Symbol("Let zodToJsonSchema decide on which parser to use"),wa={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},bp=t=>typeof t=="string"?{...wa,name:t}:{...wa,...t};function cn(){return{}}function Ep(t,r){var o,c,u;const f={type:"array"};return(o=t.type)!=null&&o._def&&((u=(c=t.type)==null?void 0:c._def)==null?void 0:u.typeName)!==De.ZodAny&&(f.items=rt(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function Ap(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function Ip(){return{type:"boolean"}}function Ec(t,r){return rt(t.type._def,r)}var Sp=(t,r)=>rt(t.innerType._def,r);function Ac(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>Ac(t,r,u))};switch(c){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Tp(t)}}var Tp=t=>{const r={type:"integer",format:"unix-time"};for(const o of t.checks)switch(o.kind){case"min":r.minimum=o.value;break;case"max":r.maximum=o.value;break}return r};function Np(t,r){return{...rt(t.innerType._def,r),default:t.defaultValue()}}function Op(t,r){return r.effectStrategy==="input"?rt(t.schema._def,r):cn()}function Rp(t){return{type:"string",enum:Array.from(t.values)}}var kp=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Mp(t,r){const o=[rt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),rt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(kp(u))c.push(...u.allOf);else{let f=u;if("additionalProperties"in u&&u.additionalProperties===!1){const{additionalProperties:m,...x}=u;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Dp(t){const r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:{type:r==="bigint"?"integer":r,const:t.value}}var go=void 0,xn={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(go===void 0&&(go=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),go),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Ic(t,r){const o={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value;break;case"max":o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":yn(o,"email",c.message,r);break;case"format:idn-email":yn(o,"idn-email",c.message,r);break;case"pattern:zod":Xt(o,xn.email,c.message,r);break}break;case"url":yn(o,"uri",c.message,r);break;case"uuid":yn(o,"uuid",c.message,r);break;case"regex":Xt(o,c.regex,c.message,r);break;case"cuid":Xt(o,xn.cuid,c.message,r);break;case"cuid2":Xt(o,xn.cuid2,c.message,r);break;case"startsWith":Xt(o,RegExp(`^${xo(c.value,r)}`),c.message,r);break;case"endsWith":Xt(o,RegExp(`${xo(c.value,r)}$`),c.message,r);break;case"datetime":yn(o,"date-time",c.message,r);break;case"date":yn(o,"date",c.message,r);break;case"time":yn(o,"time",c.message,r);break;case"duration":yn(o,"duration",c.message,r);break;case"length":o.minLength=typeof o.minLength=="number"?Math.max(o.minLength,c.value):c.value,o.maxLength=typeof o.maxLength=="number"?Math.min(o.maxLength,c.value):c.value;break;case"includes":{Xt(o,RegExp(xo(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&yn(o,"ipv4",c.message,r),c.version!=="v4"&&yn(o,"ipv6",c.message,r);break}case"base64url":Xt(o,xn.base64url,c.message,r);break;case"jwt":Xt(o,xn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Xt(o,xn.ipv4Cidr,c.message,r),c.version!=="v4"&&Xt(o,xn.ipv6Cidr,c.message,r);break}case"emoji":Xt(o,xn.emoji(),c.message,r);break;case"ulid":{Xt(o,xn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{yn(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Xt(o,xn.base64,c.message,r);break}}break}case"nanoid":Xt(o,xn.nanoid,c.message,r)}return o}function xo(t,r){return r.patternStrategy==="escape"?Bp(t):t}var Pp=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Bp(t){let r="";for(let o=0;o<t.length;o++)Pp.has(t[o])||(r+="\\"),r+=t[o];return r}function yn(t,r,o,c){var u;t.format||(u=t.anyOf)!=null&&u.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...o&&c.errorMessages&&{errorMessage:{format:o}}})):t.format=r}function Xt(t,r,o,c){var u;t.pattern||(u=t.allOf)!=null&&u.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:_a(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=_a(r,c)}function _a(t,r){var o;if(!r.applyRegexFlags||!t.flags)return t.source;const c={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},u=c.i?t.source.toLowerCase():t.source;let f="",m=!1,x=!1,_=!1;for(let g=0;g<u.length;g++){if(m){f+=u[g],m=!1;continue}if(c.i){if(x){if(u[g].match(/[a-z]/)){_?(f+=u[g],f+=`${u[g-2]}-${u[g]}`.toUpperCase(),_=!1):u[g+1]==="-"&&((o=u[g+2])!=null&&o.match(/[a-z]/))?(f+=u[g],_=!0):f+=`${u[g]}${u[g].toUpperCase()}`;continue}}else if(u[g].match(/[a-z]/)){f+=`[${u[g]}${u[g].toUpperCase()}]`;continue}}if(c.m){if(u[g]==="^"){f+=`(^|(?<=[\r
|
|
35
35
|
]))`;continue}else if(u[g]==="$"){f+=`($|(?=[\r
|
|
36
36
|
]))`;continue}}if(c.s&&u[g]==="."){f+=x?`${u[g]}\r
|
|
37
37
|
`:`[${u[g]}\r
|
|
38
|
-
]`;continue}f+=u[g],u[g]==="\\"?p=!0:x&&u[g]==="]"?x=!1:!x&&u[g]==="["&&(x=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function Sc(t,r){var o,c,u,f,p,x;const _={type:"object",additionalProperties:(o=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===De.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:g,...C}=Ic(t.keyType._def,r);return{..._,propertyNames:C}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===De.ZodEnum)return{..._,propertyNames:{enum:t.keyType._def.values}};if(((p=t.keyType)==null?void 0:p._def.typeName)===De.ZodBranded&&t.keyType._def.type._def.typeName===De.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...C}=Ec(t.keyType._def,r);return{..._,propertyNames:C}}}return _}function Lp(t,r){if(r.mapStrategy==="record")return Sc(t,r);const o=rt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||cn(),c=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||cn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function Fp(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),u=Array.from(new Set(c.map(f=>typeof f)));return{type:u.length===1?u[0]==="string"?"string":"number":["string","number"],enum:c}}function Up(){return{not:cn()}}function zp(){return{type:"null"}}var Oo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $p(t,r){const o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(c=>c._def.typeName in Oo&&(!c._def.checks||!c._def.checks.length))){const c=o.reduce((u,f)=>{const p=Oo[f._def.typeName];return p&&!u.includes(p)?[...u,p]:u},[]);return{type:c.length>1?c:c[0]}}else if(o.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=o.reduce((u,f)=>{const p=typeof f._def.value;switch(p){case"string":case"number":case"boolean":return[...u,p];case"bigint":return[...u,"integer"];case"object":if(f._def.value===null)return[...u,"null"];case"symbol":case"undefined":case"function":default:return u}},[]);if(c.length===o.length){const u=c.filter((f,p,x)=>x.indexOf(f)===p);return{type:u.length>1?u:u[0],enum:o.reduce((f,p)=>f.includes(p._def.value)?f:[...f,p._def.value],[])}}}else if(o.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((c,u)=>[...c,...u._def.values.filter(f=>!c.includes(f))],[])};return Vp(t,r)}var Vp=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>rt(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${u}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return o.length?{anyOf:o}:void 0};function Zp(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Oo[t.innerType._def.typeName],"null"]};const o=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function jp(t){const r={type:"number"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"int":r.type="integer";break;case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function Wp(t,r){const o={type:"object",properties:{}},c=[],u=t.shape();for(const p in u){let x=u[p];if(x===void 0||x._def===void 0)continue;const _=Gp(x),g=rt(x._def,{...r,currentPath:[...r.currentPath,"properties",p],propertyPath:[...r.currentPath,"properties",p]});g!==void 0&&(o.properties[p]=g,_||c.push(p))}c.length&&(o.required=c);const f=Hp(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Hp(t,r){if(t.catchall._def.typeName!=="ZodNever")return rt(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Gp(t){try{return t.isOptional()}catch{return!0}}var Xp=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return rt(t.innerType._def,r);const c=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:cn()},c]}:cn()},qp=(t,r)=>{if(r.pipeStrategy==="input")return rt(t.in._def,r);if(r.pipeStrategy==="output")return rt(t.out._def,r);const o=rt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=rt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function Yp(t,r){return rt(t.type._def,r)}function Jp(t,r){const c={type:"array",uniqueItems:!0,items:rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Kp(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:rt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Qp(){return{not:cn()}}function em(){return cn()}var tm=(t,r)=>rt(t.innerType._def,r),nm=(t,r,o)=>{switch(r){case De.ZodString:return Ic(t,o);case De.ZodNumber:return jp(t);case De.ZodObject:return Wp(t,o);case De.ZodBigInt:return Ap(t);case De.ZodBoolean:return Ip();case De.ZodDate:return Ac(t,o);case De.ZodUndefined:return Qp();case De.ZodNull:return zp();case De.ZodArray:return Ep(t,o);case De.ZodUnion:case De.ZodDiscriminatedUnion:return $p(t,o);case De.ZodIntersection:return Mp(t,o);case De.ZodTuple:return Kp(t,o);case De.ZodRecord:return Sc(t,o);case De.ZodLiteral:return Dp(t);case De.ZodEnum:return Rp(t);case De.ZodNativeEnum:return Fp(t);case De.ZodNullable:return Zp(t,o);case De.ZodOptional:return Xp(t,o);case De.ZodMap:return Lp(t,o);case De.ZodSet:return Jp(t,o);case De.ZodLazy:return()=>t.getter()._def;case De.ZodPromise:return Yp(t,o);case De.ZodNaN:case De.ZodNever:return Up();case De.ZodEffects:return Op(t,o);case De.ZodAny:return cn();case De.ZodUnknown:return em();case De.ZodDefault:return Np(t,o);case De.ZodBranded:return Ec(t,o);case De.ZodReadonly:return tm(t,o);case De.ZodCatch:return Sp(t,o);case De.ZodPipeline:return qp(t,o);case De.ZodFunction:case De.ZodVoid:case De.ZodSymbol:return;default:return(c=>{})()}},rm=(t,r)=>{let o=0;for(;o<t.length&&o<r.length&&t[o]===r[o];o++);return[(t.length-o).toString(),...r.slice(o)].join("/")};function rt(t,r,o=!1){var c;const u=r.seen.get(t);if(r.override){const _=(c=r.override)==null?void 0:c.call(r,t,r,u,o);if(_!==Cp)return _}if(u&&!o){const _=im(u,r);if(_!==void 0)return _}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const p=nm(t,t.typeName,r),x=typeof p=="function"?rt(p(),r):p;if(x&&om(t,r,x),r.postProcess){const _=r.postProcess(x,t,r);return f.jsonSchema=x,_}return f.jsonSchema=x,x}var im=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:rm(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((o,c)=>r.currentPath[c]===o)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),cn()):r.$refStrategy==="seen"?cn():void 0}},om=(t,r,o)=>(t.description&&(o.description=t.description),o),sm=t=>{const r=bp(t),o=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,u])=>[u._def,{def:u._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},am=(t,r)=>{var o;const c=sm(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[C,A])=>{var B;return{...g,[C]:(B=rt(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,C]},!0))!=null?B:cn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,p=(o=rt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:cn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(p.title=x);const _=f===void 0?u?{...p,[c.definitionPath]:u}:p:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...u,[f]:p}};return _.$schema="http://json-schema.org/draft-07/schema#",_},Ro=Symbol.for("vercel.ai.schema");function ze(t){let r;return()=>(r==null&&(r=t()),r)}function $i(t,{validate:r}={}){return{[Ro]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function lm(t){return typeof t=="object"&&t!==null&&Ro in t&&t[Ro]===!0&&"jsonSchema"in t&&"validate"in t}function Qo(t){return t==null?$i({properties:{},additionalProperties:!1}):lm(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Fe(t):cm(t):t()}function cm(t){return $i(()=>Ko(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const o=await t["~standard"].validate(r);return"value"in o?{success:!0,value:o.value}:{success:!1,error:new cr({value:r,cause:o.issues})}}})}function um(t,r){var o;const c=(o=void 0)!=null?o:!1;return $i(()=>am(t,{$refStrategy:c?"root":"none"}),{validate:async u=>{const f=await t.safeParseAsync(u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dm(t,r){var o;const c=(o=void 0)!=null?o:!1;return $i(()=>Ko($f(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await dc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function fm(t){return"_zod"in t}function Fe(t,r){return fm(t)?dm(t):um(t)}async function Wt({value:t,schema:r,context:o}){const c=await Nr({value:t,schema:r,context:o});if(!c.success)throw cr.wrap({value:t,cause:c.error,context:o});return c.value}async function Nr({value:t,schema:r,context:o}){const c=Qo(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const u=await c.validate(t);return u.success?{success:!0,value:u.value,rawValue:t}:{success:!1,error:cr.wrap({value:t,cause:u.error,context:o}),rawValue:t}}catch(u){return{success:!1,error:cr.wrap({value:t,cause:u,context:o}),rawValue:t}}}async function hm({text:t,schema:r}){try{const o=Jo(t);return r==null?o:Wt({value:o,schema:r})}catch(o){throw Oi.isInstance(o)||cr.isInstance(o)?o:new Oi({text:t,cause:o})}}async function Yn({text:t,schema:r}){try{const o=Jo(t);return r==null?{success:!0,value:o,rawValue:o}:await Nr({value:o,schema:r})}catch(o){return{success:!1,error:Oi.isInstance(o)?o:new Oi({text:t,cause:o}),rawValue:void 0}}}function va(t){try{return Jo(t),!0}catch{return!1}}function pm({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new xc).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await Yn({text:o,schema:r}))}}))}async function Bn({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Nr({value:r[t],schema:o});if(!c.success)throw new Ol({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var mm=()=>globalThis.fetch,Ln=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p})=>Nc({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p}),Tc=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p})=>Nc({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p}),Nc=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:p=mm()})=>{try{const x=await p(t,{method:"POST",headers:bc(r,`ai-sdk/provider-utils/${mp}`,hp()),body:o.content,signal:f}),_=ii(x);if(!x.ok){let g;try{g=await u({response:x,url:t,requestBodyValues:o.values})}catch(C){throw No(C)||sn.isInstance(C)?C:new sn({message:"Failed to process error response",cause:C,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:o.values})}catch(g){throw g instanceof Error&&(No(g)||sn.isInstance(g))?g:new sn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}}catch(x){throw fp({error:x,url:t,requestBodyValues:o.values})}};function gm({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:p,onInputDelta:x,onInputAvailable:_,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:p,onInputDelta:x,onInputAvailable:_})}function Fn({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:p,onInputStart:x,onInputDelta:_,onInputAvailable:g,...C})=>({type:"provider",id:t,args:C,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:p,onInputStart:x,onInputDelta:_,onInputAvailable:g,supportsDeferredResults:c})}async function Oc(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var xm=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const p=await c.text(),x=ii(c);if(p.trim()==="")return{responseHeaders:x,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,isRetryable:o?.(c)})};try{const _=await hm({text:p,schema:t});return{responseHeaders:x,value:new sn({message:r(_),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,data:_,isRetryable:o?.(c,_)})}}catch{return{responseHeaders:x,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,isRetryable:o?.(c)})}}},es=t=>async({response:r})=>{const o=ii(r);if(r.body==null)throw new Dd({});return{responseHeaders:o,value:pm({stream:r.body,schema:t})}},ur=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await Yn({text:u,schema:t}),p=ii(r);if(!f.success)throw new sn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:p,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:p,value:f.value,rawValue:f.rawValue}},ym=()=>async({response:t,url:r,requestBodyValues:o})=>{const c=ii(t);if(!t.body)throw new sn({message:"Response body is empty",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const u=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(u)}}catch(u){throw new sn({message:"Failed to read response as array buffer",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:u})}};function wm(t){return t?.replace(/\/$/,"")}var Ci=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Rc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var _m=Object.defineProperty,vm=(t,r)=>{for(var o in r)_m(t,o,{get:r[o],enumerable:!0})},kc="AI_NoObjectGeneratedError",Mc=`vercel.ai.error.${kc}`,Cm=Symbol.for(Mc),Dc,Gn=class extends xt{constructor({message:t="No object generated.",cause:r,text:o,response:c,usage:u,finishReason:f}){super({name:kc,message:t,cause:r}),this[Dc]=!0,this.text=o,this.response=c,this.usage=u,this.finishReason=f}static isInstance(t){return xt.hasMarker(t,Mc)}};Dc=Cm;var Pc=Pe([w(),Di(Uint8Array),Di(ArrayBuffer),Gh(t=>{var r,o;return(o=(r=globalThis.Buffer)==null?void 0:r.isBuffer(t))!=null?o:!1},{message:"Must be a Buffer"})]),Kr=Xo(()=>Pe([hc(),w(),Q(),Tt(),gt(w(),Kr.optional()),ye(Kr)])),bt=gt(w(),gt(w(),Kr.optional())),Bc=S({type:G("text"),text:w(),providerOptions:bt.optional()}),bm=S({type:G("image"),image:Pe([Pc,Di(URL)]),mediaType:w().optional(),providerOptions:bt.optional()}),Lc=S({type:G("file"),data:Pe([Pc,Di(URL)]),filename:w().optional(),mediaType:w(),providerOptions:bt.optional()}),Em=S({type:G("reasoning"),text:w(),providerOptions:bt.optional()}),Am=S({type:G("tool-call"),toolCallId:w(),toolName:w(),input:Tr(),providerOptions:bt.optional(),providerExecuted:Tt().optional()}),Im=lt("type",[S({type:G("text"),value:w(),providerOptions:bt.optional()}),S({type:G("json"),value:Kr,providerOptions:bt.optional()}),S({type:G("execution-denied"),reason:w().optional(),providerOptions:bt.optional()}),S({type:G("error-text"),value:w(),providerOptions:bt.optional()}),S({type:G("error-json"),value:Kr,providerOptions:bt.optional()}),S({type:G("content"),value:ye(Pe([S({type:G("text"),text:w(),providerOptions:bt.optional()}),S({type:G("media"),data:w(),mediaType:w()}),S({type:G("file-data"),data:w(),mediaType:w(),filename:w().optional(),providerOptions:bt.optional()}),S({type:G("file-url"),url:w(),providerOptions:bt.optional()}),S({type:G("file-id"),fileId:Pe([w(),gt(w(),w())]),providerOptions:bt.optional()}),S({type:G("image-data"),data:w(),mediaType:w(),providerOptions:bt.optional()}),S({type:G("image-url"),url:w(),providerOptions:bt.optional()}),S({type:G("image-file-id"),fileId:Pe([w(),gt(w(),w())]),providerOptions:bt.optional()}),S({type:G("custom"),providerOptions:bt.optional()})]))})]),Fc=S({type:G("tool-result"),toolCallId:w(),toolName:w(),output:Im,providerOptions:bt.optional()}),Sm=S({type:G("tool-approval-request"),approvalId:w(),toolCallId:w()}),Tm=S({type:G("tool-approval-response"),approvalId:w(),approved:Tt(),reason:w().optional()}),Nm=S({role:G("system"),content:w(),providerOptions:bt.optional()}),Om=S({role:G("user"),content:Pe([w(),ye(Pe([Bc,bm,Lc]))]),providerOptions:bt.optional()}),Rm=S({role:G("assistant"),content:Pe([w(),ye(Pe([Bc,Lc,Em,Am,Fc,Sm]))]),providerOptions:bt.optional()}),km=S({role:G("tool"),content:ye(Pe([Fc,Tm])),providerOptions:bt.optional()});Pe([Nm,Om,Rm,km]);var Mm={};vm(Mm,{array:()=>Lm,choice:()=>Fm,json:()=>Um,object:()=>Bm,text:()=>Pm});function Dm(t){const r=["ROOT"];let o=-1,c=null;function u(_,g,C){switch(_){case'"':{o=g,r.pop(),r.push(C),r.push("INSIDE_STRING");break}case"f":case"t":case"n":{o=g,c=g,r.pop(),r.push(C),r.push("INSIDE_LITERAL");break}case"-":{r.pop(),r.push(C),r.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=g,r.pop(),r.push(C),r.push("INSIDE_NUMBER");break}case"{":{o=g,r.pop(),r.push(C),r.push("INSIDE_OBJECT_START");break}case"[":{o=g,r.pop(),r.push(C),r.push("INSIDE_ARRAY_START");break}}}function f(_,g){switch(_){case",":{r.pop(),r.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{o=g,r.pop();break}}}function p(_,g){switch(_){case",":{r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=g,r.pop();break}}}for(let _=0;_<t.length;_++){const g=t[_];switch(r[r.length-1]){case"ROOT":u(g,_,"FINISH");break;case"INSIDE_OBJECT_START":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_KEY");break}case"}":{o=_,r.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(g){case":":{r.pop(),r.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{u(g,_,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{f(g,_);break}case"INSIDE_STRING":{switch(g){case'"':{r.pop(),o=_;break}case"\\":{r.push("INSIDE_STRING_ESCAPE");break}default:o=_}break}case"INSIDE_ARRAY_START":{switch(g){case"]":{o=_,r.pop();break}default:{o=_,u(g,_,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(g){case",":{r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=_,r.pop();break}default:{o=_;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{u(g,_,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{r.pop(),o=_;break}case"INSIDE_NUMBER":{switch(g){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=_;break}case"e":case"E":case"-":case".":break;case",":{r.pop(),r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&p(g,_),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&f(g,_);break}case"}":{r.pop(),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&f(g,_);break}case"]":{r.pop(),r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&p(g,_);break}default:{r.pop();break}}break}case"INSIDE_LITERAL":{const A=t.substring(c,_+1);!"false".startsWith(A)&&!"true".startsWith(A)&&!"null".startsWith(A)?(r.pop(),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?f(g,_):r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&p(g,_)):o=_;break}}}let x=t.slice(0,o+1);for(let _=r.length-1;_>=0;_--)switch(r[_]){case"INSIDE_STRING":{x+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{x+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{x+="]";break}case"INSIDE_LITERAL":{const C=t.substring(c,t.length);"true".startsWith(C)?x+="true".slice(C.length):"false".startsWith(C)?x+="false".slice(C.length):"null".startsWith(C)&&(x+="null".slice(C.length))}}return x}async function Vi(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let r=await Yn({text:t});return r.success?{value:r.value,state:"successful-parse"}:(r=await Yn({text:Dm(t)}),r.success?{value:r.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Pm=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:t}){return t},async parsePartialOutput({text:t}){return{partial:t}},createElementStreamTransform(){}}),Bm=({schema:t,name:r,description:o})=>{const c=Qo(t);return{name:"object",responseFormat:Oc(c.jsonSchema).then(u=>({type:"json",schema:u,...r!=null&&{name:r},...o!=null&&{description:o}})),async parseCompleteOutput({text:u},f){const p=await Yn({text:u});if(!p.success)throw new Gn({message:"No object generated: could not parse the response.",cause:p.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});const x=await Nr({value:p.value,schema:c});if(!x.success)throw new Gn({message:"No object generated: response did not match schema.",cause:x.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});return x.value},async parsePartialOutput({text:u}){const f=await Vi(u);switch(f.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:f.value}}},createElementStreamTransform(){}}},Lm=({element:t,name:r,description:o})=>{const c=Qo(t);return{name:"array",responseFormat:Oc(c.jsonSchema).then(u=>{const{$schema:f,...p}=u;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:p}},required:["elements"],additionalProperties:!1},...r!=null&&{name:r},...o!=null&&{description:o}}}),async parseCompleteOutput({text:u},f){const p=await Yn({text:u});if(!p.success)throw new Gn({message:"No object generated: could not parse the response.",cause:p.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});const x=p.value;if(x==null||typeof x!="object"||!("elements"in x)||!Array.isArray(x.elements))throw new Gn({message:"No object generated: response did not match schema.",cause:new cr({value:x,cause:"response must be an object with an elements array"}),text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});for(const _ of x.elements){const g=await Nr({value:_,schema:c});if(!g.success)throw new Gn({message:"No object generated: response did not match schema.",cause:g.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason})}return x.elements},async parsePartialOutput({text:u}){const f=await Vi(u);switch(f.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const p=f.value;if(p==null||typeof p!="object"||!("elements"in p)||!Array.isArray(p.elements))return;const x=f.state==="repaired-parse"&&p.elements.length>0?p.elements.slice(0,-1):p.elements,_=[];for(const g of x){const C=await Nr({value:g,schema:c});C.success&&_.push(C.value)}return{partial:_}}}},createElementStreamTransform(){let u=0;return new TransformStream({transform({partialOutput:f},p){if(f!=null)for(;u<f.length;u++)p.enqueue(f[u])}})}}},Fm=({options:t,name:r,description:o})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...r!=null&&{name:r},...o!=null&&{description:o}}),async parseCompleteOutput({text:c},u){const f=await Yn({text:c});if(!f.success)throw new Gn({message:"No object generated: could not parse the response.",cause:f.error,text:c,response:u.response,usage:u.usage,finishReason:u.finishReason});const p=f.value;if(p==null||typeof p!="object"||!("result"in p)||typeof p.result!="string"||!t.includes(p.result))throw new Gn({message:"No object generated: response did not match schema.",cause:new cr({value:p,cause:"response must be an object that contains a choice value."}),text:c,response:u.response,usage:u.usage,finishReason:u.finishReason});return p.result},async parsePartialOutput({text:c}){const u=await Vi(c);switch(u.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const f=u.value;if(f==null||typeof f!="object"||!("result"in f)||typeof f.result!="string")return;const p=t.filter(x=>x.startsWith(f.result));return u.state==="successful-parse"?p.includes(f.result)?{partial:f.result}:void 0:p.length===1?{partial:p[0]}:void 0}}},createElementStreamTransform(){}}),Um=({name:t,description:r}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:o},c){const u=await Yn({text:o});if(!u.success)throw new Gn({message:"No object generated: could not parse the response.",cause:u.error,text:o,response:c.response,usage:c.usage,finishReason:c.finishReason});return u.value},async parsePartialOutput({text:o}){const c=await Vi(o);switch(c.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return c.value===void 0?void 0:{partial:c.value}}},createElementStreamTransform(){}});oi({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(t,r){r.enqueue(`data: ${JSON.stringify(t)}
|
|
38
|
+
]`;continue}f+=u[g],u[g]==="\\"?m=!0:x&&u[g]==="]"?x=!1:!x&&u[g]==="["&&(x=!0)}try{new RegExp(f)}catch{return console.warn(`Could not convert regex pattern at ${r.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return f}function Sc(t,r){var o,c,u,f,m,x;const _={type:"object",additionalProperties:(o=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===De.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:g,...C}=Ic(t.keyType._def,r);return{..._,propertyNames:C}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===De.ZodEnum)return{..._,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===De.ZodBranded&&t.keyType._def.type._def.typeName===De.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...C}=Ec(t.keyType._def,r);return{..._,propertyNames:C}}}return _}function Lp(t,r){if(r.mapStrategy==="record")return Sc(t,r);const o=rt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||cn(),c=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||cn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function Fp(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),u=Array.from(new Set(c.map(f=>typeof f)));return{type:u.length===1?u[0]==="string"?"string":"number":["string","number"],enum:c}}function Up(){return{not:cn()}}function zp(){return{type:"null"}}var Oo={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function $p(t,r){const o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(c=>c._def.typeName in Oo&&(!c._def.checks||!c._def.checks.length))){const c=o.reduce((u,f)=>{const m=Oo[f._def.typeName];return m&&!u.includes(m)?[...u,m]:u},[]);return{type:c.length>1?c:c[0]}}else if(o.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=o.reduce((u,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...u,m];case"bigint":return[...u,"integer"];case"object":if(f._def.value===null)return[...u,"null"];case"symbol":case"undefined":case"function":default:return u}},[]);if(c.length===o.length){const u=c.filter((f,m,x)=>x.indexOf(f)===m);return{type:u.length>1?u:u[0],enum:o.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(o.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:o.reduce((c,u)=>[...c,...u._def.values.filter(f=>!c.includes(f))],[])};return Vp(t,r)}var Vp=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>rt(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${u}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return o.length?{anyOf:o}:void 0};function Zp(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Oo[t.innerType._def.typeName],"null"]};const o=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function jp(t){const r={type:"number"};if(!t.checks)return r;for(const o of t.checks)switch(o.kind){case"int":r.type="integer";break;case"min":o.inclusive?r.minimum=o.value:r.exclusiveMinimum=o.value;break;case"max":o.inclusive?r.maximum=o.value:r.exclusiveMaximum=o.value;break;case"multipleOf":r.multipleOf=o.value;break}return r}function Wp(t,r){const o={type:"object",properties:{}},c=[],u=t.shape();for(const m in u){let x=u[m];if(x===void 0||x._def===void 0)continue;const _=Gp(x),g=rt(x._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});g!==void 0&&(o.properties[m]=g,_||c.push(m))}c.length&&(o.required=c);const f=Hp(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Hp(t,r){if(t.catchall._def.typeName!=="ZodNever")return rt(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Gp(t){try{return t.isOptional()}catch{return!0}}var Xp=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return rt(t.innerType._def,r);const c=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:cn()},c]}:cn()},qp=(t,r)=>{if(r.pipeStrategy==="input")return rt(t.in._def,r);if(r.pipeStrategy==="output")return rt(t.out._def,r);const o=rt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=rt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function Yp(t,r){return rt(t.type._def,r)}function Jp(t,r){const c={type:"array",uniqueItems:!0,items:rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Kp(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:rt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Qp(){return{not:cn()}}function em(){return cn()}var tm=(t,r)=>rt(t.innerType._def,r),nm=(t,r,o)=>{switch(r){case De.ZodString:return Ic(t,o);case De.ZodNumber:return jp(t);case De.ZodObject:return Wp(t,o);case De.ZodBigInt:return Ap(t);case De.ZodBoolean:return Ip();case De.ZodDate:return Ac(t,o);case De.ZodUndefined:return Qp();case De.ZodNull:return zp();case De.ZodArray:return Ep(t,o);case De.ZodUnion:case De.ZodDiscriminatedUnion:return $p(t,o);case De.ZodIntersection:return Mp(t,o);case De.ZodTuple:return Kp(t,o);case De.ZodRecord:return Sc(t,o);case De.ZodLiteral:return Dp(t);case De.ZodEnum:return Rp(t);case De.ZodNativeEnum:return Fp(t);case De.ZodNullable:return Zp(t,o);case De.ZodOptional:return Xp(t,o);case De.ZodMap:return Lp(t,o);case De.ZodSet:return Jp(t,o);case De.ZodLazy:return()=>t.getter()._def;case De.ZodPromise:return Yp(t,o);case De.ZodNaN:case De.ZodNever:return Up();case De.ZodEffects:return Op(t,o);case De.ZodAny:return cn();case De.ZodUnknown:return em();case De.ZodDefault:return Np(t,o);case De.ZodBranded:return Ec(t,o);case De.ZodReadonly:return tm(t,o);case De.ZodCatch:return Sp(t,o);case De.ZodPipeline:return qp(t,o);case De.ZodFunction:case De.ZodVoid:case De.ZodSymbol:return;default:return(c=>{})()}},rm=(t,r)=>{let o=0;for(;o<t.length&&o<r.length&&t[o]===r[o];o++);return[(t.length-o).toString(),...r.slice(o)].join("/")};function rt(t,r,o=!1){var c;const u=r.seen.get(t);if(r.override){const _=(c=r.override)==null?void 0:c.call(r,t,r,u,o);if(_!==Cp)return _}if(u&&!o){const _=im(u,r);if(_!==void 0)return _}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=nm(t,t.typeName,r),x=typeof m=="function"?rt(m(),r):m;if(x&&om(t,r,x),r.postProcess){const _=r.postProcess(x,t,r);return f.jsonSchema=x,_}return f.jsonSchema=x,x}var im=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:rm(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((o,c)=>r.currentPath[c]===o)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),cn()):r.$refStrategy==="seen"?cn():void 0}},om=(t,r,o)=>(t.description&&(o.description=t.description),o),sm=t=>{const r=bp(t),o=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:o,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,u])=>[u._def,{def:u._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},am=(t,r)=>{var o;const c=sm(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[C,A])=>{var P;return{...g,[C]:(P=rt(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,C]},!0))!=null?P:cn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(o=rt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:cn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(m.title=x);const _=f===void 0?u?{...m,[c.definitionPath]:u}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...u,[f]:m}};return _.$schema="http://json-schema.org/draft-07/schema#",_},Ro=Symbol.for("vercel.ai.schema");function ze(t){let r;return()=>(r==null&&(r=t()),r)}function $i(t,{validate:r}={}){return{[Ro]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function lm(t){return typeof t=="object"&&t!==null&&Ro in t&&t[Ro]===!0&&"jsonSchema"in t&&"validate"in t}function Qo(t){return t==null?$i({properties:{},additionalProperties:!1}):lm(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Fe(t):cm(t):t()}function cm(t){return $i(()=>Ko(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const o=await t["~standard"].validate(r);return"value"in o?{success:!0,value:o.value}:{success:!1,error:new cr({value:r,cause:o.issues})}}})}function um(t,r){var o;const c=(o=void 0)!=null?o:!1;return $i(()=>am(t,{$refStrategy:c?"root":"none"}),{validate:async u=>{const f=await t.safeParseAsync(u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dm(t,r){var o;const c=(o=void 0)!=null?o:!1;return $i(()=>Ko($f(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await dc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function fm(t){return"_zod"in t}function Fe(t,r){return fm(t)?dm(t):um(t)}async function Wt({value:t,schema:r,context:o}){const c=await Nr({value:t,schema:r,context:o});if(!c.success)throw cr.wrap({value:t,cause:c.error,context:o});return c.value}async function Nr({value:t,schema:r,context:o}){const c=Qo(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const u=await c.validate(t);return u.success?{success:!0,value:u.value,rawValue:t}:{success:!1,error:cr.wrap({value:t,cause:u.error,context:o}),rawValue:t}}catch(u){return{success:!1,error:cr.wrap({value:t,cause:u,context:o}),rawValue:t}}}async function hm({text:t,schema:r}){try{const o=Jo(t);return r==null?o:Wt({value:o,schema:r})}catch(o){throw Oi.isInstance(o)||cr.isInstance(o)?o:new Oi({text:t,cause:o})}}async function Yn({text:t,schema:r}){try{const o=Jo(t);return r==null?{success:!0,value:o,rawValue:o}:await Nr({value:o,schema:r})}catch(o){return{success:!1,error:Oi.isInstance(o)?o:new Oi({text:t,cause:o}),rawValue:void 0}}}function va(t){try{return Jo(t),!0}catch{return!1}}function pm({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new xc).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await Yn({text:o,schema:r}))}}))}async function Bn({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Nr({value:r[t],schema:o});if(!c.success)throw new Ol({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var mm=()=>globalThis.fetch,Ln=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>Nc({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),Tc=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>Nc({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),Nc=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=mm()})=>{try{const x=await m(t,{method:"POST",headers:bc(r,`ai-sdk/provider-utils/${mp}`,hp()),body:o.content,signal:f}),_=ii(x);if(!x.ok){let g;try{g=await u({response:x,url:t,requestBodyValues:o.values})}catch(C){throw No(C)||sn.isInstance(C)?C:new sn({message:"Failed to process error response",cause:C,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:o.values})}catch(g){throw g instanceof Error&&(No(g)||sn.isInstance(g))?g:new sn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}}catch(x){throw fp({error:x,url:t,requestBodyValues:o.values})}};function gm({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:_,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:_})}function Fn({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:_,onInputAvailable:g,...C})=>({type:"provider",id:t,args:C,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:_,onInputAvailable:g,supportsDeferredResults:c})}async function Oc(t){return typeof t=="function"&&(t=t()),Promise.resolve(t)}var xm=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),x=ii(c);if(m.trim()==="")return{responseHeaders:x,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:o?.(c)})};try{const _=await hm({text:m,schema:t});return{responseHeaders:x,value:new sn({message:r(_),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:_,isRetryable:o?.(c,_)})}}catch{return{responseHeaders:x,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:o?.(c)})}}},es=t=>async({response:r})=>{const o=ii(r);if(r.body==null)throw new Dd({});return{responseHeaders:o,value:pm({stream:r.body,schema:t})}},ur=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await Yn({text:u,schema:t}),m=ii(r);if(!f.success)throw new sn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},ym=()=>async({response:t,url:r,requestBodyValues:o})=>{const c=ii(t);if(!t.body)throw new sn({message:"Response body is empty",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const u=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(u)}}catch(u){throw new sn({message:"Failed to read response as array buffer",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:u})}};function wm(t){return t?.replace(/\/$/,"")}var Ci=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Rc(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var _m=Object.defineProperty,vm=(t,r)=>{for(var o in r)_m(t,o,{get:r[o],enumerable:!0})},kc="AI_NoObjectGeneratedError",Mc=`vercel.ai.error.${kc}`,Cm=Symbol.for(Mc),Dc,Gn=class extends xt{constructor({message:t="No object generated.",cause:r,text:o,response:c,usage:u,finishReason:f}){super({name:kc,message:t,cause:r}),this[Dc]=!0,this.text=o,this.response=c,this.usage=u,this.finishReason=f}static isInstance(t){return xt.hasMarker(t,Mc)}};Dc=Cm;var Pc=Pe([w(),Di(Uint8Array),Di(ArrayBuffer),Gh(t=>{var r,o;return(o=(r=globalThis.Buffer)==null?void 0:r.isBuffer(t))!=null?o:!1},{message:"Must be a Buffer"})]),Kr=Xo(()=>Pe([hc(),w(),ee(),Tt(),gt(w(),Kr.optional()),ye(Kr)])),bt=gt(w(),gt(w(),Kr.optional())),Bc=S({type:G("text"),text:w(),providerOptions:bt.optional()}),bm=S({type:G("image"),image:Pe([Pc,Di(URL)]),mediaType:w().optional(),providerOptions:bt.optional()}),Lc=S({type:G("file"),data:Pe([Pc,Di(URL)]),filename:w().optional(),mediaType:w(),providerOptions:bt.optional()}),Em=S({type:G("reasoning"),text:w(),providerOptions:bt.optional()}),Am=S({type:G("tool-call"),toolCallId:w(),toolName:w(),input:Tr(),providerOptions:bt.optional(),providerExecuted:Tt().optional()}),Im=lt("type",[S({type:G("text"),value:w(),providerOptions:bt.optional()}),S({type:G("json"),value:Kr,providerOptions:bt.optional()}),S({type:G("execution-denied"),reason:w().optional(),providerOptions:bt.optional()}),S({type:G("error-text"),value:w(),providerOptions:bt.optional()}),S({type:G("error-json"),value:Kr,providerOptions:bt.optional()}),S({type:G("content"),value:ye(Pe([S({type:G("text"),text:w(),providerOptions:bt.optional()}),S({type:G("media"),data:w(),mediaType:w()}),S({type:G("file-data"),data:w(),mediaType:w(),filename:w().optional(),providerOptions:bt.optional()}),S({type:G("file-url"),url:w(),providerOptions:bt.optional()}),S({type:G("file-id"),fileId:Pe([w(),gt(w(),w())]),providerOptions:bt.optional()}),S({type:G("image-data"),data:w(),mediaType:w(),providerOptions:bt.optional()}),S({type:G("image-url"),url:w(),providerOptions:bt.optional()}),S({type:G("image-file-id"),fileId:Pe([w(),gt(w(),w())]),providerOptions:bt.optional()}),S({type:G("custom"),providerOptions:bt.optional()})]))})]),Fc=S({type:G("tool-result"),toolCallId:w(),toolName:w(),output:Im,providerOptions:bt.optional()}),Sm=S({type:G("tool-approval-request"),approvalId:w(),toolCallId:w()}),Tm=S({type:G("tool-approval-response"),approvalId:w(),approved:Tt(),reason:w().optional()}),Nm=S({role:G("system"),content:w(),providerOptions:bt.optional()}),Om=S({role:G("user"),content:Pe([w(),ye(Pe([Bc,bm,Lc]))]),providerOptions:bt.optional()}),Rm=S({role:G("assistant"),content:Pe([w(),ye(Pe([Bc,Lc,Em,Am,Fc,Sm]))]),providerOptions:bt.optional()}),km=S({role:G("tool"),content:ye(Pe([Fc,Tm])),providerOptions:bt.optional()});Pe([Nm,Om,Rm,km]);var Mm={};vm(Mm,{array:()=>Lm,choice:()=>Fm,json:()=>Um,object:()=>Bm,text:()=>Pm});function Dm(t){const r=["ROOT"];let o=-1,c=null;function u(_,g,C){switch(_){case'"':{o=g,r.pop(),r.push(C),r.push("INSIDE_STRING");break}case"f":case"t":case"n":{o=g,c=g,r.pop(),r.push(C),r.push("INSIDE_LITERAL");break}case"-":{r.pop(),r.push(C),r.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=g,r.pop(),r.push(C),r.push("INSIDE_NUMBER");break}case"{":{o=g,r.pop(),r.push(C),r.push("INSIDE_OBJECT_START");break}case"[":{o=g,r.pop(),r.push(C),r.push("INSIDE_ARRAY_START");break}}}function f(_,g){switch(_){case",":{r.pop(),r.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{o=g,r.pop();break}}}function m(_,g){switch(_){case",":{r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=g,r.pop();break}}}for(let _=0;_<t.length;_++){const g=t[_];switch(r[r.length-1]){case"ROOT":u(g,_,"FINISH");break;case"INSIDE_OBJECT_START":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_KEY");break}case"}":{o=_,r.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(g){case'"':{r.pop(),r.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(g){case":":{r.pop(),r.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{u(g,_,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{f(g,_);break}case"INSIDE_STRING":{switch(g){case'"':{r.pop(),o=_;break}case"\\":{r.push("INSIDE_STRING_ESCAPE");break}default:o=_}break}case"INSIDE_ARRAY_START":{switch(g){case"]":{o=_,r.pop();break}default:{o=_,u(g,_,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(g){case",":{r.pop(),r.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{o=_,r.pop();break}default:{o=_;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{u(g,_,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{r.pop(),o=_;break}case"INSIDE_NUMBER":{switch(g){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{o=_;break}case"e":case"E":case"-":case".":break;case",":{r.pop(),r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&m(g,_),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&f(g,_);break}case"}":{r.pop(),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&f(g,_);break}case"]":{r.pop(),r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&m(g,_);break}default:{r.pop();break}}break}case"INSIDE_LITERAL":{const A=t.substring(c,_+1);!"false".startsWith(A)&&!"true".startsWith(A)&&!"null".startsWith(A)?(r.pop(),r[r.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?f(g,_):r[r.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&m(g,_)):o=_;break}}}let x=t.slice(0,o+1);for(let _=r.length-1;_>=0;_--)switch(r[_]){case"INSIDE_STRING":{x+='"';break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{x+="}";break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{x+="]";break}case"INSIDE_LITERAL":{const C=t.substring(c,t.length);"true".startsWith(C)?x+="true".slice(C.length):"false".startsWith(C)?x+="false".slice(C.length):"null".startsWith(C)&&(x+="null".slice(C.length))}}return x}async function Vi(t){if(t===void 0)return{value:void 0,state:"undefined-input"};let r=await Yn({text:t});return r.success?{value:r.value,state:"successful-parse"}:(r=await Yn({text:Dm(t)}),r.success?{value:r.value,state:"repaired-parse"}:{value:void 0,state:"failed-parse"})}var Pm=()=>({name:"text",responseFormat:Promise.resolve({type:"text"}),async parseCompleteOutput({text:t}){return t},async parsePartialOutput({text:t}){return{partial:t}},createElementStreamTransform(){}}),Bm=({schema:t,name:r,description:o})=>{const c=Qo(t);return{name:"object",responseFormat:Oc(c.jsonSchema).then(u=>({type:"json",schema:u,...r!=null&&{name:r},...o!=null&&{description:o}})),async parseCompleteOutput({text:u},f){const m=await Yn({text:u});if(!m.success)throw new Gn({message:"No object generated: could not parse the response.",cause:m.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});const x=await Nr({value:m.value,schema:c});if(!x.success)throw new Gn({message:"No object generated: response did not match schema.",cause:x.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});return x.value},async parsePartialOutput({text:u}){const f=await Vi(u);switch(f.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return{partial:f.value}}},createElementStreamTransform(){}}},Lm=({element:t,name:r,description:o})=>{const c=Qo(t);return{name:"array",responseFormat:Oc(c.jsonSchema).then(u=>{const{$schema:f,...m}=u;return{type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{elements:{type:"array",items:m}},required:["elements"],additionalProperties:!1},...r!=null&&{name:r},...o!=null&&{description:o}}}),async parseCompleteOutput({text:u},f){const m=await Yn({text:u});if(!m.success)throw new Gn({message:"No object generated: could not parse the response.",cause:m.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});const x=m.value;if(x==null||typeof x!="object"||!("elements"in x)||!Array.isArray(x.elements))throw new Gn({message:"No object generated: response did not match schema.",cause:new cr({value:x,cause:"response must be an object with an elements array"}),text:u,response:f.response,usage:f.usage,finishReason:f.finishReason});for(const _ of x.elements){const g=await Nr({value:_,schema:c});if(!g.success)throw new Gn({message:"No object generated: response did not match schema.",cause:g.error,text:u,response:f.response,usage:f.usage,finishReason:f.finishReason})}return x.elements},async parsePartialOutput({text:u}){const f=await Vi(u);switch(f.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const m=f.value;if(m==null||typeof m!="object"||!("elements"in m)||!Array.isArray(m.elements))return;const x=f.state==="repaired-parse"&&m.elements.length>0?m.elements.slice(0,-1):m.elements,_=[];for(const g of x){const C=await Nr({value:g,schema:c});C.success&&_.push(C.value)}return{partial:_}}}},createElementStreamTransform(){let u=0;return new TransformStream({transform({partialOutput:f},m){if(f!=null)for(;u<f.length;u++)m.enqueue(f[u])}})}}},Fm=({options:t,name:r,description:o})=>({name:"choice",responseFormat:Promise.resolve({type:"json",schema:{$schema:"http://json-schema.org/draft-07/schema#",type:"object",properties:{result:{type:"string",enum:t}},required:["result"],additionalProperties:!1},...r!=null&&{name:r},...o!=null&&{description:o}}),async parseCompleteOutput({text:c},u){const f=await Yn({text:c});if(!f.success)throw new Gn({message:"No object generated: could not parse the response.",cause:f.error,text:c,response:u.response,usage:u.usage,finishReason:u.finishReason});const m=f.value;if(m==null||typeof m!="object"||!("result"in m)||typeof m.result!="string"||!t.includes(m.result))throw new Gn({message:"No object generated: response did not match schema.",cause:new cr({value:m,cause:"response must be an object that contains a choice value."}),text:c,response:u.response,usage:u.usage,finishReason:u.finishReason});return m.result},async parsePartialOutput({text:c}){const u=await Vi(c);switch(u.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":{const f=u.value;if(f==null||typeof f!="object"||!("result"in f)||typeof f.result!="string")return;const m=t.filter(x=>x.startsWith(f.result));return u.state==="successful-parse"?m.includes(f.result)?{partial:f.result}:void 0:m.length===1?{partial:m[0]}:void 0}}},createElementStreamTransform(){}}),Um=({name:t,description:r}={})=>({name:"json",responseFormat:Promise.resolve({type:"json",...t!=null&&{name:t},...r!=null&&{description:r}}),async parseCompleteOutput({text:o},c){const u=await Yn({text:o});if(!u.success)throw new Gn({message:"No object generated: could not parse the response.",cause:u.error,text:o,response:c.response,usage:c.usage,finishReason:c.finishReason});return u.value},async parsePartialOutput({text:o}){const c=await Vi(o);switch(c.state){case"failed-parse":case"undefined-input":return;case"repaired-parse":case"successful-parse":return c.value===void 0?void 0:{partial:c.value}}},createElementStreamTransform(){}});oi({prefix:"aitxt",size:24});(class extends TransformStream{constructor(){super({transform(t,r){r.enqueue(`data: ${JSON.stringify(t)}
|
|
39
39
|
|
|
40
40
|
`)},flush(t){t.enqueue(`data: [DONE]
|
|
41
41
|
|
|
42
|
-
`)}})}});oi({prefix:"aitxt",size:24});oi({prefix:"aiobj",size:24});oi({prefix:"aiobj",size:24});var Ni={exports:{}},zm=Ni.exports,Ca;function $m(){return Ca||(Ca=1,(function(t,r){(function(o,c){t.exports=c()})(zm,(function(){var o=1e3,c=6e4,u=36e5,f="millisecond",p="second",x="minute",_="hour",g="day",C="week",A="month",B="quarter",O="year",k="date",P="Invalid Date",L=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,Y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,Z={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(X){var D=["th","st","nd","rd"],K=X%100;return"["+X+(D[(K-20)%10]||D[K]||D[0])+"]"}},$=function(X,D,K){var W=String(X);return!W||W.length>=D?X:""+Array(D+1-W.length).join(K)+X},H={s:$,z:function(X){var D=-X.utcOffset(),K=Math.abs(D),W=Math.floor(K/60),ee=K%60;return(D<=0?"+":"-")+$(W,2,"0")+":"+$(ee,2,"0")},m:function X(D,K){if(D.date()<K.date())return-X(K,D);var W=12*(K.year()-D.year())+(K.month()-D.month()),ee=D.clone().add(W,A),he=K-ee<0,ge=D.clone().add(W+(he?-1:1),A);return+(-(W+(K-ee)/(he?ee-ge:ge-ee))||0)},a:function(X){return X<0?Math.ceil(X)||0:Math.floor(X)},p:function(X){return{M:A,y:O,w:C,d:g,D:k,h:_,m:x,s:p,ms:f,Q:B}[X]||String(X||"").toLowerCase().replace(/s$/,"")},u:function(X){return X===void 0}},re="en",j={};j[re]=Z;var V="$isDayjsObject",z=function(X){return X instanceof fe||!(!X||!X[V])},M=function X(D,K,W){var ee;if(!D)return re;if(typeof D=="string"){var he=D.toLowerCase();j[he]&&(ee=he),K&&(j[he]=K,ee=he);var ge=D.split("-");if(!ee&&ge.length>1)return X(ge[0])}else{var de=D.name;j[de]=D,ee=de}return!W&&ee&&(re=ee),ee||!W&&re},we=function(X,D){if(z(X))return X.clone();var K=typeof D=="object"?D:{};return K.date=X,K.args=arguments,new fe(K)},le=H;le.l=M,le.i=z,le.w=function(X,D){return we(X,{locale:D.$L,utc:D.$u,x:D.$x,$offset:D.$offset})};var fe=(function(){function X(K){this.$L=M(K.locale,null,!0),this.parse(K),this.$x=this.$x||K.x||{},this[V]=!0}var D=X.prototype;return D.parse=function(K){this.$d=(function(W){var ee=W.date,he=W.utc;if(ee===null)return new Date(NaN);if(le.u(ee))return new Date;if(ee instanceof Date)return new Date(ee);if(typeof ee=="string"&&!/Z$/i.test(ee)){var ge=ee.match(L);if(ge){var de=ge[2]-1||0,Ce=(ge[7]||"0").substring(0,3);return he?new Date(Date.UTC(ge[1],de,ge[3]||1,ge[4]||0,ge[5]||0,ge[6]||0,Ce)):new Date(ge[1],de,ge[3]||1,ge[4]||0,ge[5]||0,ge[6]||0,Ce)}}return new Date(ee)})(K),this.init()},D.init=function(){var K=this.$d;this.$y=K.getFullYear(),this.$M=K.getMonth(),this.$D=K.getDate(),this.$W=K.getDay(),this.$H=K.getHours(),this.$m=K.getMinutes(),this.$s=K.getSeconds(),this.$ms=K.getMilliseconds()},D.$utils=function(){return le},D.isValid=function(){return this.$d.toString()!==P},D.isSame=function(K,W){var ee=we(K);return this.startOf(W)<=ee&&ee<=this.endOf(W)},D.isAfter=function(K,W){return we(K)<this.startOf(W)},D.isBefore=function(K,W){return this.endOf(W)<we(K)},D.$g=function(K,W,ee){return le.u(K)?this[W]:this.set(ee,K)},D.unix=function(){return Math.floor(this.valueOf()/1e3)},D.valueOf=function(){return this.$d.getTime()},D.startOf=function(K,W){var ee=this,he=!!le.u(W)||W,ge=le.p(K),de=function(Ne,ot){var Xe=le.w(ee.$u?Date.UTC(ee.$y,ot,Ne):new Date(ee.$y,ot,Ne),ee);return he?Xe:Xe.endOf(g)},Ce=function(Ne,ot){return le.w(ee.toDate()[Ne].apply(ee.toDate("s"),(he?[0,0,0,0]:[23,59,59,999]).slice(ot)),ee)},Ve=this.$W,Me=this.$M,Ye=this.$D,ie="set"+(this.$u?"UTC":"");switch(ge){case O:return he?de(1,0):de(31,11);case A:return he?de(1,Me):de(0,Me+1);case C:var ke=this.$locale().weekStart||0,Ae=(Ve<ke?Ve+7:Ve)-ke;return de(he?Ye-Ae:Ye+(6-Ae),Me);case g:case k:return Ce(ie+"Hours",0);case _:return Ce(ie+"Minutes",1);case x:return Ce(ie+"Seconds",2);case p:return Ce(ie+"Milliseconds",3);default:return this.clone()}},D.endOf=function(K){return this.startOf(K,!1)},D.$set=function(K,W){var ee,he=le.p(K),ge="set"+(this.$u?"UTC":""),de=(ee={},ee[g]=ge+"Date",ee[k]=ge+"Date",ee[A]=ge+"Month",ee[O]=ge+"FullYear",ee[_]=ge+"Hours",ee[x]=ge+"Minutes",ee[p]=ge+"Seconds",ee[f]=ge+"Milliseconds",ee)[he],Ce=he===g?this.$D+(W-this.$W):W;if(he===A||he===O){var Ve=this.clone().set(k,1);Ve.$d[de](Ce),Ve.init(),this.$d=Ve.set(k,Math.min(this.$D,Ve.daysInMonth())).$d}else de&&this.$d[de](Ce);return this.init(),this},D.set=function(K,W){return this.clone().$set(K,W)},D.get=function(K){return this[le.p(K)]()},D.add=function(K,W){var ee,he=this;K=Number(K);var ge=le.p(W),de=function(Me){var Ye=we(he);return le.w(Ye.date(Ye.date()+Math.round(Me*K)),he)};if(ge===A)return this.set(A,this.$M+K);if(ge===O)return this.set(O,this.$y+K);if(ge===g)return de(1);if(ge===C)return de(7);var Ce=(ee={},ee[x]=c,ee[_]=u,ee[p]=o,ee)[ge]||1,Ve=this.$d.getTime()+K*Ce;return le.w(Ve,this)},D.subtract=function(K,W){return this.add(-1*K,W)},D.format=function(K){var W=this,ee=this.$locale();if(!this.isValid())return ee.invalidDate||P;var he=K||"YYYY-MM-DDTHH:mm:ssZ",ge=le.z(this),de=this.$H,Ce=this.$m,Ve=this.$M,Me=ee.weekdays,Ye=ee.months,ie=ee.meridiem,ke=function(ot,Xe,$t,Ue){return ot&&(ot[Xe]||ot(W,he))||$t[Xe].slice(0,Ue)},Ae=function(ot){return le.s(de%12||12,ot,"0")},Ne=ie||function(ot,Xe,$t){var Ue=ot<12?"AM":"PM";return $t?Ue.toLowerCase():Ue};return he.replace(Y,(function(ot,Xe){return Xe||(function($t){switch($t){case"YY":return String(W.$y).slice(-2);case"YYYY":return le.s(W.$y,4,"0");case"M":return Ve+1;case"MM":return le.s(Ve+1,2,"0");case"MMM":return ke(ee.monthsShort,Ve,Ye,3);case"MMMM":return ke(Ye,Ve);case"D":return W.$D;case"DD":return le.s(W.$D,2,"0");case"d":return String(W.$W);case"dd":return ke(ee.weekdaysMin,W.$W,Me,2);case"ddd":return ke(ee.weekdaysShort,W.$W,Me,3);case"dddd":return Me[W.$W];case"H":return String(de);case"HH":return le.s(de,2,"0");case"h":return Ae(1);case"hh":return Ae(2);case"a":return Ne(de,Ce,!0);case"A":return Ne(de,Ce,!1);case"m":return String(Ce);case"mm":return le.s(Ce,2,"0");case"s":return String(W.$s);case"ss":return le.s(W.$s,2,"0");case"SSS":return le.s(W.$ms,3,"0");case"Z":return ge}return null})(ot)||ge.replace(":","")}))},D.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},D.diff=function(K,W,ee){var he,ge=this,de=le.p(W),Ce=we(K),Ve=(Ce.utcOffset()-this.utcOffset())*c,Me=this-Ce,Ye=function(){return le.m(ge,Ce)};switch(de){case O:he=Ye()/12;break;case A:he=Ye();break;case B:he=Ye()/3;break;case C:he=(Me-Ve)/6048e5;break;case g:he=(Me-Ve)/864e5;break;case _:he=Me/u;break;case x:he=Me/c;break;case p:he=Me/o;break;default:he=Me}return ee?he:le.a(he)},D.daysInMonth=function(){return this.endOf(A).$D},D.$locale=function(){return j[this.$L]},D.locale=function(K,W){if(!K)return this.$L;var ee=this.clone(),he=M(K,W,!0);return he&&(ee.$L=he),ee},D.clone=function(){return le.w(this.$d,this)},D.toDate=function(){return new Date(this.valueOf())},D.toJSON=function(){return this.isValid()?this.toISOString():null},D.toISOString=function(){return this.$d.toISOString()},D.toString=function(){return this.$d.toUTCString()},X})(),ae=fe.prototype;return we.prototype=ae,[["$ms",f],["$s",p],["$m",x],["$H",_],["$W",g],["$M",A],["$y",O],["$D",k]].forEach((function(X){ae[X[1]]=function(D){return this.$g(D,X[0],X[1])}})),we.extend=function(X,D){return X.$i||(X(D,fe,we),X.$i=!0),we},we.locale=M,we.isDayjs=z,we.unix=function(X){return we(1e3*X)},we.en=j[re],we.Ls=j,we.p={},we}))})(Ni)),Ni.exports}var Vm=$m();const Zm=Rc(Vm),jm={description:"获取今天的日期",inputSchema:Ht.z.object({}),execute:()=>({date:`当前日期: ${Zm().format("YYYY-M-D")}`})},Wm="next-sdk:page-ready",Wr=new Map,Hm=Symbol("default"),Gm=t=>{const r=Hm;return Wr.get(r)??null};function Xm(t){const{enabled:r,agent:o,installedPlugins:c,customAgentProvider:u}=t,f=Symbol("remoter-route-state"),p=typeof window<"u"&&window!==window.top,x=j=>{Wr.set(f,j)},_=()=>Wr.get(f)??null;u?.setRouteStateGetter&&u.setRouteStateGetter(_),p&&x({toolRouteMap:new Map,activeRoutes:new Set,initialized:!1});const g=new Map,C=j=>j.replace(/\/+$/,"")||"/",A=()=>_()?.toolRouteMap??Ht.getToolRouteMap(),B=()=>{const j=A(),V=new Set(j.keys());o.ignoreToolnames=o.ignoreToolnames.filter(z=>!V.has(z)),c.value.forEach(z=>{const M=g.get(z.id);M&&(z.tools=M.slice())})},O=()=>{if(!r.value){B();return}const j=_()?.activeRoutes??Ht.getActiveRoutes(),V=A(),z=new Set,M=new Set;V.forEach((le,fe)=>{M.add(fe);const ae=C(le);(j.has(ae)||j.has(le))&&z.add(fe)});const we=new Set(o.ignoreToolnames);M.forEach(le=>{we.add(le)}),z.forEach(le=>{we.delete(le)}),o.ignoreToolnames=Array.from(we),c.value.forEach(le=>{g.has(le.id)||g.set(le.id,le.tools.slice());const fe=g.get(le.id)||[];le.tools=fe.filter(ae=>M.has(ae.id)?z.has(ae.id):!0)})},k=j=>j===window||p&&j===window.parent,P=j=>{if(!k(j.source)||j.data?.type!==Wm)return;const V=_();V&&V.activeRoutes.add(C(j.data.route)),O()},L=j=>{if(!k(j.source)||j.data?.type!==Ht.MSG_PAGE_LEAVE)return;const V=_();V&&V.activeRoutes.delete(C(j.data.route)),O()},Y=j=>{if(!k(j.source)||j.data?.type!==Ht.MSG_ROUTE_STATE_INITIAL)return;const{toolRouteMap:V,activeRoutes:z}=j.data;x({toolRouteMap:new Map(V),activeRoutes:new Set(z.map(C)),initialized:!0}),O()},Z=v.watch(()=>c.value.map(j=>`${j.id}:${j.tools?.length??0}`).join("|"),(j,V)=>{if(j===V)return;const z=_();p&&(!z||!z.initialized)&&window.parent&&window.parent.postMessage({type:Ht.MSG_REMOTER_READY},"*"),O()});let $=!1;const H=()=>{$||($=!0,window.addEventListener("message",P),window.addEventListener("message",L),window.addEventListener("message",Y),p&&window.parent&&window.parent.postMessage({type:Ht.MSG_REMOTER_READY},"*"),O())},re=()=>{$&&($=!1,window.removeEventListener("message",P),window.removeEventListener("message",L),window.removeEventListener("message",Y),B(),Wr.delete(f))};v.onMounted(()=>{v.watch(r,j=>{j?H():re()},{immediate:!0})}),v.onUnmounted(()=>{re(),Z(),Wr.delete(f)})}var Uc="vercel.ai.error",qm=Symbol.for(Uc),zc,Ym=class $c extends Error{constructor({name:r,message:o,cause:c}){super(o),this[zc]=!0,this.name=r,this.cause=c}static isInstance(r){return $c.hasMarker(r,Uc)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}};zc=qm;var Bt=Ym,Vc="AI_APICallError",Zc=`vercel.ai.error.${Vc}`,Jm=Symbol.for(Zc),jc,Pn=class extends Bt{constructor({message:t,url:r,requestBodyValues:o,statusCode:c,responseHeaders:u,responseBody:f,cause:p,isRetryable:x=c!=null&&(c===408||c===409||c===429||c>=500),data:_}){super({name:Vc,message:t,cause:p}),this[jc]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=x,this.data=_}static isInstance(t){return Bt.hasMarker(t,Zc)}};jc=Jm;var Wc="AI_EmptyResponseBodyError",Hc=`vercel.ai.error.${Wc}`,Km=Symbol.for(Hc),Gc,Qm=class extends Bt{constructor({message:t="Empty response body"}={}){super({name:Wc,message:t}),this[Gc]=!0}static isInstance(t){return Bt.hasMarker(t,Hc)}};Gc=Km;function Xc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var qc="AI_InvalidArgumentError",Yc=`vercel.ai.error.${qc}`,eg=Symbol.for(Yc),Jc,Kc=class extends Bt{constructor({message:t,cause:r,argument:o}){super({name:qc,message:t,cause:r}),this[Jc]=!0,this.argument=o}static isInstance(t){return Bt.hasMarker(t,Yc)}};Jc=eg;var Qc="AI_InvalidResponseDataError",eu=`vercel.ai.error.${Qc}`,tg=Symbol.for(eu),tu,ba=class extends Bt{constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Qc,message:r}),this[tu]=!0,this.data=t}static isInstance(t){return Bt.hasMarker(t,eu)}};tu=tg;var nu="AI_JSONParseError",ru=`vercel.ai.error.${nu}`,ng=Symbol.for(ru),iu,Pi=class extends Bt{constructor({text:t,cause:r}){super({name:nu,message:`JSON parsing failed: Text: ${t}.
|
|
42
|
+
`)}})}});oi({prefix:"aitxt",size:24});oi({prefix:"aiobj",size:24});oi({prefix:"aiobj",size:24});var Ni={exports:{}},zm=Ni.exports,Ca;function $m(){return Ca||(Ca=1,(function(t,r){(function(o,c){t.exports=c()})(zm,(function(){var o=1e3,c=6e4,u=36e5,f="millisecond",m="second",x="minute",_="hour",g="day",C="week",A="month",P="quarter",O="year",k="date",B="Invalid Date",L=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,K=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,z={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(q){var D=["th","st","nd","rd"],Q=q%100;return"["+q+(D[(Q-20)%10]||D[Q]||D[0])+"]"}},$=function(q,D,Q){var j=String(q);return!j||j.length>=D?q:""+Array(D+1-j.length).join(Q)+q},W={s:$,z:function(q){var D=-q.utcOffset(),Q=Math.abs(D),j=Math.floor(Q/60),te=Q%60;return(D<=0?"+":"-")+$(j,2,"0")+":"+$(te,2,"0")},m:function q(D,Q){if(D.date()<Q.date())return-q(Q,D);var j=12*(Q.year()-D.year())+(Q.month()-D.month()),te=D.clone().add(j,A),he=Q-te<0,ge=D.clone().add(j+(he?-1:1),A);return+(-(j+(Q-te)/(he?te-ge:ge-te))||0)},a:function(q){return q<0?Math.ceil(q)||0:Math.floor(q)},p:function(q){return{M:A,y:O,w:C,d:g,D:k,h:_,m:x,s:m,ms:f,Q:P}[q]||String(q||"").toLowerCase().replace(/s$/,"")},u:function(q){return q===void 0}},X="en",H={};H[X]=z;var V="$isDayjsObject",Z=function(q){return q instanceof fe||!(!q||!q[V])},M=function q(D,Q,j){var te;if(!D)return X;if(typeof D=="string"){var he=D.toLowerCase();H[he]&&(te=he),Q&&(H[he]=Q,te=he);var ge=D.split("-");if(!te&&ge.length>1)return q(ge[0])}else{var de=D.name;H[de]=D,te=de}return!j&&te&&(X=te),te||!j&&X},we=function(q,D){if(Z(q))return q.clone();var Q=typeof D=="object"?D:{};return Q.date=q,Q.args=arguments,new fe(Q)},ce=W;ce.l=M,ce.i=Z,ce.w=function(q,D){return we(q,{locale:D.$L,utc:D.$u,x:D.$x,$offset:D.$offset})};var fe=(function(){function q(Q){this.$L=M(Q.locale,null,!0),this.parse(Q),this.$x=this.$x||Q.x||{},this[V]=!0}var D=q.prototype;return D.parse=function(Q){this.$d=(function(j){var te=j.date,he=j.utc;if(te===null)return new Date(NaN);if(ce.u(te))return new Date;if(te instanceof Date)return new Date(te);if(typeof te=="string"&&!/Z$/i.test(te)){var ge=te.match(L);if(ge){var de=ge[2]-1||0,Ce=(ge[7]||"0").substring(0,3);return he?new Date(Date.UTC(ge[1],de,ge[3]||1,ge[4]||0,ge[5]||0,ge[6]||0,Ce)):new Date(ge[1],de,ge[3]||1,ge[4]||0,ge[5]||0,ge[6]||0,Ce)}}return new Date(te)})(Q),this.init()},D.init=function(){var Q=this.$d;this.$y=Q.getFullYear(),this.$M=Q.getMonth(),this.$D=Q.getDate(),this.$W=Q.getDay(),this.$H=Q.getHours(),this.$m=Q.getMinutes(),this.$s=Q.getSeconds(),this.$ms=Q.getMilliseconds()},D.$utils=function(){return ce},D.isValid=function(){return this.$d.toString()!==B},D.isSame=function(Q,j){var te=we(Q);return this.startOf(j)<=te&&te<=this.endOf(j)},D.isAfter=function(Q,j){return we(Q)<this.startOf(j)},D.isBefore=function(Q,j){return this.endOf(j)<we(Q)},D.$g=function(Q,j,te){return ce.u(Q)?this[j]:this.set(te,Q)},D.unix=function(){return Math.floor(this.valueOf()/1e3)},D.valueOf=function(){return this.$d.getTime()},D.startOf=function(Q,j){var te=this,he=!!ce.u(j)||j,ge=ce.p(Q),de=function(Ne,ot){var Xe=ce.w(te.$u?Date.UTC(te.$y,ot,Ne):new Date(te.$y,ot,Ne),te);return he?Xe:Xe.endOf(g)},Ce=function(Ne,ot){return ce.w(te.toDate()[Ne].apply(te.toDate("s"),(he?[0,0,0,0]:[23,59,59,999]).slice(ot)),te)},Ve=this.$W,Me=this.$M,Ye=this.$D,ie="set"+(this.$u?"UTC":"");switch(ge){case O:return he?de(1,0):de(31,11);case A:return he?de(1,Me):de(0,Me+1);case C:var ke=this.$locale().weekStart||0,Ae=(Ve<ke?Ve+7:Ve)-ke;return de(he?Ye-Ae:Ye+(6-Ae),Me);case g:case k:return Ce(ie+"Hours",0);case _:return Ce(ie+"Minutes",1);case x:return Ce(ie+"Seconds",2);case m:return Ce(ie+"Milliseconds",3);default:return this.clone()}},D.endOf=function(Q){return this.startOf(Q,!1)},D.$set=function(Q,j){var te,he=ce.p(Q),ge="set"+(this.$u?"UTC":""),de=(te={},te[g]=ge+"Date",te[k]=ge+"Date",te[A]=ge+"Month",te[O]=ge+"FullYear",te[_]=ge+"Hours",te[x]=ge+"Minutes",te[m]=ge+"Seconds",te[f]=ge+"Milliseconds",te)[he],Ce=he===g?this.$D+(j-this.$W):j;if(he===A||he===O){var Ve=this.clone().set(k,1);Ve.$d[de](Ce),Ve.init(),this.$d=Ve.set(k,Math.min(this.$D,Ve.daysInMonth())).$d}else de&&this.$d[de](Ce);return this.init(),this},D.set=function(Q,j){return this.clone().$set(Q,j)},D.get=function(Q){return this[ce.p(Q)]()},D.add=function(Q,j){var te,he=this;Q=Number(Q);var ge=ce.p(j),de=function(Me){var Ye=we(he);return ce.w(Ye.date(Ye.date()+Math.round(Me*Q)),he)};if(ge===A)return this.set(A,this.$M+Q);if(ge===O)return this.set(O,this.$y+Q);if(ge===g)return de(1);if(ge===C)return de(7);var Ce=(te={},te[x]=c,te[_]=u,te[m]=o,te)[ge]||1,Ve=this.$d.getTime()+Q*Ce;return ce.w(Ve,this)},D.subtract=function(Q,j){return this.add(-1*Q,j)},D.format=function(Q){var j=this,te=this.$locale();if(!this.isValid())return te.invalidDate||B;var he=Q||"YYYY-MM-DDTHH:mm:ssZ",ge=ce.z(this),de=this.$H,Ce=this.$m,Ve=this.$M,Me=te.weekdays,Ye=te.months,ie=te.meridiem,ke=function(ot,Xe,$t,Ue){return ot&&(ot[Xe]||ot(j,he))||$t[Xe].slice(0,Ue)},Ae=function(ot){return ce.s(de%12||12,ot,"0")},Ne=ie||function(ot,Xe,$t){var Ue=ot<12?"AM":"PM";return $t?Ue.toLowerCase():Ue};return he.replace(K,(function(ot,Xe){return Xe||(function($t){switch($t){case"YY":return String(j.$y).slice(-2);case"YYYY":return ce.s(j.$y,4,"0");case"M":return Ve+1;case"MM":return ce.s(Ve+1,2,"0");case"MMM":return ke(te.monthsShort,Ve,Ye,3);case"MMMM":return ke(Ye,Ve);case"D":return j.$D;case"DD":return ce.s(j.$D,2,"0");case"d":return String(j.$W);case"dd":return ke(te.weekdaysMin,j.$W,Me,2);case"ddd":return ke(te.weekdaysShort,j.$W,Me,3);case"dddd":return Me[j.$W];case"H":return String(de);case"HH":return ce.s(de,2,"0");case"h":return Ae(1);case"hh":return Ae(2);case"a":return Ne(de,Ce,!0);case"A":return Ne(de,Ce,!1);case"m":return String(Ce);case"mm":return ce.s(Ce,2,"0");case"s":return String(j.$s);case"ss":return ce.s(j.$s,2,"0");case"SSS":return ce.s(j.$ms,3,"0");case"Z":return ge}return null})(ot)||ge.replace(":","")}))},D.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},D.diff=function(Q,j,te){var he,ge=this,de=ce.p(j),Ce=we(Q),Ve=(Ce.utcOffset()-this.utcOffset())*c,Me=this-Ce,Ye=function(){return ce.m(ge,Ce)};switch(de){case O:he=Ye()/12;break;case A:he=Ye();break;case P:he=Ye()/3;break;case C:he=(Me-Ve)/6048e5;break;case g:he=(Me-Ve)/864e5;break;case _:he=Me/u;break;case x:he=Me/c;break;case m:he=Me/o;break;default:he=Me}return te?he:ce.a(he)},D.daysInMonth=function(){return this.endOf(A).$D},D.$locale=function(){return H[this.$L]},D.locale=function(Q,j){if(!Q)return this.$L;var te=this.clone(),he=M(Q,j,!0);return he&&(te.$L=he),te},D.clone=function(){return ce.w(this.$d,this)},D.toDate=function(){return new Date(this.valueOf())},D.toJSON=function(){return this.isValid()?this.toISOString():null},D.toISOString=function(){return this.$d.toISOString()},D.toString=function(){return this.$d.toUTCString()},q})(),ae=fe.prototype;return we.prototype=ae,[["$ms",f],["$s",m],["$m",x],["$H",_],["$W",g],["$M",A],["$y",O],["$D",k]].forEach((function(q){ae[q[1]]=function(D){return this.$g(D,q[0],q[1])}})),we.extend=function(q,D){return q.$i||(q(D,fe,we),q.$i=!0),we},we.locale=M,we.isDayjs=Z,we.unix=function(q){return we(1e3*q)},we.en=H[X],we.Ls=H,we.p={},we}))})(Ni)),Ni.exports}var Vm=$m();const Zm=Rc(Vm),jm={description:"获取今天的日期",inputSchema:Ht.z.object({}),execute:()=>({date:`当前日期: ${Zm().format("YYYY-M-D")}`})},Wm="next-sdk:page-ready",Wr=new Map,Hm=Symbol("default"),Gm=t=>{const r=Hm;return Wr.get(r)??null};function Xm(t){const{enabled:r,installedPlugins:o,customAgentProvider:c}=t,u=Symbol("remoter-route-state"),f=typeof window<"u"&&window!==window.top,m=X=>{Wr.set(u,X)},x=()=>Wr.get(u)??null;c?.setRouteStateGetter&&c.setRouteStateGetter(x),f&&m({toolRouteMap:new Map,activeRoutes:new Set,initialized:!1});const _=new Map,g=X=>X.replace(/\/+$/,"")||"/",C=()=>x()?.toolRouteMap??Ht.getToolRouteMap(),A=()=>{o.value.forEach(X=>{const H=_.get(X.id);H&&(X.tools=H.slice())})},P=()=>{if(!r.value){A();return}const X=x()?.activeRoutes??Ht.getActiveRoutes(),H=C(),V=new Set,Z=new Set;H.forEach((M,we)=>{Z.add(we);const ce=g(M);(X.has(ce)||X.has(M))&&V.add(we)}),o.value.forEach(M=>{_.has(M.id)||_.set(M.id,M.tools.slice());const we=_.get(M.id)||[];M.tools=we.filter(ce=>Z.has(ce.id)?V.has(ce.id):!0)})},O=X=>X===window||f&&X===window.parent,k=X=>{if(!O(X.source)||X.data?.type!==Wm)return;const H=x();H&&H.activeRoutes.add(g(X.data.route)),P()},B=X=>{if(!O(X.source)||X.data?.type!==Ht.MSG_PAGE_LEAVE)return;const H=x();H&&H.activeRoutes.delete(g(X.data.route)),P()},L=X=>{if(!O(X.source)||X.data?.type!==Ht.MSG_ROUTE_STATE_INITIAL)return;const{toolRouteMap:H,activeRoutes:V}=X.data;m({toolRouteMap:new Map(H),activeRoutes:new Set(V.map(g)),initialized:!0}),P()},K=v.watch(()=>o.value.map(X=>`${X.id}:${X.tools?.length??0}`).join("|"),(X,H)=>{if(X===H)return;const V=x();f&&(!V||!V.initialized)&&window.parent&&window.parent.postMessage({type:Ht.MSG_REMOTER_READY},"*"),P()});let z=!1;const $=()=>{z||(z=!0,window.addEventListener("message",k),window.addEventListener("message",B),window.addEventListener("message",L),f&&window.parent&&window.parent.postMessage({type:Ht.MSG_REMOTER_READY},"*"),P())},W=()=>{z&&(z=!1,window.removeEventListener("message",k),window.removeEventListener("message",B),window.removeEventListener("message",L),A(),Wr.delete(u))};v.onMounted(()=>{v.watch(r,X=>{X?$():W()},{immediate:!0})}),v.onUnmounted(()=>{W(),K(),Wr.delete(u)})}var Uc="vercel.ai.error",qm=Symbol.for(Uc),zc,Ym=class $c extends Error{constructor({name:r,message:o,cause:c}){super(o),this[zc]=!0,this.name=r,this.cause=c}static isInstance(r){return $c.hasMarker(r,Uc)}static hasMarker(r,o){const c=Symbol.for(o);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}};zc=qm;var Bt=Ym,Vc="AI_APICallError",Zc=`vercel.ai.error.${Vc}`,Jm=Symbol.for(Zc),jc,Pn=class extends Bt{constructor({message:t,url:r,requestBodyValues:o,statusCode:c,responseHeaders:u,responseBody:f,cause:m,isRetryable:x=c!=null&&(c===408||c===409||c===429||c>=500),data:_}){super({name:Vc,message:t,cause:m}),this[jc]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=x,this.data=_}static isInstance(t){return Bt.hasMarker(t,Zc)}};jc=Jm;var Wc="AI_EmptyResponseBodyError",Hc=`vercel.ai.error.${Wc}`,Km=Symbol.for(Hc),Gc,Qm=class extends Bt{constructor({message:t="Empty response body"}={}){super({name:Wc,message:t}),this[Gc]=!0}static isInstance(t){return Bt.hasMarker(t,Hc)}};Gc=Km;function Xc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var qc="AI_InvalidArgumentError",Yc=`vercel.ai.error.${qc}`,eg=Symbol.for(Yc),Jc,Kc=class extends Bt{constructor({message:t,cause:r,argument:o}){super({name:qc,message:t,cause:r}),this[Jc]=!0,this.argument=o}static isInstance(t){return Bt.hasMarker(t,Yc)}};Jc=eg;var Qc="AI_InvalidResponseDataError",eu=`vercel.ai.error.${Qc}`,tg=Symbol.for(eu),tu,ba=class extends Bt{constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Qc,message:r}),this[tu]=!0,this.data=t}static isInstance(t){return Bt.hasMarker(t,eu)}};tu=tg;var nu="AI_JSONParseError",ru=`vercel.ai.error.${nu}`,ng=Symbol.for(ru),iu,Pi=class extends Bt{constructor({text:t,cause:r}){super({name:nu,message:`JSON parsing failed: Text: ${t}.
|
|
43
43
|
Error message: ${Xc(r)}`,cause:r}),this[iu]=!0,this.text=t}static isInstance(t){return Bt.hasMarker(t,ru)}};iu=ng;var ou="AI_LoadAPIKeyError",su=`vercel.ai.error.${ou}`,rg=Symbol.for(su),au,bi=class extends Bt{constructor({message:t}){super({name:ou,message:t}),this[au]=!0}static isInstance(t){return Bt.hasMarker(t,su)}};au=rg;var lu="AI_NoSuchModelError",cu=`vercel.ai.error.${lu}`,ig=Symbol.for(cu),uu,Ea=class extends Bt{constructor({errorName:t=lu,modelId:r,modelType:o,message:c=`No such ${o}: ${r}`}){super({name:t,message:c}),this[uu]=!0,this.modelId=r,this.modelType=o}static isInstance(t){return Bt.hasMarker(t,cu)}};uu=ig;var du="AI_TypeValidationError",fu=`vercel.ai.error.${du}`,og=Symbol.for(fu),hu,sg=class ko extends Bt{constructor({value:r,cause:o}){super({name:du,message:`Type validation failed: Value: ${JSON.stringify(r)}.
|
|
44
|
-
Error message: ${Xc(o)}`,cause:o}),this[hu]=!0,this.value=r}static isInstance(r){return Bt.hasMarker(r,fu)}static wrap({value:r,cause:o}){return ko.isInstance(o)&&o.value===r?o:new ko({value:r,cause:o})}};hu=og;var Qr=sg,pu="AI_UnsupportedFunctionalityError",mu=`vercel.ai.error.${pu}`,ag=Symbol.for(mu),gu,xu=class extends Bt{constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:pu,message:r}),this[gu]=!0,this.functionality=t}static isInstance(t){return Bt.hasMarker(t,mu)}};gu=ag;function Aa(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Zi(t){return Object.fromEntries([...t.headers])}var lg=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,p=new Array(r);for(let x=0;x<r;x++)p[x]=o[Math.random()*f|0];return p.join("")};if(t==null)return u;if(o.includes(c))throw new Kc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Ei=lg();function Mo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var cg=["fetch failed","failed to fetch"];function ug({error:t,url:r,requestBodyValues:o}){if(Mo(t))return t;if(t instanceof TypeError&&cg.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Pn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function dg(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fg(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function yu(t,...r){const o=new Headers(fg(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var hg="3.0.18";function pg({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new bi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new bi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new bi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new bi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var mg=/"__proto__"\s*:/,gg=/"constructor"\s*:/;function Ia(t){const r=JSON.parse(t);return r===null||typeof r!="object"||mg.test(t)===!1&&gg.test(t)===!1?r:xg(r)}function xg(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function ts(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Ia(t)}try{return Ia(t)}finally{Error.stackTraceLimit=r}}var Do=Symbol.for("vercel.ai.validator");function yg(t){return{[Do]:!0,validate:t}}function wg(t){return typeof t=="object"&&t!==null&&Do in t&&t[Do]===!0&&"validate"in t}function _g(t){return wg(t)?t:typeof t=="function"?t():vg(t)}function vg(t){return yg(async r=>{const o=await t["~standard"].validate(r);return o.issues==null?{success:!0,value:o.value}:{success:!1,error:new Qr({value:r,cause:o.issues})}})}async function Cg({value:t,schema:r}){const o=await ei({value:t,schema:r});if(!o.success)throw Qr.wrap({value:t,cause:o.error});return o.value}async function ei({value:t,schema:r}){const o=_g(r);try{if(o.validate==null)return{success:!0,value:t,rawValue:t};const c=await o.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Qr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Qr.wrap({value:t,cause:c}),rawValue:t}}}async function bg({text:t,schema:r}){try{const o=ts(t);return r==null?o:Cg({value:o,schema:r})}catch(o){throw Pi.isInstance(o)||Qr.isInstance(o)?o:new Pi({text:t,cause:o})}}async function wu({text:t,schema:r}){try{const o=ts(t);return r==null?{success:!0,value:o,rawValue:o}:await ei({value:o,schema:r})}catch(o){return{success:!1,error:Pi.isInstance(o)?o:new Pi({text:t,cause:o}),rawValue:void 0}}}function Sa(t){try{return ts(t),!0}catch{return!1}}function Eg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new xc).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await wu({text:o,schema:r}))}}))}async function Ta({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await ei({value:r[t],schema:o});if(!c.success)throw new Kc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Ag=()=>globalThis.fetch,Na=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p})=>Ig({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:p}),Ig=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:p=Ag()})=>{try{const x=await p(t,{method:"POST",headers:yu(r,`ai-sdk/provider-utils/${hg}`,dg()),body:o.content,signal:f}),_=Zi(x);if(!x.ok){let g;try{g=await u({response:x,url:t,requestBodyValues:o.values})}catch(C){throw Mo(C)||Pn.isInstance(C)?C:new Pn({message:"Failed to process error response",cause:C,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:o.values})}catch(g){throw g instanceof Error&&(Mo(g)||Pn.isInstance(g))?g:new Pn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}}catch(x){throw ug({error:x,url:t,requestBodyValues:o.values})}},Sg=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const p=await c.text(),x=Zi(c);if(p.trim()==="")return{responseHeaders:x,value:new Pn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,isRetryable:o?.(c)})};try{const _=await bg({text:p,schema:t});return{responseHeaders:x,value:new Pn({message:r(_),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,data:_,isRetryable:o?.(c,_)})}}catch{return{responseHeaders:x,value:new Pn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:p,isRetryable:o?.(c)})}}},Tg=t=>async({response:r})=>{const o=Zi(r);if(r.body==null)throw new Qm({});return{responseHeaders:o,value:Eg({stream:r.body,schema:t})}},Ng=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await wu({text:u,schema:t}),p=Zi(r);if(!f.success)throw new Pn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:p,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:p,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:Og}=globalThis;function Rg(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return Og(r)}function kg(t){return t instanceof Uint8Array?Rg(t):t}function Mg(t){return t?.replace(/\/$/,"")}function zr(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function Dg(t){const r=[];for(const{role:o,content:c,...u}of t){const f=zr({...u});switch(o){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...zr(c[0])});break}r.push({role:"user",content:c.map(p=>{const x=zr(p);switch(p.type){case"text":return{type:"text",text:p.text,...x};case"file":if(p.mediaType.startsWith("image/")){const _=p.mediaType==="image/*"?"image/jpeg":p.mediaType;return{type:"image_url",image_url:{url:p.data instanceof URL?p.data.toString():`data:${_};base64,${kg(p.data)}`},...x}}else throw new xu({functionality:`file part media type ${p.mediaType}`})}}),...f});break}case"assistant":{let p="";const x=[];for(const _ of c){const g=zr(_);switch(_.type){case"text":{p+=_.text;break}case"tool-call":{x.push({id:_.toolCallId,type:"function",function:{name:_.toolName,arguments:JSON.stringify(_.input)},...g});break}}}r.push({role:"assistant",content:p,tool_calls:x.length>0?x:void 0,...f});break}case"tool":{for(const p of c){const x=p.output;let _;switch(x.type){case"text":case"error-text":_=x.value;break;case"content":case"json":case"error-json":_=JSON.stringify(x.value);break}const g=zr(p);r.push({role:"tool",tool_call_id:p.toolCallId,content:_,...g})}break}default:{const p=o;throw new Error(`Unsupported role: ${p}`)}}}return r}function Oa({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function Ra(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var yo=S({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),Pg=S({error:S({message:w(),type:w().nullish(),param:fr().nullish(),code:Pe([w(),Q()]).nullish()})}),Bg={errorSchema:Pg,errorToMessage:t=>t.error.message};function Lg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)f.type==="provider-defined"?o.push({type:"unsupported-tool",tool:f}):c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}});if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new xu({functionality:`tool choice type: ${f}`})}}}var Fg=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:Bg;this.chunkSchema=zg(u.errorSchema),this.failedResponseHandler=Sg(u),this.supportsStructuredOutputs=(c=r.supportsStructuredOutputs)!=null?c:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,r,o;return(o=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?o:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:p,providerOptions:x,stopSequences:_,responseFormat:g,seed:C,toolChoice:A,tools:B}){var O,k,P,L;const Y=[],Z=Object.assign((O=await Ta({provider:"openai-compatible",providerOptions:x,schema:yo}))!=null?O:{},(k=await Ta({provider:this.providerOptionsName,providerOptions:x,schema:yo}))!=null?k:{});u!=null&&Y.push({type:"unsupported-setting",setting:"topK"}),g?.type==="json"&&g.schema!=null&&!this.supportsStructuredOutputs&&Y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:H,toolWarnings:re}=Lg({tools:B,toolChoice:A});return{args:{model:this.modelId,user:Z.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:p,response_format:g?.type==="json"?this.supportsStructuredOutputs===!0&&g.schema!=null?{type:"json_schema",json_schema:{schema:g.schema,name:(P=g.name)!=null?P:"response",description:g.description}}:{type:"json_object"}:void 0,stop:_,seed:C,...Object.fromEntries(Object.entries((L=x?.[this.providerOptionsName])!=null?L:{}).filter(([j])=>!Object.keys(yo.shape).includes(j))),reasoning_effort:Z.reasoningEffort,verbosity:Z.textVerbosity,messages:Dg(t),tools:$,tool_choice:H},warnings:[...Y,...re]}}async doGenerate(t){var r,o,c,u,f,p,x,_,g,C,A,B,O,k,P,L,Y;const{args:Z,warnings:$}=await this.getArgs({...t}),H=JSON.stringify(Z),{responseHeaders:re,value:j,rawValue:V}=await Na({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Aa(this.config.headers(),t.headers),body:Z,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ng(Ug),abortSignal:t.abortSignal,fetch:this.config.fetch}),z=j.choices[0],M=[],we=z.message.content;we!=null&&we.length>0&&M.push({type:"text",text:we});const le=(r=z.message.reasoning_content)!=null?r:z.message.reasoning;if(le!=null&&le.length>0&&M.push({type:"reasoning",text:le}),z.message.tool_calls!=null)for(const X of z.message.tool_calls)M.push({type:"tool-call",toolCallId:(o=X.id)!=null?o:Ei(),toolName:X.function.name,input:X.function.arguments});const fe={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:V}))},ae=(f=j.usage)==null?void 0:f.completion_tokens_details;return ae?.accepted_prediction_tokens!=null&&(fe[this.providerOptionsName].acceptedPredictionTokens=ae?.accepted_prediction_tokens),ae?.rejected_prediction_tokens!=null&&(fe[this.providerOptionsName].rejectedPredictionTokens=ae?.rejected_prediction_tokens),{content:M,finishReason:Ra(z.finish_reason),usage:{inputTokens:(x=(p=j.usage)==null?void 0:p.prompt_tokens)!=null?x:void 0,outputTokens:(g=(_=j.usage)==null?void 0:_.completion_tokens)!=null?g:void 0,totalTokens:(A=(C=j.usage)==null?void 0:C.total_tokens)!=null?A:void 0,reasoningTokens:(k=(O=(B=j.usage)==null?void 0:B.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?k:void 0,cachedInputTokens:(Y=(L=(P=j.usage)==null?void 0:P.prompt_tokens_details)==null?void 0:L.cached_tokens)!=null?Y:void 0},providerMetadata:fe,request:{body:H},response:{...Oa(j),headers:re,body:V},warnings:$}}async doStream(t){var r;const{args:o,warnings:c}=await this.getArgs({...t}),u={...o,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},f=(r=this.config.metadataExtractor)==null?void 0:r.createStreamExtractor(),{responseHeaders:p,value:x}=await Na({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Aa(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Tg(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=[];let g="unknown";const C={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let A=!0;const B=this.providerOptionsName;let O=!1,k=!1;return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:c})},transform(P,L){var Y,Z,$,H,re,j,V,z,M,we,le,fe,ae;if(t.includeRawChunks&&L.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g="error",L.enqueue({type:"error",error:P.error});return}const X=P.value;if(f?.processChunk(P.rawValue),"error"in X){g="error",L.enqueue({type:"error",error:X.error.message});return}if(A&&(A=!1,L.enqueue({type:"response-metadata",...Oa(X)})),X.usage!=null){const{prompt_tokens:ee,completion_tokens:he,total_tokens:ge,prompt_tokens_details:de,completion_tokens_details:Ce}=X.usage;C.promptTokens=ee??void 0,C.completionTokens=he??void 0,C.totalTokens=ge??void 0,Ce?.reasoning_tokens!=null&&(C.completionTokensDetails.reasoningTokens=Ce?.reasoning_tokens),Ce?.accepted_prediction_tokens!=null&&(C.completionTokensDetails.acceptedPredictionTokens=Ce?.accepted_prediction_tokens),Ce?.rejected_prediction_tokens!=null&&(C.completionTokensDetails.rejectedPredictionTokens=Ce?.rejected_prediction_tokens),de?.cached_tokens!=null&&(C.promptTokensDetails.cachedTokens=de?.cached_tokens)}const D=X.choices[0];if(D?.finish_reason!=null&&(g=Ra(D.finish_reason)),D?.delta==null)return;const K=D.delta,W=(Y=K.reasoning_content)!=null?Y:K.reasoning;if(W&&(O||(L.enqueue({type:"reasoning-start",id:"reasoning-0"}),O=!0),L.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:W})),K.content&&(k||(L.enqueue({type:"text-start",id:"txt-0"}),k=!0),L.enqueue({type:"text-delta",id:"txt-0",delta:K.content})),K.tool_calls!=null)for(const ee of K.tool_calls){const he=ee.index;if(_[he]==null){if(ee.id==null)throw new ba({data:ee,message:"Expected 'id' to be a string."});if(((Z=ee.function)==null?void 0:Z.name)==null)throw new ba({data:ee,message:"Expected 'function.name' to be a string."});L.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),_[he]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:($=ee.function.arguments)!=null?$:""},hasFinished:!1};const de=_[he];((H=de.function)==null?void 0:H.name)!=null&&((re=de.function)==null?void 0:re.arguments)!=null&&(de.function.arguments.length>0&&L.enqueue({type:"tool-input-delta",id:de.id,delta:de.function.arguments}),Sa(de.function.arguments)&&(L.enqueue({type:"tool-input-end",id:de.id}),L.enqueue({type:"tool-call",toolCallId:(j=de.id)!=null?j:Ei(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const ge=_[he];ge.hasFinished||(((V=ee.function)==null?void 0:V.arguments)!=null&&(ge.function.arguments+=(M=(z=ee.function)==null?void 0:z.arguments)!=null?M:""),L.enqueue({type:"tool-input-delta",id:ge.id,delta:(we=ee.function.arguments)!=null?we:""}),((le=ge.function)==null?void 0:le.name)!=null&&((fe=ge.function)==null?void 0:fe.arguments)!=null&&Sa(ge.function.arguments)&&(L.enqueue({type:"tool-input-end",id:ge.id}),L.enqueue({type:"tool-call",toolCallId:(ae=ge.id)!=null?ae:Ei(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0))}},flush(P){var L,Y,Z,$,H,re;O&&P.enqueue({type:"reasoning-end",id:"reasoning-0"}),k&&P.enqueue({type:"text-end",id:"txt-0"});for(const V of _.filter(z=>!z.hasFinished))P.enqueue({type:"tool-input-end",id:V.id}),P.enqueue({type:"tool-call",toolCallId:(L=V.id)!=null?L:Ei(),toolName:V.function.name,input:V.function.arguments});const j={[B]:{},...f?.buildMetadata()};C.completionTokensDetails.acceptedPredictionTokens!=null&&(j[B].acceptedPredictionTokens=C.completionTokensDetails.acceptedPredictionTokens),C.completionTokensDetails.rejectedPredictionTokens!=null&&(j[B].rejectedPredictionTokens=C.completionTokensDetails.rejectedPredictionTokens),P.enqueue({type:"finish",finishReason:g,usage:{inputTokens:(Y=C.promptTokens)!=null?Y:void 0,outputTokens:(Z=C.completionTokens)!=null?Z:void 0,totalTokens:($=C.totalTokens)!=null?$:void 0,reasoningTokens:(H=C.completionTokensDetails.reasoningTokens)!=null?H:void 0,cachedInputTokens:(re=C.promptTokensDetails.cachedTokens)!=null?re:void 0},providerMetadata:j})}})),request:{body:u},response:{headers:p}}}},_u=S({prompt_tokens:Q().nullish(),completion_tokens:Q().nullish(),total_tokens:Q().nullish(),prompt_tokens_details:S({cached_tokens:Q().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:Q().nullish(),accepted_prediction_tokens:Q().nullish(),rejected_prediction_tokens:Q().nullish()}).nullish()}).nullish(),Ug=S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({message:S({role:G("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ye(S({id:w().nullish(),function:S({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:_u}),zg=t=>Pe([S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({delta:S({role:Le(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ye(S({index:Q(),id:w().nullish(),function:S({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:_u}),t]);S({echo:Tt().optional(),logitBias:gt(w(),Q()).optional(),suffix:w().optional(),user:w().optional()});var $g=S({prompt_tokens:Q(),completion_tokens:Q(),total_tokens:Q()});S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w()})),usage:$g.nullish()});S({dimensions:Q().optional(),user:w().optional()});S({data:ye(S({embedding:ye(Q())})),usage:S({prompt_tokens:Q()}).nullish(),providerMetadata:gt(w(),gt(w(),fr())).optional()});S({data:ye(S({b64_json:w()}))});var ka=t=>{var r,o;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(o=t.prompt_cache_miss_tokens)!=null?o:NaN}}},Vg={extractMetadata:async({parsedBody:t})=>{const r=await ei({value:t,schema:Zg});return!r.success||r.value.usage==null?void 0:ka(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await ei({value:r,schema:jg});u.success&&((c=(o=u.value.choices)==null?void 0:o[0])==null?void 0:c.finish_reason)==="stop"&&u.value.usage&&(t=u.value.usage)},buildMetadata:()=>ka(t)}}},vu=S({prompt_cache_hit_tokens:Q().nullish(),prompt_cache_miss_tokens:Q().nullish()}),Zg=S({usage:vu.nullish()}),jg=S({choices:ye(S({finish_reason:w().nullish()})).nullish(),usage:vu.nullish()}),Wg="1.0.30";function Cu(t={}){var r;const o=Mg((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>yu({Authorization:`Bearer ${pg({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Wg}`);class u extends Fg{addJsonInstruction(_){var g;if(((g=_.responseFormat)==null?void 0:g.type)!=="json")return _;const B=[...Array.isArray(_.prompt)?_.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{..._,prompt:B}}async doGenerate(_){return super.doGenerate(this.addJsonInstruction(_))}async doStream(_){return super.doStream(this.addJsonInstruction(_))}}const f=x=>new u(x,{provider:"deepseek.chat",url:({path:_})=>`${o}${_}`,headers:c,fetch:t.fetch,metadataExtractor:Vg}),p=x=>f(x);return p.languageModel=f,p.chat=f,p.textEmbeddingModel=x=>{throw new Ea({modelId:x,modelType:"textEmbeddingModel"})},p.imageModel=x=>{throw new Ea({modelId:x,modelType:"imageModel"})},p}Cu();var ns=S({error:S({message:w(),type:w().nullish(),param:fr().nullish(),code:Pe([w(),Q()]).nullish()})}),Cn=xm({errorSchema:ns,errorToMessage:t=>t.error.message});function bu(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),o=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),u=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function Ma(t){var r,o,c,u,f,p;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const x=(r=t.prompt_tokens)!=null?r:0,_=(o=t.completion_tokens)!=null?o:0,g=(u=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?u:0,C=(p=(f=t.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?p:0;return{inputTokens:{total:x,noCache:x-g,cacheRead:g,cacheWrite:void 0},outputTokens:{total:_,text:_-C,reasoning:C},raw:t}}function Hg({prompt:t,systemMessageMode:r="system"}){var o;const c=[],u=[];for(const{role:f,content:p}of t)switch(f){case"system":{switch(r){case"system":{c.push({role:"system",content:p});break}case"developer":{c.push({role:"developer",content:p});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const x=r;throw new Error(`Unsupported system message mode: ${x}`)}}break}case"user":{if(p.length===1&&p[0].type==="text"){c.push({role:"user",content:p[0].text});break}c.push({role:"user",content:p.map((x,_)=>{var g,C,A;switch(x.type){case"text":return{type:"text",text:x.text};case"file":if(x.mediaType.startsWith("image/")){const B=x.mediaType==="image/*"?"image/jpeg":x.mediaType;return{type:"image_url",image_url:{url:x.data instanceof URL?x.data.toString():`data:${B};base64,${Ar(x.data)}`,detail:(C=(g=x.providerOptions)==null?void 0:g.openai)==null?void 0:C.imageDetail}}}else if(x.mediaType.startsWith("audio/")){if(x.data instanceof URL)throw new Dn({functionality:"audio file parts with URLs"});switch(x.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Ar(x.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Ar(x.data),format:"mp3"}};default:throw new Dn({functionality:`audio content parts with media type ${x.mediaType}`})}}else if(x.mediaType==="application/pdf"){if(x.data instanceof URL)throw new Dn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof x.data=="string"&&x.data.startsWith("file-")?{file_id:x.data}:{filename:(A=x.filename)!=null?A:`part-${_}.pdf`,file_data:`data:application/pdf;base64,${Ar(x.data)}`}}}else throw new Dn({functionality:`file part media type ${x.mediaType}`})}})});break}case"assistant":{let x="";const _=[];for(const g of p)switch(g.type){case"text":{x+=g.text;break}case"tool-call":{_.push({id:g.toolCallId,type:"function",function:{name:g.toolName,arguments:JSON.stringify(g.input)}});break}}c.push({role:"assistant",content:x,tool_calls:_.length>0?_:void 0});break}case"tool":{for(const x of p){if(x.type==="tool-approval-response")continue;const _=x.output;let g;switch(_.type){case"text":case"error-text":g=_.value;break;case"execution-denied":g=(o=_.reason)!=null?o:"Tool execution denied.";break;case"content":case"json":case"error-json":g=JSON.stringify(_.value);break}c.push({role:"tool",tool_call_id:x.toolCallId,content:g})}break}default:{const x=f;throw new Error(`Unsupported role: ${x}`)}}return{messages:c,warnings:u}}function wo({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Da(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Gg=ze(()=>Fe(S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({message:S({role:G("assistant").nullish(),content:w().nullish(),tool_calls:ye(S({id:w().nullish(),type:G("function"),function:S({name:w(),arguments:w()})})).nullish(),annotations:ye(S({type:G("url_citation"),url_citation:S({start_index:Q(),end_index:Q(),url:w(),title:w()})})).nullish()}),index:Q(),logprobs:S({content:ye(S({token:w(),logprob:Q(),top_logprobs:ye(S({token:w(),logprob:Q()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:S({prompt_tokens:Q().nullish(),completion_tokens:Q().nullish(),total_tokens:Q().nullish(),prompt_tokens_details:S({cached_tokens:Q().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:Q().nullish(),accepted_prediction_tokens:Q().nullish(),rejected_prediction_tokens:Q().nullish()}).nullish()}).nullish()}))),Xg=ze(()=>Fe(Pe([S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({delta:S({role:Le(["assistant"]).nullish(),content:w().nullish(),tool_calls:ye(S({index:Q(),id:w().nullish(),type:G("function").nullish(),function:S({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ye(S({type:G("url_citation"),url_citation:S({start_index:Q(),end_index:Q(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:S({content:ye(S({token:w(),logprob:Q(),top_logprobs:ye(S({token:w(),logprob:Q()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:Q()})),usage:S({prompt_tokens:Q().nullish(),completion_tokens:Q().nullish(),total_tokens:Q().nullish(),prompt_tokens_details:S({cached_tokens:Q().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:Q().nullish(),accepted_prediction_tokens:Q().nullish(),rejected_prediction_tokens:Q().nullish()}).nullish()}).nullish()}),ns]))),qg=ze(()=>Fe(S({logitBias:gt(Yh(),Q()).optional(),logprobs:Pe([Tt(),Q()]).optional(),parallelToolCalls:Tt().optional(),user:w().optional(),reasoningEffort:Le(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:Q().optional(),store:Tt().optional(),metadata:gt(w().max(64),w().max(512)).optional(),prediction:gt(w(),fr()).optional(),serviceTier:Le(["auto","flex","priority","default"]).optional(),strictJsonSchema:Tt().optional(),textVerbosity:Le(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheRetention:Le(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Le(["system","developer","remove"]).optional(),forceReasoning:Tt().optional()})));function Yg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:o.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new Dn({functionality:`tool choice type: ${f}`})}}}var Jg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:p,stopSequences:x,responseFormat:_,seed:g,tools:C,toolChoice:A,providerOptions:B}){var O,k,P,L,Y;const Z=[],$=(O=await Bn({provider:"openai",providerOptions:B,schema:qg}))!=null?O:{},H=bu(this.modelId),re=(k=$.forceReasoning)!=null?k:H.isReasoningModel;u!=null&&Z.push({type:"unsupported",feature:"topK"});const{messages:j,warnings:V}=Hg({prompt:t,systemMessageMode:(P=$.systemMessageMode)!=null?P:re?"developer":H.systemMessageMode});Z.push(...V);const z=(L=$.strictJsonSchema)!=null?L:!0,M={model:this.modelId,logit_bias:$.logitBias,logprobs:$.logprobs===!0||typeof $.logprobs=="number"?!0:void 0,top_logprobs:typeof $.logprobs=="number"?$.logprobs:typeof $.logprobs=="boolean"&&$.logprobs?0:void 0,user:$.user,parallel_tool_calls:$.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:p,response_format:_?.type==="json"?_.schema!=null?{type:"json_schema",json_schema:{schema:_.schema,strict:z,name:(Y=_.name)!=null?Y:"response",description:_.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:$.textVerbosity,max_completion_tokens:$.maxCompletionTokens,store:$.store,metadata:$.metadata,prediction:$.prediction,reasoning_effort:$.reasoningEffort,service_tier:$.serviceTier,prompt_cache_key:$.promptCacheKey,prompt_cache_retention:$.promptCacheRetention,safety_identifier:$.safetyIdentifier,messages:j};re?(($.reasoningEffort!=="none"||!H.supportsNonReasoningParameters)&&(M.temperature!=null&&(M.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,Z.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),M.logprobs!=null&&(M.logprobs=void 0,Z.push({type:"other",message:"logprobs is not supported for reasoning models"}))),M.frequency_penalty!=null&&(M.frequency_penalty=void 0,Z.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),M.presence_penalty!=null&&(M.presence_penalty=void 0,Z.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),M.logit_bias!=null&&(M.logit_bias=void 0,Z.push({type:"other",message:"logitBias is not supported for reasoning models"})),M.top_logprobs!=null&&(M.top_logprobs=void 0,Z.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),M.max_tokens!=null&&(M.max_completion_tokens==null&&(M.max_completion_tokens=M.max_tokens),M.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&M.temperature!=null&&(M.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),$.serviceTier==="flex"&&!H.supportsFlexProcessing&&(Z.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),M.service_tier=void 0),$.serviceTier==="priority"&&!H.supportsPriorityProcessing&&(Z.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),M.service_tier=void 0);const{tools:we,toolChoice:le,toolWarnings:fe}=Yg({tools:C,toolChoice:A});return{args:{...M,tools:we,tool_choice:le},warnings:[...Z,...fe]}}async doGenerate(t){var r,o,c,u,f,p,x;const{args:_,warnings:g}=await this.getArgs(t),{responseHeaders:C,value:A,rawValue:B}=await Ln({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:_,failedResponseHandler:Cn,successfulResponseHandler:ur(Gg),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=A.choices[0],k=[],P=O.message.content;P!=null&&P.length>0&&k.push({type:"text",text:P});for(const Z of(r=O.message.tool_calls)!=null?r:[])k.push({type:"tool-call",toolCallId:(o=Z.id)!=null?o:qt(),toolName:Z.function.name,input:Z.function.arguments});for(const Z of(c=O.message.annotations)!=null?c:[])k.push({type:"source",sourceType:"url",id:qt(),url:Z.url_citation.url,title:Z.url_citation.title});const L=(u=A.usage)==null?void 0:u.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const Y={openai:{}};return L?.accepted_prediction_tokens!=null&&(Y.openai.acceptedPredictionTokens=L?.accepted_prediction_tokens),L?.rejected_prediction_tokens!=null&&(Y.openai.rejectedPredictionTokens=L?.rejected_prediction_tokens),((p=O.logprobs)==null?void 0:p.content)!=null&&(Y.openai.logprobs=O.logprobs.content),{content:k,finishReason:{unified:Da(O.finish_reason),raw:(x=O.finish_reason)!=null?x:void 0},usage:Ma(A.usage),request:{body:_},response:{...wo(A),headers:C,body:B},warnings:g,providerMetadata:Y}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await Ln({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:c,failedResponseHandler:Cn,successfulResponseHandler:es(Xg),abortSignal:t.abortSignal,fetch:this.config.fetch}),p=[];let x={unified:"other",raw:void 0},_,g=!1,C=!1;const A={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(B){B.enqueue({type:"stream-start",warnings:o})},transform(B,O){var k,P,L,Y,Z,$,H,re,j,V,z,M,we,le,fe,ae,X;if(t.includeRawChunks&&O.enqueue({type:"raw",rawValue:B.rawValue}),!B.success){x={unified:"error",raw:void 0},O.enqueue({type:"error",error:B.error});return}const D=B.value;if("error"in D){x={unified:"error",raw:void 0},O.enqueue({type:"error",error:D.error});return}if(!g){const ee=wo(D);Object.values(ee).some(Boolean)&&(g=!0,O.enqueue({type:"response-metadata",...wo(D)}))}D.usage!=null&&(_=D.usage,((k=D.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(A.openai.acceptedPredictionTokens=(P=D.usage.completion_tokens_details)==null?void 0:P.accepted_prediction_tokens),((L=D.usage.completion_tokens_details)==null?void 0:L.rejected_prediction_tokens)!=null&&(A.openai.rejectedPredictionTokens=(Y=D.usage.completion_tokens_details)==null?void 0:Y.rejected_prediction_tokens));const K=D.choices[0];if(K?.finish_reason!=null&&(x={unified:Da(K.finish_reason),raw:K.finish_reason}),((Z=K?.logprobs)==null?void 0:Z.content)!=null&&(A.openai.logprobs=K.logprobs.content),K?.delta==null)return;const W=K.delta;if(W.content!=null&&(C||(O.enqueue({type:"text-start",id:"0"}),C=!0),O.enqueue({type:"text-delta",id:"0",delta:W.content})),W.tool_calls!=null)for(const ee of W.tool_calls){const he=ee.index;if(p[he]==null){if(ee.type!=null&&ee.type!=="function")throw new fo({data:ee,message:"Expected 'function' type."});if(ee.id==null)throw new fo({data:ee,message:"Expected 'id' to be a string."});if((($=ee.function)==null?void 0:$.name)==null)throw new fo({data:ee,message:"Expected 'function.name' to be a string."});O.enqueue({type:"tool-input-start",id:ee.id,toolName:ee.function.name}),p[he]={id:ee.id,type:"function",function:{name:ee.function.name,arguments:(H=ee.function.arguments)!=null?H:""},hasFinished:!1};const de=p[he];((re=de.function)==null?void 0:re.name)!=null&&((j=de.function)==null?void 0:j.arguments)!=null&&(de.function.arguments.length>0&&O.enqueue({type:"tool-input-delta",id:de.id,delta:de.function.arguments}),va(de.function.arguments)&&(O.enqueue({type:"tool-input-end",id:de.id}),O.enqueue({type:"tool-call",toolCallId:(V=de.id)!=null?V:qt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const ge=p[he];ge.hasFinished||(((z=ee.function)==null?void 0:z.arguments)!=null&&(ge.function.arguments+=(we=(M=ee.function)==null?void 0:M.arguments)!=null?we:""),O.enqueue({type:"tool-input-delta",id:ge.id,delta:(le=ee.function.arguments)!=null?le:""}),((fe=ge.function)==null?void 0:fe.name)!=null&&((ae=ge.function)==null?void 0:ae.arguments)!=null&&va(ge.function.arguments)&&(O.enqueue({type:"tool-input-end",id:ge.id}),O.enqueue({type:"tool-call",toolCallId:(X=ge.id)!=null?X:qt(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0))}if(W.annotations!=null)for(const ee of W.annotations)O.enqueue({type:"source",sourceType:"url",id:qt(),url:ee.url_citation.url,title:ee.url_citation.title})},flush(B){C&&B.enqueue({type:"text-end",id:"0"}),B.enqueue({type:"finish",finishReason:x,usage:Ma(_),...A!=null?{providerMetadata:A}:{}})}})),request:{body:c},response:{headers:u}}}};function Pa(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,p=(o=t.completion_tokens)!=null?o:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(u=t.completion_tokens)!=null?u:void 0,text:p,reasoning:void 0},raw:t}}function Kg({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
44
|
+
Error message: ${Xc(o)}`,cause:o}),this[hu]=!0,this.value=r}static isInstance(r){return Bt.hasMarker(r,fu)}static wrap({value:r,cause:o}){return ko.isInstance(o)&&o.value===r?o:new ko({value:r,cause:o})}};hu=og;var Qr=sg,pu="AI_UnsupportedFunctionalityError",mu=`vercel.ai.error.${pu}`,ag=Symbol.for(mu),gu,xu=class extends Bt{constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:pu,message:r}),this[gu]=!0,this.functionality=t}static isInstance(t){return Bt.hasMarker(t,mu)}};gu=ag;function Aa(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Zi(t){return Object.fromEntries([...t.headers])}var lg=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Kc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Ei=lg();function Mo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var cg=["fetch failed","failed to fetch"];function ug({error:t,url:r,requestBodyValues:o}){if(Mo(t))return t;if(t instanceof TypeError&&cg.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Pn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function dg(t=globalThis){var r,o,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(o=t.process)==null?void 0:o.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fg(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((o,c)=>{r[c.toLowerCase()]=o});else{Array.isArray(t)||(t=Object.entries(t));for(const[o,c]of t)c!=null&&(r[o.toLowerCase()]=c)}return r}function yu(t,...r){const o=new Headers(fg(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var hg="3.0.18";function pg({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new bi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new bi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new bi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new bi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var mg=/"__proto__"\s*:/,gg=/"constructor"\s*:/;function Ia(t){const r=JSON.parse(t);return r===null||typeof r!="object"||mg.test(t)===!1&&gg.test(t)===!1?r:xg(r)}function xg(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function ts(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Ia(t)}try{return Ia(t)}finally{Error.stackTraceLimit=r}}var Do=Symbol.for("vercel.ai.validator");function yg(t){return{[Do]:!0,validate:t}}function wg(t){return typeof t=="object"&&t!==null&&Do in t&&t[Do]===!0&&"validate"in t}function _g(t){return wg(t)?t:typeof t=="function"?t():vg(t)}function vg(t){return yg(async r=>{const o=await t["~standard"].validate(r);return o.issues==null?{success:!0,value:o.value}:{success:!1,error:new Qr({value:r,cause:o.issues})}})}async function Cg({value:t,schema:r}){const o=await ei({value:t,schema:r});if(!o.success)throw Qr.wrap({value:t,cause:o.error});return o.value}async function ei({value:t,schema:r}){const o=_g(r);try{if(o.validate==null)return{success:!0,value:t,rawValue:t};const c=await o.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Qr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Qr.wrap({value:t,cause:c}),rawValue:t}}}async function bg({text:t,schema:r}){try{const o=ts(t);return r==null?o:Cg({value:o,schema:r})}catch(o){throw Pi.isInstance(o)||Qr.isInstance(o)?o:new Pi({text:t,cause:o})}}async function wu({text:t,schema:r}){try{const o=ts(t);return r==null?{success:!0,value:o,rawValue:o}:await ei({value:o,schema:r})}catch(o){return{success:!1,error:Pi.isInstance(o)?o:new Pi({text:t,cause:o}),rawValue:void 0}}}function Sa(t){try{return ts(t),!0}catch{return!1}}function Eg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new xc).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await wu({text:o,schema:r}))}}))}async function Ta({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await ei({value:r[t],schema:o});if(!c.success)throw new Kc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Ag=()=>globalThis.fetch,Na=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>Ig({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),Ig=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=Ag()})=>{try{const x=await m(t,{method:"POST",headers:yu(r,`ai-sdk/provider-utils/${hg}`,dg()),body:o.content,signal:f}),_=Zi(x);if(!x.ok){let g;try{g=await u({response:x,url:t,requestBodyValues:o.values})}catch(C){throw Mo(C)||Pn.isInstance(C)?C:new Pn({message:"Failed to process error response",cause:C,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:o.values})}catch(g){throw g instanceof Error&&(Mo(g)||Pn.isInstance(g))?g:new Pn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:_,requestBodyValues:o.values})}}catch(x){throw ug({error:x,url:t,requestBodyValues:o.values})}},Sg=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),x=Zi(c);if(m.trim()==="")return{responseHeaders:x,value:new Pn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:o?.(c)})};try{const _=await bg({text:m,schema:t});return{responseHeaders:x,value:new Pn({message:r(_),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:_,isRetryable:o?.(c,_)})}}catch{return{responseHeaders:x,value:new Pn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:o?.(c)})}}},Tg=t=>async({response:r})=>{const o=Zi(r);if(r.body==null)throw new Qm({});return{responseHeaders:o,value:Eg({stream:r.body,schema:t})}},Ng=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await wu({text:u,schema:t}),m=Zi(r);if(!f.success)throw new Pn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:Og}=globalThis;function Rg(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return Og(r)}function kg(t){return t instanceof Uint8Array?Rg(t):t}function Mg(t){return t?.replace(/\/$/,"")}function zr(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function Dg(t){const r=[];for(const{role:o,content:c,...u}of t){const f=zr({...u});switch(o){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...zr(c[0])});break}r.push({role:"user",content:c.map(m=>{const x=zr(m);switch(m.type){case"text":return{type:"text",text:m.text,...x};case"file":if(m.mediaType.startsWith("image/")){const _=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${_};base64,${kg(m.data)}`},...x}}else throw new xu({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const x=[];for(const _ of c){const g=zr(_);switch(_.type){case"text":{m+=_.text;break}case"tool-call":{x.push({id:_.toolCallId,type:"function",function:{name:_.toolName,arguments:JSON.stringify(_.input)},...g});break}}}r.push({role:"assistant",content:m,tool_calls:x.length>0?x:void 0,...f});break}case"tool":{for(const m of c){const x=m.output;let _;switch(x.type){case"text":case"error-text":_=x.value;break;case"content":case"json":case"error-json":_=JSON.stringify(x.value);break}const g=zr(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:_,...g})}break}default:{const m=o;throw new Error(`Unsupported role: ${m}`)}}}return r}function Oa({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function Ra(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"unknown"}}var yo=S({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),Pg=S({error:S({message:w(),type:w().nullish(),param:fr().nullish(),code:Pe([w(),ee()]).nullish()})}),Bg={errorSchema:Pg,errorToMessage:t=>t.error.message};function Lg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)f.type==="provider-defined"?o.push({type:"unsupported-tool",tool:f}):c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}});if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new xu({functionality:`tool choice type: ${f}`})}}}var Fg=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:Bg;this.chunkSchema=zg(u.errorSchema),this.failedResponseHandler=Sg(u),this.supportsStructuredOutputs=(c=r.supportsStructuredOutputs)!=null?c:!1}get provider(){return this.config.provider}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get supportedUrls(){var t,r,o;return(o=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?o:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,providerOptions:x,stopSequences:_,responseFormat:g,seed:C,toolChoice:A,tools:P}){var O,k,B,L;const K=[],z=Object.assign((O=await Ta({provider:"openai-compatible",providerOptions:x,schema:yo}))!=null?O:{},(k=await Ta({provider:this.providerOptionsName,providerOptions:x,schema:yo}))!=null?k:{});u!=null&&K.push({type:"unsupported-setting",setting:"topK"}),g?.type==="json"&&g.schema!=null&&!this.supportsStructuredOutputs&&K.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:$,toolChoice:W,toolWarnings:X}=Lg({tools:P,toolChoice:A});return{args:{model:this.modelId,user:z.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:g?.type==="json"?this.supportsStructuredOutputs===!0&&g.schema!=null?{type:"json_schema",json_schema:{schema:g.schema,name:(B=g.name)!=null?B:"response",description:g.description}}:{type:"json_object"}:void 0,stop:_,seed:C,...Object.fromEntries(Object.entries((L=x?.[this.providerOptionsName])!=null?L:{}).filter(([H])=>!Object.keys(yo.shape).includes(H))),reasoning_effort:z.reasoningEffort,verbosity:z.textVerbosity,messages:Dg(t),tools:$,tool_choice:W},warnings:[...K,...X]}}async doGenerate(t){var r,o,c,u,f,m,x,_,g,C,A,P,O,k,B,L,K;const{args:z,warnings:$}=await this.getArgs({...t}),W=JSON.stringify(z),{responseHeaders:X,value:H,rawValue:V}=await Na({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Aa(this.config.headers(),t.headers),body:z,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Ng(Ug),abortSignal:t.abortSignal,fetch:this.config.fetch}),Z=H.choices[0],M=[],we=Z.message.content;we!=null&&we.length>0&&M.push({type:"text",text:we});const ce=(r=Z.message.reasoning_content)!=null?r:Z.message.reasoning;if(ce!=null&&ce.length>0&&M.push({type:"reasoning",text:ce}),Z.message.tool_calls!=null)for(const q of Z.message.tool_calls)M.push({type:"tool-call",toolCallId:(o=q.id)!=null?o:Ei(),toolName:q.function.name,input:q.function.arguments});const fe={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:V}))},ae=(f=H.usage)==null?void 0:f.completion_tokens_details;return ae?.accepted_prediction_tokens!=null&&(fe[this.providerOptionsName].acceptedPredictionTokens=ae?.accepted_prediction_tokens),ae?.rejected_prediction_tokens!=null&&(fe[this.providerOptionsName].rejectedPredictionTokens=ae?.rejected_prediction_tokens),{content:M,finishReason:Ra(Z.finish_reason),usage:{inputTokens:(x=(m=H.usage)==null?void 0:m.prompt_tokens)!=null?x:void 0,outputTokens:(g=(_=H.usage)==null?void 0:_.completion_tokens)!=null?g:void 0,totalTokens:(A=(C=H.usage)==null?void 0:C.total_tokens)!=null?A:void 0,reasoningTokens:(k=(O=(P=H.usage)==null?void 0:P.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?k:void 0,cachedInputTokens:(K=(L=(B=H.usage)==null?void 0:B.prompt_tokens_details)==null?void 0:L.cached_tokens)!=null?K:void 0},providerMetadata:fe,request:{body:W},response:{...Oa(H),headers:X,body:V},warnings:$}}async doStream(t){var r;const{args:o,warnings:c}=await this.getArgs({...t}),u={...o,stream:!0,stream_options:this.config.includeUsage?{include_usage:!0}:void 0},f=(r=this.config.metadataExtractor)==null?void 0:r.createStreamExtractor(),{responseHeaders:m,value:x}=await Na({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Aa(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:Tg(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),_=[];let g="unknown";const C={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let A=!0;const P=this.providerOptionsName;let O=!1,k=!1;return{stream:x.pipeThrough(new TransformStream({start(B){B.enqueue({type:"stream-start",warnings:c})},transform(B,L){var K,z,$,W,X,H,V,Z,M,we,ce,fe,ae;if(t.includeRawChunks&&L.enqueue({type:"raw",rawValue:B.rawValue}),!B.success){g="error",L.enqueue({type:"error",error:B.error});return}const q=B.value;if(f?.processChunk(B.rawValue),"error"in q){g="error",L.enqueue({type:"error",error:q.error.message});return}if(A&&(A=!1,L.enqueue({type:"response-metadata",...Oa(q)})),q.usage!=null){const{prompt_tokens:te,completion_tokens:he,total_tokens:ge,prompt_tokens_details:de,completion_tokens_details:Ce}=q.usage;C.promptTokens=te??void 0,C.completionTokens=he??void 0,C.totalTokens=ge??void 0,Ce?.reasoning_tokens!=null&&(C.completionTokensDetails.reasoningTokens=Ce?.reasoning_tokens),Ce?.accepted_prediction_tokens!=null&&(C.completionTokensDetails.acceptedPredictionTokens=Ce?.accepted_prediction_tokens),Ce?.rejected_prediction_tokens!=null&&(C.completionTokensDetails.rejectedPredictionTokens=Ce?.rejected_prediction_tokens),de?.cached_tokens!=null&&(C.promptTokensDetails.cachedTokens=de?.cached_tokens)}const D=q.choices[0];if(D?.finish_reason!=null&&(g=Ra(D.finish_reason)),D?.delta==null)return;const Q=D.delta,j=(K=Q.reasoning_content)!=null?K:Q.reasoning;if(j&&(O||(L.enqueue({type:"reasoning-start",id:"reasoning-0"}),O=!0),L.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:j})),Q.content&&(k||(L.enqueue({type:"text-start",id:"txt-0"}),k=!0),L.enqueue({type:"text-delta",id:"txt-0",delta:Q.content})),Q.tool_calls!=null)for(const te of Q.tool_calls){const he=te.index;if(_[he]==null){if(te.id==null)throw new ba({data:te,message:"Expected 'id' to be a string."});if(((z=te.function)==null?void 0:z.name)==null)throw new ba({data:te,message:"Expected 'function.name' to be a string."});L.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),_[he]={id:te.id,type:"function",function:{name:te.function.name,arguments:($=te.function.arguments)!=null?$:""},hasFinished:!1};const de=_[he];((W=de.function)==null?void 0:W.name)!=null&&((X=de.function)==null?void 0:X.arguments)!=null&&(de.function.arguments.length>0&&L.enqueue({type:"tool-input-delta",id:de.id,delta:de.function.arguments}),Sa(de.function.arguments)&&(L.enqueue({type:"tool-input-end",id:de.id}),L.enqueue({type:"tool-call",toolCallId:(H=de.id)!=null?H:Ei(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const ge=_[he];ge.hasFinished||(((V=te.function)==null?void 0:V.arguments)!=null&&(ge.function.arguments+=(M=(Z=te.function)==null?void 0:Z.arguments)!=null?M:""),L.enqueue({type:"tool-input-delta",id:ge.id,delta:(we=te.function.arguments)!=null?we:""}),((ce=ge.function)==null?void 0:ce.name)!=null&&((fe=ge.function)==null?void 0:fe.arguments)!=null&&Sa(ge.function.arguments)&&(L.enqueue({type:"tool-input-end",id:ge.id}),L.enqueue({type:"tool-call",toolCallId:(ae=ge.id)!=null?ae:Ei(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0))}},flush(B){var L,K,z,$,W,X;O&&B.enqueue({type:"reasoning-end",id:"reasoning-0"}),k&&B.enqueue({type:"text-end",id:"txt-0"});for(const V of _.filter(Z=>!Z.hasFinished))B.enqueue({type:"tool-input-end",id:V.id}),B.enqueue({type:"tool-call",toolCallId:(L=V.id)!=null?L:Ei(),toolName:V.function.name,input:V.function.arguments});const H={[P]:{},...f?.buildMetadata()};C.completionTokensDetails.acceptedPredictionTokens!=null&&(H[P].acceptedPredictionTokens=C.completionTokensDetails.acceptedPredictionTokens),C.completionTokensDetails.rejectedPredictionTokens!=null&&(H[P].rejectedPredictionTokens=C.completionTokensDetails.rejectedPredictionTokens),B.enqueue({type:"finish",finishReason:g,usage:{inputTokens:(K=C.promptTokens)!=null?K:void 0,outputTokens:(z=C.completionTokens)!=null?z:void 0,totalTokens:($=C.totalTokens)!=null?$:void 0,reasoningTokens:(W=C.completionTokensDetails.reasoningTokens)!=null?W:void 0,cachedInputTokens:(X=C.promptTokensDetails.cachedTokens)!=null?X:void 0},providerMetadata:H})}})),request:{body:u},response:{headers:m}}}},_u=S({prompt_tokens:ee().nullish(),completion_tokens:ee().nullish(),total_tokens:ee().nullish(),prompt_tokens_details:S({cached_tokens:ee().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:ee().nullish(),accepted_prediction_tokens:ee().nullish(),rejected_prediction_tokens:ee().nullish()}).nullish()}).nullish(),Ug=S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({message:S({role:G("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ye(S({id:w().nullish(),function:S({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:_u}),zg=t=>Pe([S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({delta:S({role:Le(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ye(S({index:ee(),id:w().nullish(),function:S({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:_u}),t]);S({echo:Tt().optional(),logitBias:gt(w(),ee()).optional(),suffix:w().optional(),user:w().optional()});var $g=S({prompt_tokens:ee(),completion_tokens:ee(),total_tokens:ee()});S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w()})),usage:$g.nullish()});S({dimensions:ee().optional(),user:w().optional()});S({data:ye(S({embedding:ye(ee())})),usage:S({prompt_tokens:ee()}).nullish(),providerMetadata:gt(w(),gt(w(),fr())).optional()});S({data:ye(S({b64_json:w()}))});var ka=t=>{var r,o;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(o=t.prompt_cache_miss_tokens)!=null?o:NaN}}},Vg={extractMetadata:async({parsedBody:t})=>{const r=await ei({value:t,schema:Zg});return!r.success||r.value.usage==null?void 0:ka(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await ei({value:r,schema:jg});u.success&&((c=(o=u.value.choices)==null?void 0:o[0])==null?void 0:c.finish_reason)==="stop"&&u.value.usage&&(t=u.value.usage)},buildMetadata:()=>ka(t)}}},vu=S({prompt_cache_hit_tokens:ee().nullish(),prompt_cache_miss_tokens:ee().nullish()}),Zg=S({usage:vu.nullish()}),jg=S({choices:ye(S({finish_reason:w().nullish()})).nullish(),usage:vu.nullish()}),Wg="1.0.30";function Cu(t={}){var r;const o=Mg((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>yu({Authorization:`Bearer ${pg({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Wg}`);class u extends Fg{addJsonInstruction(_){var g;if(((g=_.responseFormat)==null?void 0:g.type)!=="json")return _;const P=[...Array.isArray(_.prompt)?_.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{..._,prompt:P}}async doGenerate(_){return super.doGenerate(this.addJsonInstruction(_))}async doStream(_){return super.doStream(this.addJsonInstruction(_))}}const f=x=>new u(x,{provider:"deepseek.chat",url:({path:_})=>`${o}${_}`,headers:c,fetch:t.fetch,metadataExtractor:Vg}),m=x=>f(x);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=x=>{throw new Ea({modelId:x,modelType:"textEmbeddingModel"})},m.imageModel=x=>{throw new Ea({modelId:x,modelType:"imageModel"})},m}Cu();var ns=S({error:S({message:w(),type:w().nullish(),param:fr().nullish(),code:Pe([w(),ee()]).nullish()})}),Cn=xm({errorSchema:ns,errorToMessage:t=>t.error.message});function bu(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),o=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),u=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function Ma(t){var r,o,c,u,f,m;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const x=(r=t.prompt_tokens)!=null?r:0,_=(o=t.completion_tokens)!=null?o:0,g=(u=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?u:0,C=(m=(f=t.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:x,noCache:x-g,cacheRead:g,cacheWrite:void 0},outputTokens:{total:_,text:_-C,reasoning:C},raw:t}}function Hg({prompt:t,systemMessageMode:r="system"}){var o;const c=[],u=[];for(const{role:f,content:m}of t)switch(f){case"system":{switch(r){case"system":{c.push({role:"system",content:m});break}case"developer":{c.push({role:"developer",content:m});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const x=r;throw new Error(`Unsupported system message mode: ${x}`)}}break}case"user":{if(m.length===1&&m[0].type==="text"){c.push({role:"user",content:m[0].text});break}c.push({role:"user",content:m.map((x,_)=>{var g,C,A;switch(x.type){case"text":return{type:"text",text:x.text};case"file":if(x.mediaType.startsWith("image/")){const P=x.mediaType==="image/*"?"image/jpeg":x.mediaType;return{type:"image_url",image_url:{url:x.data instanceof URL?x.data.toString():`data:${P};base64,${Ar(x.data)}`,detail:(C=(g=x.providerOptions)==null?void 0:g.openai)==null?void 0:C.imageDetail}}}else if(x.mediaType.startsWith("audio/")){if(x.data instanceof URL)throw new Dn({functionality:"audio file parts with URLs"});switch(x.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Ar(x.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Ar(x.data),format:"mp3"}};default:throw new Dn({functionality:`audio content parts with media type ${x.mediaType}`})}}else if(x.mediaType==="application/pdf"){if(x.data instanceof URL)throw new Dn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof x.data=="string"&&x.data.startsWith("file-")?{file_id:x.data}:{filename:(A=x.filename)!=null?A:`part-${_}.pdf`,file_data:`data:application/pdf;base64,${Ar(x.data)}`}}}else throw new Dn({functionality:`file part media type ${x.mediaType}`})}})});break}case"assistant":{let x="";const _=[];for(const g of m)switch(g.type){case"text":{x+=g.text;break}case"tool-call":{_.push({id:g.toolCallId,type:"function",function:{name:g.toolName,arguments:JSON.stringify(g.input)}});break}}c.push({role:"assistant",content:x,tool_calls:_.length>0?_:void 0});break}case"tool":{for(const x of m){if(x.type==="tool-approval-response")continue;const _=x.output;let g;switch(_.type){case"text":case"error-text":g=_.value;break;case"execution-denied":g=(o=_.reason)!=null?o:"Tool execution denied.";break;case"content":case"json":case"error-json":g=JSON.stringify(_.value);break}c.push({role:"tool",tool_call_id:x.toolCallId,content:g})}break}default:{const x=f;throw new Error(`Unsupported role: ${x}`)}}return{messages:c,warnings:u}}function wo({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Da(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Gg=ze(()=>Fe(S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({message:S({role:G("assistant").nullish(),content:w().nullish(),tool_calls:ye(S({id:w().nullish(),type:G("function"),function:S({name:w(),arguments:w()})})).nullish(),annotations:ye(S({type:G("url_citation"),url_citation:S({start_index:ee(),end_index:ee(),url:w(),title:w()})})).nullish()}),index:ee(),logprobs:S({content:ye(S({token:w(),logprob:ee(),top_logprobs:ye(S({token:w(),logprob:ee()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:S({prompt_tokens:ee().nullish(),completion_tokens:ee().nullish(),total_tokens:ee().nullish(),prompt_tokens_details:S({cached_tokens:ee().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:ee().nullish(),accepted_prediction_tokens:ee().nullish(),rejected_prediction_tokens:ee().nullish()}).nullish()}).nullish()}))),Xg=ze(()=>Fe(Pe([S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({delta:S({role:Le(["assistant"]).nullish(),content:w().nullish(),tool_calls:ye(S({index:ee(),id:w().nullish(),type:G("function").nullish(),function:S({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ye(S({type:G("url_citation"),url_citation:S({start_index:ee(),end_index:ee(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:S({content:ye(S({token:w(),logprob:ee(),top_logprobs:ye(S({token:w(),logprob:ee()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:ee()})),usage:S({prompt_tokens:ee().nullish(),completion_tokens:ee().nullish(),total_tokens:ee().nullish(),prompt_tokens_details:S({cached_tokens:ee().nullish()}).nullish(),completion_tokens_details:S({reasoning_tokens:ee().nullish(),accepted_prediction_tokens:ee().nullish(),rejected_prediction_tokens:ee().nullish()}).nullish()}).nullish()}),ns]))),qg=ze(()=>Fe(S({logitBias:gt(Yh(),ee()).optional(),logprobs:Pe([Tt(),ee()]).optional(),parallelToolCalls:Tt().optional(),user:w().optional(),reasoningEffort:Le(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:ee().optional(),store:Tt().optional(),metadata:gt(w().max(64),w().max(512)).optional(),prediction:gt(w(),fr()).optional(),serviceTier:Le(["auto","flex","priority","default"]).optional(),strictJsonSchema:Tt().optional(),textVerbosity:Le(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheRetention:Le(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Le(["system","developer","remove"]).optional(),forceReasoning:Tt().optional()})));function Yg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const o=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o};const c=[];for(const f of t)switch(f.type){case"function":c.push({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema,...f.strict!=null?{strict:f.strict}:{}}});break;default:o.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:o};const u=r.type;switch(u){case"auto":case"none":case"required":return{tools:c,toolChoice:u,toolWarnings:o};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:o};default:{const f=u;throw new Dn({functionality:`tool choice type: ${f}`})}}}var Jg=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:_,seed:g,tools:C,toolChoice:A,providerOptions:P}){var O,k,B,L,K;const z=[],$=(O=await Bn({provider:"openai",providerOptions:P,schema:qg}))!=null?O:{},W=bu(this.modelId),X=(k=$.forceReasoning)!=null?k:W.isReasoningModel;u!=null&&z.push({type:"unsupported",feature:"topK"});const{messages:H,warnings:V}=Hg({prompt:t,systemMessageMode:(B=$.systemMessageMode)!=null?B:X?"developer":W.systemMessageMode});z.push(...V);const Z=(L=$.strictJsonSchema)!=null?L:!0,M={model:this.modelId,logit_bias:$.logitBias,logprobs:$.logprobs===!0||typeof $.logprobs=="number"?!0:void 0,top_logprobs:typeof $.logprobs=="number"?$.logprobs:typeof $.logprobs=="boolean"&&$.logprobs?0:void 0,user:$.user,parallel_tool_calls:$.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:_?.type==="json"?_.schema!=null?{type:"json_schema",json_schema:{schema:_.schema,strict:Z,name:(K=_.name)!=null?K:"response",description:_.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:$.textVerbosity,max_completion_tokens:$.maxCompletionTokens,store:$.store,metadata:$.metadata,prediction:$.prediction,reasoning_effort:$.reasoningEffort,service_tier:$.serviceTier,prompt_cache_key:$.promptCacheKey,prompt_cache_retention:$.promptCacheRetention,safety_identifier:$.safetyIdentifier,messages:H};X?(($.reasoningEffort!=="none"||!W.supportsNonReasoningParameters)&&(M.temperature!=null&&(M.temperature=void 0,z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,z.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),M.logprobs!=null&&(M.logprobs=void 0,z.push({type:"other",message:"logprobs is not supported for reasoning models"}))),M.frequency_penalty!=null&&(M.frequency_penalty=void 0,z.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),M.presence_penalty!=null&&(M.presence_penalty=void 0,z.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),M.logit_bias!=null&&(M.logit_bias=void 0,z.push({type:"other",message:"logitBias is not supported for reasoning models"})),M.top_logprobs!=null&&(M.top_logprobs=void 0,z.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),M.max_tokens!=null&&(M.max_completion_tokens==null&&(M.max_completion_tokens=M.max_tokens),M.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&M.temperature!=null&&(M.temperature=void 0,z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),$.serviceTier==="flex"&&!W.supportsFlexProcessing&&(z.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),M.service_tier=void 0),$.serviceTier==="priority"&&!W.supportsPriorityProcessing&&(z.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),M.service_tier=void 0);const{tools:we,toolChoice:ce,toolWarnings:fe}=Yg({tools:C,toolChoice:A});return{args:{...M,tools:we,tool_choice:ce},warnings:[...z,...fe]}}async doGenerate(t){var r,o,c,u,f,m,x;const{args:_,warnings:g}=await this.getArgs(t),{responseHeaders:C,value:A,rawValue:P}=await Ln({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:_,failedResponseHandler:Cn,successfulResponseHandler:ur(Gg),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=A.choices[0],k=[],B=O.message.content;B!=null&&B.length>0&&k.push({type:"text",text:B});for(const z of(r=O.message.tool_calls)!=null?r:[])k.push({type:"tool-call",toolCallId:(o=z.id)!=null?o:qt(),toolName:z.function.name,input:z.function.arguments});for(const z of(c=O.message.annotations)!=null?c:[])k.push({type:"source",sourceType:"url",id:qt(),url:z.url_citation.url,title:z.url_citation.title});const L=(u=A.usage)==null?void 0:u.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const K={openai:{}};return L?.accepted_prediction_tokens!=null&&(K.openai.acceptedPredictionTokens=L?.accepted_prediction_tokens),L?.rejected_prediction_tokens!=null&&(K.openai.rejectedPredictionTokens=L?.rejected_prediction_tokens),((m=O.logprobs)==null?void 0:m.content)!=null&&(K.openai.logprobs=O.logprobs.content),{content:k,finishReason:{unified:Da(O.finish_reason),raw:(x=O.finish_reason)!=null?x:void 0},usage:Ma(A.usage),request:{body:_},response:{...wo(A),headers:C,body:P},warnings:g,providerMetadata:K}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await Ln({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:c,failedResponseHandler:Cn,successfulResponseHandler:es(Xg),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=[];let x={unified:"other",raw:void 0},_,g=!1,C=!1;const A={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:o})},transform(P,O){var k,B,L,K,z,$,W,X,H,V,Z,M,we,ce,fe,ae,q;if(t.includeRawChunks&&O.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){x={unified:"error",raw:void 0},O.enqueue({type:"error",error:P.error});return}const D=P.value;if("error"in D){x={unified:"error",raw:void 0},O.enqueue({type:"error",error:D.error});return}if(!g){const te=wo(D);Object.values(te).some(Boolean)&&(g=!0,O.enqueue({type:"response-metadata",...wo(D)}))}D.usage!=null&&(_=D.usage,((k=D.usage.completion_tokens_details)==null?void 0:k.accepted_prediction_tokens)!=null&&(A.openai.acceptedPredictionTokens=(B=D.usage.completion_tokens_details)==null?void 0:B.accepted_prediction_tokens),((L=D.usage.completion_tokens_details)==null?void 0:L.rejected_prediction_tokens)!=null&&(A.openai.rejectedPredictionTokens=(K=D.usage.completion_tokens_details)==null?void 0:K.rejected_prediction_tokens));const Q=D.choices[0];if(Q?.finish_reason!=null&&(x={unified:Da(Q.finish_reason),raw:Q.finish_reason}),((z=Q?.logprobs)==null?void 0:z.content)!=null&&(A.openai.logprobs=Q.logprobs.content),Q?.delta==null)return;const j=Q.delta;if(j.content!=null&&(C||(O.enqueue({type:"text-start",id:"0"}),C=!0),O.enqueue({type:"text-delta",id:"0",delta:j.content})),j.tool_calls!=null)for(const te of j.tool_calls){const he=te.index;if(m[he]==null){if(te.type!=null&&te.type!=="function")throw new fo({data:te,message:"Expected 'function' type."});if(te.id==null)throw new fo({data:te,message:"Expected 'id' to be a string."});if((($=te.function)==null?void 0:$.name)==null)throw new fo({data:te,message:"Expected 'function.name' to be a string."});O.enqueue({type:"tool-input-start",id:te.id,toolName:te.function.name}),m[he]={id:te.id,type:"function",function:{name:te.function.name,arguments:(W=te.function.arguments)!=null?W:""},hasFinished:!1};const de=m[he];((X=de.function)==null?void 0:X.name)!=null&&((H=de.function)==null?void 0:H.arguments)!=null&&(de.function.arguments.length>0&&O.enqueue({type:"tool-input-delta",id:de.id,delta:de.function.arguments}),va(de.function.arguments)&&(O.enqueue({type:"tool-input-end",id:de.id}),O.enqueue({type:"tool-call",toolCallId:(V=de.id)!=null?V:qt(),toolName:de.function.name,input:de.function.arguments}),de.hasFinished=!0));continue}const ge=m[he];ge.hasFinished||(((Z=te.function)==null?void 0:Z.arguments)!=null&&(ge.function.arguments+=(we=(M=te.function)==null?void 0:M.arguments)!=null?we:""),O.enqueue({type:"tool-input-delta",id:ge.id,delta:(ce=te.function.arguments)!=null?ce:""}),((fe=ge.function)==null?void 0:fe.name)!=null&&((ae=ge.function)==null?void 0:ae.arguments)!=null&&va(ge.function.arguments)&&(O.enqueue({type:"tool-input-end",id:ge.id}),O.enqueue({type:"tool-call",toolCallId:(q=ge.id)!=null?q:qt(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0))}if(j.annotations!=null)for(const te of j.annotations)O.enqueue({type:"source",sourceType:"url",id:qt(),url:te.url_citation.url,title:te.url_citation.title})},flush(P){C&&P.enqueue({type:"text-end",id:"0"}),P.enqueue({type:"finish",finishReason:x,usage:Ma(_),...A!=null?{providerMetadata:A}:{}})}})),request:{body:c},response:{headers:u}}}};function Pa(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=(r=t.prompt_tokens)!=null?r:0,m=(o=t.completion_tokens)!=null?o:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(u=t.completion_tokens)!=null?u:void 0,text:m,reasoning:void 0},raw:t}}function Kg({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
45
45
|
|
|
46
|
-
`,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Ld({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const
|
|
47
|
-
${
|
|
46
|
+
`,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Ld({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const m=f.map(x=>{switch(x.type){case"text":return x.text}}).filter(Boolean).join("");c+=`${r}:
|
|
47
|
+
${m}
|
|
48
48
|
|
|
49
|
-
`;break}case"assistant":{const
|
|
50
|
-
${
|
|
49
|
+
`;break}case"assistant":{const m=f.map(x=>{switch(x.type){case"text":return x.text;case"tool-call":throw new Dn({functionality:"tool-call messages"})}}).join("");c+=`${o}:
|
|
50
|
+
${m}
|
|
51
51
|
|
|
52
|
-
`;break}case"tool":throw new Dn({functionality:"tool messages"});default:{const
|
|
52
|
+
`;break}case"tool":throw new Dn({functionality:"tool messages"});default:{const m=u;throw new Error(`Unsupported role: ${m}`)}}return c+=`${o}:
|
|
53
53
|
`,{prompt:c,stopSequences:[`
|
|
54
|
-
${r}:`]}}function Ba({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function La(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Qg=ze(()=>Fe(S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w(),logprobs:S({tokens:ye(w()),token_logprobs:ye(Q()),top_logprobs:ye(gt(w(),Q())).nullish()}).nullish()})),usage:S({prompt_tokens:Q(),completion_tokens:Q(),total_tokens:Q()}).nullish()}))),e2=ze(()=>Fe(Pe([S({id:w().nullish(),created:Q().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w().nullish(),index:Q(),logprobs:S({tokens:ye(w()),token_logprobs:ye(Q()),top_logprobs:ye(gt(w(),Q())).nullish()}).nullish()})),usage:S({prompt_tokens:Q(),completion_tokens:Q(),total_tokens:Q()}).nullish()}),ns]))),Fa=ze(()=>Fe(S({echo:Tt().optional(),logitBias:gt(w(),Q()).optional(),suffix:w().optional(),user:w().optional(),logprobs:Pe([Tt(),Q()]).optional()}))),t2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:p,stopSequences:x,responseFormat:_,tools:g,toolChoice:C,seed:A,providerOptions:B}){const O=[],k={...await Bn({provider:"openai",providerOptions:B,schema:Fa}),...await Bn({provider:this.providerOptionsName,providerOptions:B,schema:Fa})};u!=null&&O.push({type:"unsupported",feature:"topK"}),g?.length&&O.push({type:"unsupported",feature:"tools"}),C!=null&&O.push({type:"unsupported",feature:"toolChoice"}),_!=null&&_.type!=="text"&&O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:P,stopSequences:L}=Kg({prompt:t}),Y=[...L??[],...x??[]];return{args:{model:this.modelId,echo:k.echo,logit_bias:k.logitBias,logprobs:k?.logprobs===!0?0:k?.logprobs===!1?void 0:k?.logprobs,suffix:k.suffix,user:k.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:p,seed:A,prompt:P,stop:Y.length>0?Y:void 0},warnings:O}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:p}=await Ln({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:o,failedResponseHandler:Cn,successfulResponseHandler:ur(Qg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],_={openai:{}};return x.logprobs!=null&&(_.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Pa(f.usage),finishReason:{unified:La(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:o},response:{...Ba(f),headers:u,body:p},providerMetadata:_,warnings:c}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await Ln({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:c,failedResponseHandler:Cn,successfulResponseHandler:es(e2),abortSignal:t.abortSignal,fetch:this.config.fetch});let p={unified:"other",raw:void 0};const x={openai:{}};let _,g=!0;return{stream:f.pipeThrough(new TransformStream({start(C){C.enqueue({type:"stream-start",warnings:o})},transform(C,A){if(t.includeRawChunks&&A.enqueue({type:"raw",rawValue:C.rawValue}),!C.success){p={unified:"error",raw:void 0},A.enqueue({type:"error",error:C.error});return}const B=C.value;if("error"in B){p={unified:"error",raw:void 0},A.enqueue({type:"error",error:B.error});return}g&&(g=!1,A.enqueue({type:"response-metadata",...Ba(B)}),A.enqueue({type:"text-start",id:"0"})),B.usage!=null&&(_=B.usage);const O=B.choices[0];O?.finish_reason!=null&&(p={unified:La(O.finish_reason),raw:O.finish_reason}),O?.logprobs!=null&&(x.openai.logprobs=O.logprobs),O?.text!=null&&O.text.length>0&&A.enqueue({type:"text-delta",id:"0",delta:O.text})},flush(C){g||C.enqueue({type:"text-end",id:"0"}),C.enqueue({type:"finish",finishReason:p,providerMetadata:x,usage:Pa(_)})}})),request:{body:c},response:{headers:u}}}},n2=ze(()=>Fe(S({dimensions:Q().optional(),user:w().optional()}))),r2=ze(()=>Fe(S({data:ye(S({embedding:ye(Q())})),usage:S({prompt_tokens:Q()}).nullish()}))),i2=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:o,providerOptions:c}){var u;if(t.length>this.maxEmbeddingsPerCall)throw new Vd({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await Bn({provider:"openai",providerOptions:c,schema:n2}))!=null?u:{},{responseHeaders:p,value:x,rawValue:_}=await Ln({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:vn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:Cn,successfulResponseHandler:ur(r2),abortSignal:o,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map(g=>g.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:p,body:_}}}},Ua=ze(()=>Fe(S({created:Q().nullish(),data:ye(S({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:S({input_tokens:Q().nullish(),output_tokens:Q().nullish(),total_tokens:Q().nullish(),input_tokens_details:S({image_tokens:Q().nullish(),text_tokens:Q().nullish()}).nullish()}).nullish()}))),o2={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},s2=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function a2(t){return s2.some(r=>t.startsWith(r))}var l2=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=o2[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:o,n:c,size:u,aspectRatio:f,seed:p,providerOptions:x,headers:_,abortSignal:g}){var C,A,B,O,k,P,L,Y,Z,$,H;const re=[];f!=null&&re.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),p!=null&&re.push({type:"unsupported",feature:"seed"});const j=(B=(A=(C=this.config._internal)==null?void 0:C.currentDate)==null?void 0:A.call(C))!=null?B:new Date;if(r!=null){const{value:M,responseHeaders:we}=await Tc({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:vn(this.config.headers(),_),formData:ip({model:this.modelId,prompt:t,image:await Promise.all(r.map(le=>le.type==="file"?new Blob([le.data instanceof Uint8Array?new Blob([le.data],{type:le.mediaType}):new Blob([Yo(le.data)],{type:le.mediaType})],{type:le.mediaType}):Cc(le.url))),mask:o!=null?await c2(o):void 0,n:c,size:u,...(O=x.openai)!=null?O:{}}),failedResponseHandler:Cn,successfulResponseHandler:ur(Ua),abortSignal:g,fetch:this.config.fetch});return{images:M.data.map(le=>le.b64_json),warnings:re,usage:M.usage!=null?{inputTokens:(k=M.usage.input_tokens)!=null?k:void 0,outputTokens:(P=M.usage.output_tokens)!=null?P:void 0,totalTokens:(L=M.usage.total_tokens)!=null?L:void 0}:void 0,response:{timestamp:j,modelId:this.modelId,headers:we},providerMetadata:{openai:{images:M.data.map((le,fe)=>{var ae,X,D,K,W,ee;return{...le.revised_prompt?{revisedPrompt:le.revised_prompt}:{},created:(ae=M.created)!=null?ae:void 0,size:(X=M.size)!=null?X:void 0,quality:(D=M.quality)!=null?D:void 0,background:(K=M.background)!=null?K:void 0,outputFormat:(W=M.output_format)!=null?W:void 0,...za((ee=M.usage)==null?void 0:ee.input_tokens_details,fe,M.data.length)}})}}}}const{value:V,responseHeaders:z}=await Ln({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:vn(this.config.headers(),_),body:{model:this.modelId,prompt:t,n:c,size:u,...(Y=x.openai)!=null?Y:{},...a2(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Cn,successfulResponseHandler:ur(Ua),abortSignal:g,fetch:this.config.fetch});return{images:V.data.map(M=>M.b64_json),warnings:re,usage:V.usage!=null?{inputTokens:(Z=V.usage.input_tokens)!=null?Z:void 0,outputTokens:($=V.usage.output_tokens)!=null?$:void 0,totalTokens:(H=V.usage.total_tokens)!=null?H:void 0}:void 0,response:{timestamp:j,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:V.data.map((M,we)=>{var le,fe,ae,X,D,K;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(le=V.created)!=null?le:void 0,size:(fe=V.size)!=null?fe:void 0,quality:(ae=V.quality)!=null?ae:void 0,background:(X=V.background)!=null?X:void 0,outputFormat:(D=V.output_format)!=null?D:void 0,...za((K=V.usage)==null?void 0:K.input_tokens_details,we,V.data.length)}})}}}}};function za(t,r,o){if(t==null)return{};const c={};if(t.image_tokens!=null){const u=Math.floor(t.image_tokens/o),f=t.image_tokens-u*(o-1);c.imageTokens=r===o-1?f:u}if(t.text_tokens!=null){const u=Math.floor(t.text_tokens/o),f=t.text_tokens-u*(o-1);c.textTokens=r===o-1?f:u}return c}async function c2(t){if(!t)return;if(t.type==="url")return Cc(t.url);const r=t.data instanceof Uint8Array?t.data:Yo(t.data);return new Blob([r],{type:t.mediaType})}var Eu=ze(()=>Fe(S({callId:w(),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}))),Au=ze(()=>Fe(S({status:Le(["completed","failed"]),output:w().optional()}))),u2=Fn({id:"openai.apply_patch",inputSchema:Eu,outputSchema:Au}),d2=u2,f2=ze(()=>Fe(S({code:w().nullish(),containerId:w()}))),h2=ze(()=>Fe(S({outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullish()}))),p2=ze(()=>Fe(S({container:Pe([w(),S({fileIds:ye(w()).optional()})]).optional()}))),m2=Fn({id:"openai.code_interpreter",inputSchema:f2,outputSchema:h2}),g2=(t={})=>m2(t),x2=ze(()=>Fe(S({name:w(),description:w().optional(),format:Pe([S({type:G("grammar"),syntax:Le(["regex","lark"]),definition:w()}),S({type:G("text")})]).optional()}))),y2=ze(()=>Fe(w())),w2=gm({id:"openai.custom",inputSchema:y2}),_2=t=>w2(t),Iu=S({key:w(),type:Le(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Pe([w(),Q(),Tt(),ye(w())])}),Su=S({type:Le(["and","or"]),filters:ye(Pe([Iu,Xo(()=>Su)]))}),v2=ze(()=>Fe(S({vectorStoreIds:ye(w()),maxNumResults:Q().optional(),ranking:S({ranker:w().optional(),scoreThreshold:Q().optional()}).optional(),filters:Pe([Iu,Su]).optional()}))),C2=ze(()=>Fe(S({queries:ye(w()),results:ye(S({attributes:gt(w(),Tr()),fileId:w(),filename:w(),score:Q(),text:w()})).nullable()}))),b2=Fn({id:"openai.file_search",inputSchema:S({}),outputSchema:C2}),E2=ze(()=>Fe(S({background:Le(["auto","opaque","transparent"]).optional(),inputFidelity:Le(["low","high"]).optional(),inputImageMask:S({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Le(["auto"]).optional(),outputCompression:Q().int().min(0).max(100).optional(),outputFormat:Le(["png","jpeg","webp"]).optional(),partialImages:Q().int().min(0).max(3).optional(),quality:Le(["auto","low","medium","high"]).optional(),size:Le(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),A2=ze(()=>Fe(S({}))),I2=ze(()=>Fe(S({result:w()}))),S2=Fn({id:"openai.image_generation",inputSchema:A2,outputSchema:I2}),T2=(t={})=>S2(t),Tu=ze(()=>Fe(S({action:S({type:G("exec"),command:ye(w()),timeoutMs:Q().optional(),user:w().optional(),workingDirectory:w().optional(),env:gt(w(),w()).optional()})}))),Nu=ze(()=>Fe(S({output:w()}))),N2=Fn({id:"openai.local_shell",inputSchema:Tu,outputSchema:Nu}),Ou=ze(()=>Fe(S({action:S({commands:ye(w()),timeoutMs:Q().optional(),maxOutputLength:Q().optional()})}))),Po=ze(()=>Fe(S({output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exitCode:Q()})])}))}))),O2=ye(lt("type",[S({type:G("skillReference"),skillId:w(),version:w().optional()}),S({type:G("inline"),name:w(),description:w(),source:S({type:G("base64"),mediaType:G("application/zip"),data:w()})})])).optional(),R2=ze(()=>Fe(S({environment:Pe([S({type:G("containerAuto"),fileIds:ye(w()).optional(),memoryLimit:Le(["1g","4g","16g","64g"]).optional(),networkPolicy:lt("type",[S({type:G("disabled")}),S({type:G("allowlist"),allowedDomains:ye(w()),domainSecrets:ye(S({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:O2}),S({type:G("containerReference"),containerId:w()}),S({type:G("local").optional(),skills:ye(S({name:w(),description:w(),path:w()})).optional()})]).optional()}))),k2=Fn({id:"openai.shell",inputSchema:Ou,outputSchema:Po}),M2=ze(()=>Fe(S({externalWebAccess:Tt().optional(),filters:S({allowedDomains:ye(w()).optional()}).optional(),searchContextSize:Le(["low","medium","high"]).optional(),userLocation:S({type:G("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),D2=ze(()=>Fe(S({}))),P2=ze(()=>Fe(S({action:lt("type",[S({type:G("search"),query:w().optional()}),S({type:G("openPage"),url:w().nullish()}),S({type:G("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).optional()}))),B2=Fn({id:"openai.web_search",inputSchema:D2,outputSchema:P2}),L2=(t={})=>B2(t),F2=ze(()=>Fe(S({searchContextSize:Le(["low","medium","high"]).optional(),userLocation:S({type:G("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),U2=ze(()=>Fe(S({}))),z2=ze(()=>Fe(S({action:lt("type",[S({type:G("search"),query:w().optional()}),S({type:G("openPage"),url:w().nullish()}),S({type:G("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),$2=Fn({id:"openai.web_search_preview",inputSchema:U2,outputSchema:z2}),Bo=Xo(()=>Pe([w(),Q(),Tt(),hc(),ye(Bo),gt(w(),Bo)])),V2=ze(()=>Fe(S({serverLabel:w(),allowedTools:Pe([ye(w()),S({readOnly:Tt().optional(),toolNames:ye(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:gt(w(),w()).optional(),requireApproval:Pe([Le(["always","never"]),S({never:S({toolNames:ye(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Z2=ze(()=>Fe(S({}))),j2=ze(()=>Fe(S({type:G("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:Pe([w(),Bo]).optional()}))),W2=Fn({id:"openai.mcp",inputSchema:Z2,outputSchema:j2}),H2=t=>W2(t),G2={applyPatch:d2,customTool:_2,codeInterpreter:g2,fileSearch:b2,imageGeneration:T2,localShell:N2,shell:k2,webSearchPreview:$2,webSearch:L2,mcp:H2};function $a(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=t.input_tokens,p=t.output_tokens,x=(o=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,_=(u=(c=t.output_tokens_details)==null?void 0:c.reasoning_tokens)!=null?u:0;return{inputTokens:{total:f,noCache:f-x,cacheRead:x,cacheWrite:void 0},outputTokens:{total:p,text:p-_,reasoning:_},raw:t}}function Va(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function X2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,store:f,hasConversation:p=!1,hasLocalShellTool:x=!1,hasShellTool:_=!1,hasApplyPatchTool:g=!1,customProviderToolNames:C}){var A,B,O,k,P,L,Y,Z,$,H,re,j,V;const z=[],M=[],we=new Set;for(const{role:le,content:fe}of t)switch(le){case"system":{switch(o){case"system":{z.push({role:"system",content:fe});break}case"developer":{z.push({role:"developer",content:fe});break}case"remove":{M.push({type:"other",message:"system messages are removed for this model"});break}default:{const ae=o;throw new Error(`Unsupported system message mode: ${ae}`)}}break}case"user":{z.push({role:"user",content:fe.map((ae,X)=>{var D,K,W;switch(ae.type){case"text":return{type:"input_text",text:ae.text};case"file":if(ae.mediaType.startsWith("image/")){const ee=ae.mediaType==="image/*"?"image/jpeg":ae.mediaType;return{type:"input_image",...ae.data instanceof URL?{image_url:ae.data.toString()}:typeof ae.data=="string"&&Va(ae.data,u)?{file_id:ae.data}:{image_url:`data:${ee};base64,${Ar(ae.data)}`},detail:(K=(D=ae.providerOptions)==null?void 0:D[c])==null?void 0:K.imageDetail}}else{if(ae.mediaType==="application/pdf")return ae.data instanceof URL?{type:"input_file",file_url:ae.data.toString()}:{type:"input_file",...typeof ae.data=="string"&&Va(ae.data,u)?{file_id:ae.data}:{filename:(W=ae.filename)!=null?W:`part-${X}.pdf`,file_data:`data:application/pdf;base64,${Ar(ae.data)}`}};throw new Dn({functionality:`file part media type ${ae.mediaType}`})}}})});break}case"assistant":{const ae={};for(const X of fe)switch(X.type){case"text":{const D=(A=X.providerOptions)==null?void 0:A[c],K=D?.itemId,W=D?.phase;if(p&&K!=null)break;if(f&&K!=null){z.push({type:"item_reference",id:K});break}z.push({role:"assistant",content:[{type:"output_text",text:X.text}],id:K,...W!=null&&{phase:W}});break}case"tool-call":{const D=(L=(O=(B=X.providerOptions)==null?void 0:B[c])==null?void 0:O.itemId)!=null?L:(P=(k=X.providerMetadata)==null?void 0:k[c])==null?void 0:P.itemId;if(p&&D!=null)break;if(X.providerExecuted){f&&D!=null&&z.push({type:"item_reference",id:D});break}if(f&&D!=null){z.push({type:"item_reference",id:D});break}const K=r.toProviderToolName(X.toolName);if(x&&K==="local_shell"){const W=await Wt({value:X.input,schema:Tu});z.push({type:"local_shell_call",call_id:X.toolCallId,id:D,action:{type:"exec",command:W.action.command,timeout_ms:W.action.timeoutMs,user:W.action.user,working_directory:W.action.workingDirectory,env:W.action.env}});break}if(_&&K==="shell"){const W=await Wt({value:X.input,schema:Ou});z.push({type:"shell_call",call_id:X.toolCallId,id:D,status:"completed",action:{commands:W.action.commands,timeout_ms:W.action.timeoutMs,max_output_length:W.action.maxOutputLength}});break}if(g&&K==="apply_patch"){const W=await Wt({value:X.input,schema:Eu});z.push({type:"apply_patch_call",call_id:W.callId,id:D,status:"completed",operation:W.operation});break}if(C?.has(K)){z.push({type:"custom_tool_call",call_id:X.toolCallId,name:K,input:typeof X.input=="string"?X.input:JSON.stringify(X.input),id:D});break}z.push({type:"function_call",call_id:X.toolCallId,name:K,arguments:JSON.stringify(X.input),id:D});break}case"tool-result":{if(X.output.type==="execution-denied"||X.output.type==="json"&&typeof X.output.value=="object"&&X.output.value!=null&&"type"in X.output.value&&X.output.value.type==="execution-denied"||p)break;const D=r.toProviderToolName(X.toolName);if(_&&D==="shell"){if(X.output.type==="json"){const K=await Wt({value:X.output.value,schema:Po});z.push({type:"shell_call_output",call_id:X.toolCallId,output:K.output.map(W=>({stdout:W.stdout,stderr:W.stderr,outcome:W.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:W.outcome.exitCode}}))})}break}if(f){const K=($=(Z=(Y=X.providerOptions)==null?void 0:Y[c])==null?void 0:Z.itemId)!=null?$:X.toolCallId;z.push({type:"item_reference",id:K})}else M.push({type:"other",message:`Results for OpenAI tool ${X.toolName} are not sent to the API when store is false`});break}case"reasoning":{const D=await Bn({provider:c,providerOptions:X.providerOptions,schema:q2}),K=D?.itemId;if(p&&K!=null)break;if(K!=null){const W=ae[K];if(f)W===void 0&&(z.push({type:"item_reference",id:K}),ae[K]={type:"reasoning",id:K,summary:[]});else{const ee=[];X.text.length>0?ee.push({type:"summary_text",text:X.text}):W!==void 0&&M.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(X)}.`}),W===void 0?(ae[K]={type:"reasoning",id:K,encrypted_content:D?.reasoningEncryptedContent,summary:ee},z.push(ae[K])):(W.summary.push(...ee),D?.reasoningEncryptedContent!=null&&(W.encrypted_content=D.reasoningEncryptedContent))}}else{const W=D?.reasoningEncryptedContent;if(W!=null){const ee=[];X.text.length>0&&ee.push({type:"summary_text",text:X.text}),z.push({type:"reasoning",encrypted_content:W,summary:ee})}else M.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(X)}.`})}break}}break}case"tool":{for(const ae of fe){if(ae.type==="tool-approval-response"){const W=ae;if(we.has(W.approvalId))continue;we.add(W.approvalId),f&&z.push({type:"item_reference",id:W.approvalId}),z.push({type:"mcp_approval_response",approval_request_id:W.approvalId,approve:W.approved});continue}const X=ae.output;if(X.type==="execution-denied"&&((re=(H=X.providerOptions)==null?void 0:H.openai)==null?void 0:re.approvalId))continue;const D=r.toProviderToolName(ae.toolName);if(x&&D==="local_shell"&&X.type==="json"){const W=await Wt({value:X.value,schema:Nu});z.push({type:"local_shell_call_output",call_id:ae.toolCallId,output:W.output});continue}if(_&&D==="shell"&&X.type==="json"){const W=await Wt({value:X.value,schema:Po});z.push({type:"shell_call_output",call_id:ae.toolCallId,output:W.output.map(ee=>({stdout:ee.stdout,stderr:ee.stderr,outcome:ee.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ee.outcome.exitCode}}))});continue}if(g&&ae.toolName==="apply_patch"&&X.type==="json"){const W=await Wt({value:X.value,schema:Au});z.push({type:"apply_patch_call_output",call_id:ae.toolCallId,status:W.status,output:W.output});continue}if(C?.has(D)){let W;switch(X.type){case"text":case"error-text":W=X.value;break;case"execution-denied":W=(j=X.reason)!=null?j:"Tool execution denied.";break;case"json":case"error-json":W=JSON.stringify(X.value);break;case"content":W=X.value.map(ee=>{var he;switch(ee.type){case"text":return{type:"input_text",text:ee.text};case"image-data":return{type:"input_image",image_url:`data:${ee.mediaType};base64,${ee.data}`};case"image-url":return{type:"input_image",image_url:ee.url};case"file-data":return{type:"input_file",filename:(he=ee.filename)!=null?he:"data",file_data:`data:${ee.mediaType};base64,${ee.data}`};default:M.push({type:"other",message:`unsupported custom tool content part type: ${ee.type}`});return}}).filter(xa);break;default:W=""}z.push({type:"custom_tool_call_output",call_id:ae.toolCallId,output:W});continue}let K;switch(X.type){case"text":case"error-text":K=X.value;break;case"execution-denied":K=(V=X.reason)!=null?V:"Tool execution denied.";break;case"json":case"error-json":K=JSON.stringify(X.value);break;case"content":K=X.value.map(W=>{var ee;switch(W.type){case"text":return{type:"input_text",text:W.text};case"image-data":return{type:"input_image",image_url:`data:${W.mediaType};base64,${W.data}`};case"image-url":return{type:"input_image",image_url:W.url};case"file-data":return{type:"input_file",filename:(ee=W.filename)!=null?ee:"data",file_data:`data:${W.mediaType};base64,${W.data}`};default:{M.push({type:"other",message:`unsupported tool content part type: ${W.type}`});return}}}).filter(xa);break}z.push({type:"function_call_output",call_id:ae.toolCallId,output:K})}break}default:{const ae=le;throw new Error(`Unsupported role: ${ae}`)}}return{input:z,warnings:M}}var q2=S({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function Za({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var Y2=ze(()=>Fe(Pe([S({type:G("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ye(S({token:w(),logprob:Q(),top_logprobs:ye(S({token:w(),logprob:Q()}))})).nullish()}),S({type:Le(["response.completed","response.incomplete"]),response:S({incomplete_details:S({reason:w()}).nullish(),usage:S({input_tokens:Q(),input_tokens_details:S({cached_tokens:Q().nullish()}).nullish(),output_tokens:Q(),output_tokens_details:S({reasoning_tokens:Q().nullish()}).nullish()}),service_tier:w().nullish()})}),S({type:G("response.created"),response:S({id:w(),created_at:Q(),model:w(),service_tier:w().nullish()})}),S({type:G("response.output_item.added"),output_index:Q(),item:lt("type",[S({type:G("message"),id:w(),phase:Le(["commentary","final_answer"]).nullish()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish()}),S({type:G("function_call"),id:w(),call_id:w(),name:w(),arguments:w()}),S({type:G("web_search_call"),id:w(),status:w()}),S({type:G("computer_call"),id:w(),status:w()}),S({type:G("file_search_call"),id:w()}),S({type:G("image_generation_call"),id:w()}),S({type:G("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable(),status:w()}),S({type:G("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w()}),S({type:G("mcp_approval_request"),id:w()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:Q()})])}))})])}),S({type:G("response.output_item.done"),output_index:Q(),item:lt("type",[S({type:G("message"),id:w(),phase:Le(["commentary","final_answer"]).nullish()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish()}),S({type:G("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:G("completed")}),S({type:G("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:G("completed")}),S({type:G("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable()}),S({type:G("image_generation_call"),id:w(),result:w()}),S({type:G("web_search_call"),id:w(),status:w(),action:lt("type",[S({type:G("search"),query:w().nullish(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).nullish()}),S({type:G("open_page"),url:w().nullish()}),S({type:G("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),S({type:G("file_search_call"),id:w(),queries:ye(w()),results:ye(S({attributes:gt(w(),Pe([w(),Q(),Tt()])),file_id:w(),filename:w(),score:Q(),text:w()})).nullish()}),S({type:G("local_shell_call"),id:w(),call_id:w(),action:S({type:G("exec"),command:ye(w()),timeout_ms:Q().optional(),user:w().optional(),working_directory:w().optional(),env:gt(w(),w()).optional()})}),S({type:G("computer_call"),id:w(),status:G("completed")}),S({type:G("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Pe([w(),S({type:w().optional(),code:Pe([Q(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w(),server_label:w(),tools:ye(S({name:w(),description:w().optional(),input_schema:fr(),annotations:gt(w(),Tr()).optional()})),error:Pe([w(),S({type:w().optional(),code:Pe([Q(),w()]).optional(),message:w().optional()}).loose()]).optional()}),S({type:G("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:Q()})])}))})])}),S({type:G("response.function_call_arguments.delta"),item_id:w(),output_index:Q(),delta:w()}),S({type:G("response.custom_tool_call_input.delta"),item_id:w(),output_index:Q(),delta:w()}),S({type:G("response.image_generation_call.partial_image"),item_id:w(),output_index:Q(),partial_image_b64:w()}),S({type:G("response.code_interpreter_call_code.delta"),item_id:w(),output_index:Q(),delta:w()}),S({type:G("response.code_interpreter_call_code.done"),item_id:w(),output_index:Q(),code:w()}),S({type:G("response.output_text.annotation.added"),annotation:lt("type",[S({type:G("url_citation"),start_index:Q(),end_index:Q(),url:w(),title:w()}),S({type:G("file_citation"),file_id:w(),filename:w(),index:Q()}),S({type:G("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:Q(),end_index:Q()}),S({type:G("file_path"),file_id:w(),index:Q()})])}),S({type:G("response.reasoning_summary_part.added"),item_id:w(),summary_index:Q()}),S({type:G("response.reasoning_summary_text.delta"),item_id:w(),summary_index:Q(),delta:w()}),S({type:G("response.reasoning_summary_part.done"),item_id:w(),summary_index:Q()}),S({type:G("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:Q(),delta:w(),obfuscation:w().nullish()}),S({type:G("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:Q(),diff:w()}),S({type:G("error"),sequence_number:Q(),error:S({type:w(),code:w(),message:w(),param:w().nullish()})}),S({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),J2=ze(()=>Fe(S({id:w().optional(),created_at:Q().optional(),error:S({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ye(lt("type",[S({type:G("message"),role:G("assistant"),id:w(),phase:Le(["commentary","final_answer"]).nullish(),content:ye(S({type:G("output_text"),text:w(),logprobs:ye(S({token:w(),logprob:Q(),top_logprobs:ye(S({token:w(),logprob:Q()}))})).nullish(),annotations:ye(lt("type",[S({type:G("url_citation"),start_index:Q(),end_index:Q(),url:w(),title:w()}),S({type:G("file_citation"),file_id:w(),filename:w(),index:Q()}),S({type:G("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:Q(),end_index:Q()}),S({type:G("file_path"),file_id:w(),index:Q()})]))}))}),S({type:G("web_search_call"),id:w(),status:w(),action:lt("type",[S({type:G("search"),query:w().nullish(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).nullish()}),S({type:G("open_page"),url:w().nullish()}),S({type:G("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),S({type:G("file_search_call"),id:w(),queries:ye(w()),results:ye(S({attributes:gt(w(),Pe([w(),Q(),Tt()])),file_id:w(),filename:w(),score:Q(),text:w()})).nullish()}),S({type:G("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable()}),S({type:G("image_generation_call"),id:w(),result:w()}),S({type:G("local_shell_call"),id:w(),call_id:w(),action:S({type:G("exec"),command:ye(w()),timeout_ms:Q().optional(),user:w().optional(),working_directory:w().optional(),env:gt(w(),w()).optional()})}),S({type:G("function_call"),call_id:w(),name:w(),arguments:w(),id:w()}),S({type:G("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),S({type:G("computer_call"),id:w(),status:w().optional()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ye(S({type:G("summary_text"),text:w()}))}),S({type:G("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Pe([w(),S({type:w().optional(),code:Pe([Q(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w(),server_label:w(),tools:ye(S({name:w(),description:w().optional(),input_schema:fr(),annotations:gt(w(),Tr()).optional()})),error:Pe([w(),S({type:w().optional(),code:Pe([Q(),w()]).optional(),message:w().optional()}).loose()]).optional()}),S({type:G("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:Q()})])}))})])).optional(),service_tier:w().nullish(),incomplete_details:S({reason:w()}).nullish(),usage:S({input_tokens:Q(),input_tokens_details:S({cached_tokens:Q().nullish()}).nullish(),output_tokens:Q(),output_tokens_details:S({reasoning_tokens:Q().nullish()}).nullish()}).optional()}))),Ru=20,ja=ze(()=>Fe(S({conversation:w().nullish(),include:ye(Le(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:Pe([Tt(),Q().min(1).max(Ru)]).optional(),maxToolCalls:Q().nullish(),metadata:fr().nullish(),parallelToolCalls:Tt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheRetention:Le(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Le(["auto","flex","priority","default"]).nullish(),store:Tt().nullish(),strictJsonSchema:Tt().nullish(),textVerbosity:Le(["low","medium","high"]).nullish(),truncation:Le(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Le(["system","developer","remove"]).optional(),forceReasoning:Tt().optional()})));async function K2({tools:t,toolChoice:r,toolNameMapping:o,customProviderToolNames:c}){var u;t=t?.length?t:void 0;const f=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:f};const p=[],x=c??new Set;for(const g of t)switch(g.type){case"function":p.push({type:"function",name:g.name,description:g.description,parameters:g.inputSchema,...g.strict!=null?{strict:g.strict}:{}});break;case"provider":{switch(g.id){case"openai.file_search":{const C=await Wt({value:g.args,schema:v2});p.push({type:"file_search",vector_store_ids:C.vectorStoreIds,max_num_results:C.maxNumResults,ranking_options:C.ranking?{ranker:C.ranking.ranker,score_threshold:C.ranking.scoreThreshold}:void 0,filters:C.filters});break}case"openai.local_shell":{p.push({type:"local_shell"});break}case"openai.shell":{const C=await Wt({value:g.args,schema:R2});p.push({type:"shell",...C.environment&&{environment:Q2(C.environment)}});break}case"openai.apply_patch":{p.push({type:"apply_patch"});break}case"openai.web_search_preview":{const C=await Wt({value:g.args,schema:F2});p.push({type:"web_search_preview",search_context_size:C.searchContextSize,user_location:C.userLocation});break}case"openai.web_search":{const C=await Wt({value:g.args,schema:M2});p.push({type:"web_search",filters:C.filters!=null?{allowed_domains:C.filters.allowedDomains}:void 0,external_web_access:C.externalWebAccess,search_context_size:C.searchContextSize,user_location:C.userLocation});break}case"openai.code_interpreter":{const C=await Wt({value:g.args,schema:p2});p.push({type:"code_interpreter",container:C.container==null?{type:"auto",file_ids:void 0}:typeof C.container=="string"?C.container:{type:"auto",file_ids:C.container.fileIds}});break}case"openai.image_generation":{const C=await Wt({value:g.args,schema:E2});p.push({type:"image_generation",background:C.background,input_fidelity:C.inputFidelity,input_image_mask:C.inputImageMask?{file_id:C.inputImageMask.fileId,image_url:C.inputImageMask.imageUrl}:void 0,model:C.model,moderation:C.moderation,partial_images:C.partialImages,quality:C.quality,output_compression:C.outputCompression,output_format:C.outputFormat,size:C.size});break}case"openai.mcp":{const C=await Wt({value:g.args,schema:V2}),A=k=>({tool_names:k.toolNames}),B=C.requireApproval,O=B==null?void 0:typeof B=="string"?B:B.never!=null?{never:A(B.never)}:void 0;p.push({type:"mcp",server_label:C.serverLabel,allowed_tools:Array.isArray(C.allowedTools)?C.allowedTools:C.allowedTools?{read_only:C.allowedTools.readOnly,tool_names:C.allowedTools.toolNames}:void 0,authorization:C.authorization,connector_id:C.connectorId,headers:C.headers,require_approval:O??"never",server_description:C.serverDescription,server_url:C.serverUrl});break}case"openai.custom":{const C=await Wt({value:g.args,schema:x2});p.push({type:"custom",name:C.name,description:C.description,format:C.format}),x.add(C.name);break}}break}default:f.push({type:"unsupported",feature:`function tool ${g}`});break}if(r==null)return{tools:p,toolChoice:void 0,toolWarnings:f};const _=r.type;switch(_){case"auto":case"none":case"required":return{tools:p,toolChoice:_,toolWarnings:f};case"tool":{const g=(u=o?.toProviderToolName(r.toolName))!=null?u:r.toolName;return{tools:p,toolChoice:g==="code_interpreter"||g==="file_search"||g==="image_generation"||g==="web_search_preview"||g==="web_search"||g==="mcp"||g==="apply_patch"?{type:g}:x.has(g)?{type:"custom",name:g}:{type:"function",name:g},toolWarnings:f}}default:{const g=_;throw new Dn({functionality:`tool choice type: ${g}`})}}}function Q2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const o=t;return{type:"container_auto",file_ids:o.fileIds,memory_limit:o.memoryLimit,network_policy:o.networkPolicy==null?void 0:o.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:o.networkPolicy.allowedDomains,domain_secrets:o.networkPolicy.domainSecrets},skills:ex(o.skills)}}return{type:"local",skills:t.skills}}function ex(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function Wa(t){var r,o;const c={};for(const u of t)if(u.role==="assistant")for(const f of u.content){if(f.type!=="tool-call")continue;const p=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.approvalRequestId;p!=null&&(c[p]=f.toolCallId)}return c}var tx=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:o,topP:c,topK:u,presencePenalty:f,frequencyPenalty:p,seed:x,prompt:_,providerOptions:g,tools:C,toolChoice:A,responseFormat:B}){var O,k,P,L,Y,Z,$,H,re;const j=[],V=bu(this.modelId);u!=null&&j.push({type:"unsupported",feature:"topK"}),x!=null&&j.push({type:"unsupported",feature:"seed"}),f!=null&&j.push({type:"unsupported",feature:"presencePenalty"}),p!=null&&j.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&j.push({type:"unsupported",feature:"stopSequences"});const z=this.config.provider.includes("azure")?"azure":"openai";let M=await Bn({provider:z,providerOptions:g,schema:ja});M==null&&z!=="openai"&&(M=await Bn({provider:"openai",providerOptions:g,schema:ja}));const we=(O=M?.forceReasoning)!=null?O:V.isReasoningModel;M?.conversation&&M?.previousResponseId&&j.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const le=Qh({tools:C,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"},resolveProviderToolName:Ae=>Ae.id==="openai.custom"?Ae.args.name:void 0}),fe=new Set,{tools:ae,toolChoice:X,toolWarnings:D}=await K2({tools:C,toolChoice:A,toolNameMapping:le,customProviderToolNames:fe}),{input:K,warnings:W}=await X2({prompt:_,toolNameMapping:le,systemMessageMode:(k=M?.systemMessageMode)!=null?k:we?"developer":V.systemMessageMode,providerOptionsName:z,fileIdPrefixes:this.config.fileIdPrefixes,store:(P=M?.store)!=null?P:!0,hasConversation:M?.conversation!=null,hasLocalShellTool:de("openai.local_shell"),hasShellTool:de("openai.shell"),hasApplyPatchTool:de("openai.apply_patch"),customProviderToolNames:fe.size>0?fe:void 0});j.push(...W);const ee=(L=M?.strictJsonSchema)!=null?L:!0;let he=M?.include;function ge(Ae){he==null?he=[Ae]:he.includes(Ae)||(he=[...he,Ae])}function de(Ae){return C?.find(Ne=>Ne.type==="provider"&&Ne.id===Ae)!=null}const Ce=typeof M?.logprobs=="number"?M?.logprobs:M?.logprobs===!0?Ru:void 0;Ce&&ge("message.output_text.logprobs");const Ve=(Y=C?.find(Ae=>Ae.type==="provider"&&(Ae.id==="openai.web_search"||Ae.id==="openai.web_search_preview")))==null?void 0:Y.name;Ve&&ge("web_search_call.action.sources"),de("openai.code_interpreter")&&ge("code_interpreter_call.outputs");const Me=M?.store;Me===!1&&we&&ge("reasoning.encrypted_content");const Ye={model:this.modelId,input:K,temperature:r,top_p:c,max_output_tokens:t,...(B?.type==="json"||M?.textVerbosity)&&{text:{...B?.type==="json"&&{format:B.schema!=null?{type:"json_schema",strict:ee,name:(Z=B.name)!=null?Z:"response",description:B.description,schema:B.schema}:{type:"json_object"}},...M?.textVerbosity&&{verbosity:M.textVerbosity}}},conversation:M?.conversation,max_tool_calls:M?.maxToolCalls,metadata:M?.metadata,parallel_tool_calls:M?.parallelToolCalls,previous_response_id:M?.previousResponseId,store:Me,user:M?.user,instructions:M?.instructions,service_tier:M?.serviceTier,include:he,prompt_cache_key:M?.promptCacheKey,prompt_cache_retention:M?.promptCacheRetention,safety_identifier:M?.safetyIdentifier,top_logprobs:Ce,truncation:M?.truncation,...we&&(M?.reasoningEffort!=null||M?.reasoningSummary!=null)&&{reasoning:{...M?.reasoningEffort!=null&&{effort:M.reasoningEffort},...M?.reasoningSummary!=null&&{summary:M.reasoningSummary}}}};we?M?.reasoningEffort==="none"&&V.supportsNonReasoningParameters||(Ye.temperature!=null&&(Ye.temperature=void 0,j.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Ye.top_p!=null&&(Ye.top_p=void 0,j.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(M?.reasoningEffort!=null&&j.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),M?.reasoningSummary!=null&&j.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),M?.serviceTier==="flex"&&!V.supportsFlexProcessing&&(j.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Ye.service_tier),M?.serviceTier==="priority"&&!V.supportsPriorityProcessing&&(j.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Ye.service_tier);const ie=(re=(H=($=C?.find(Ae=>Ae.type==="provider"&&Ae.id==="openai.shell"))==null?void 0:$.args)==null?void 0:H.environment)==null?void 0:re.type,ke=ie==="containerAuto"||ie==="containerReference";return{webSearchToolName:Ve,args:{...Ye,tools:ae,tool_choice:X},warnings:[...j,...D],store:Me,toolNameMapping:le,providerOptionsName:z,isShellProviderExecuted:ke}}async doGenerate(t){var r,o,c,u,f,p,x,_,g,C,A,B,O,k,P,L,Y,Z,$,H,re,j,V,z,M;const{args:we,warnings:le,webSearchToolName:fe,toolNameMapping:ae,providerOptionsName:X,isShellProviderExecuted:D}=await this.getArgs(t),K=this.config.url({path:"/responses",modelId:this.modelId}),W=Wa(t.prompt),{responseHeaders:ee,value:he,rawValue:ge}=await Ln({url:K,headers:vn(this.config.headers(),t.headers),body:we,failedResponseHandler:Cn,successfulResponseHandler:ur(J2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(he.error)throw new sn({message:he.error.message,url:K,requestBodyValues:we,statusCode:400,responseHeaders:ee,responseBody:ge,isRetryable:!1});const de=[],Ce=[];let Ve=!1;for(const ie of he.output)switch(ie.type){case"reasoning":{ie.summary.length===0&&ie.summary.push({type:"summary_text",text:""});for(const ke of ie.summary)de.push({type:"reasoning",text:ke.text,providerMetadata:{[X]:{itemId:ie.id,reasoningEncryptedContent:(r=ie.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("image_generation"),result:{result:ie.result}});break}case"local_shell_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("local_shell"),input:JSON.stringify({action:ie.action}),providerMetadata:{[X]:{itemId:ie.id}}});break}case"shell_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("shell"),input:JSON.stringify({action:{commands:ie.action.commands}}),...D&&{providerExecuted:!0},providerMetadata:{[X]:{itemId:ie.id}}});break}case"shell_call_output":{de.push({type:"tool-result",toolCallId:ie.call_id,toolName:ae.toCustomToolName("shell"),result:{output:ie.output.map(ke=>({stdout:ke.stdout,stderr:ke.stderr,outcome:ke.outcome.type==="exit"?{type:"exit",exitCode:ke.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ke of ie.content){(c=(o=t.providerOptions)==null?void 0:o[X])!=null&&c.logprobs&&ke.logprobs&&Ce.push(ke.logprobs);const Ae={itemId:ie.id,...ie.phase!=null&&{phase:ie.phase},...ke.annotations.length>0&&{annotations:ke.annotations}};de.push({type:"text",text:ke.text,providerMetadata:{[X]:Ae}});for(const Ne of ke.annotations)Ne.type==="url_citation"?de.push({type:"source",sourceType:"url",id:(p=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?p:qt(),url:Ne.url,title:Ne.title}):Ne.type==="file_citation"?de.push({type:"source",sourceType:"document",id:(g=(_=(x=this.config).generateId)==null?void 0:_.call(x))!=null?g:qt(),mediaType:"text/plain",title:Ne.filename,filename:Ne.filename,providerMetadata:{[X]:{type:Ne.type,fileId:Ne.file_id,index:Ne.index}}}):Ne.type==="container_file_citation"?de.push({type:"source",sourceType:"document",id:(B=(A=(C=this.config).generateId)==null?void 0:A.call(C))!=null?B:qt(),mediaType:"text/plain",title:Ne.filename,filename:Ne.filename,providerMetadata:{[X]:{type:Ne.type,fileId:Ne.file_id,containerId:Ne.container_id}}}):Ne.type==="file_path"&&de.push({type:"source",sourceType:"document",id:(P=(k=(O=this.config).generateId)==null?void 0:k.call(O))!=null?P:qt(),mediaType:"application/octet-stream",title:Ne.file_id,filename:Ne.file_id,providerMetadata:{[X]:{type:Ne.type,fileId:Ne.file_id,index:Ne.index}}})}break}case"function_call":{Ve=!0,de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ie.name,input:ie.arguments,providerMetadata:{[X]:{itemId:ie.id}}});break}case"custom_tool_call":{Ve=!0;const ke=ae.toCustomToolName(ie.name);de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ke,input:JSON.stringify(ie.input),providerMetadata:{[X]:{itemId:ie.id}}});break}case"web_search_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName(fe??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName(fe??"web_search"),result:Ga(ie.action)});break}case"mcp_call":{const ke=ie.approval_request_id!=null&&(L=W[ie.approval_request_id])!=null?L:ie.id,Ae=`mcp.${ie.name}`;de.push({type:"tool-call",toolCallId:ke,toolName:Ae,input:ie.arguments,providerExecuted:!0,dynamic:!0}),de.push({type:"tool-result",toolCallId:ke,toolName:Ae,result:{type:"call",serverLabel:ie.server_label,name:ie.name,arguments:ie.arguments,...ie.output!=null?{output:ie.output}:{},...ie.error!=null?{error:ie.error}:{}},providerMetadata:{[X]:{itemId:ie.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ke=(Y=ie.approval_request_id)!=null?Y:ie.id,Ae=(H=($=(Z=this.config).generateId)==null?void 0:$.call(Z))!=null?H:qt(),Ne=`mcp.${ie.name}`;de.push({type:"tool-call",toolCallId:Ae,toolName:Ne,input:ie.arguments,providerExecuted:!0,dynamic:!0}),de.push({type:"tool-approval-request",approvalId:ke,toolCallId:Ae});break}case"computer_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:ie.status||"completed"}});break}case"file_search_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("file_search"),result:{queries:ie.queries,results:(j=(re=ie.results)==null?void 0:re.map(ke=>({attributes:ke.attributes,fileId:ke.file_id,filename:ke.filename,score:ke.score,text:ke.text})))!=null?j:null}});break}case"code_interpreter_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("code_interpreter"),input:JSON.stringify({code:ie.code,containerId:ie.container_id}),providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("code_interpreter"),result:{outputs:ie.outputs}});break}case"apply_patch_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("apply_patch"),input:JSON.stringify({callId:ie.call_id,operation:ie.operation}),providerMetadata:{[X]:{itemId:ie.id}}});break}}const Me={[X]:{responseId:he.id,...Ce.length>0?{logprobs:Ce}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},Ye=he.usage;return{content:de,finishReason:{unified:Za({finishReason:(V=he.incomplete_details)==null?void 0:V.reason,hasFunctionCall:Ve}),raw:(M=(z=he.incomplete_details)==null?void 0:z.reason)!=null?M:void 0},usage:$a(Ye),request:{body:we},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:ee,body:ge},providerMetadata:Me,warnings:le}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:p,isShellProviderExecuted:x}=await this.getArgs(t),{responseHeaders:_,value:g}=await Ln({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:Cn,successfulResponseHandler:es(Y2),abortSignal:t.abortSignal,fetch:this.config.fetch}),C=this,A=Wa(t.prompt),B=new Map;let O={unified:"other",raw:void 0},k;const P=[];let L=null;const Y={},Z=[];let $,H=!1;const re={};let j;return{stream:g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:o})},transform(V,z){var M,we,le,fe,ae,X,D,K,W,ee,he,ge,de,Ce,Ve,Me,Ye,ie,ke,Ae,Ne,ot,Xe,$t,Ue,pn,Vt,bn,wt,Je,je,En;if(t.includeRawChunks&&z.enqueue({type:"raw",rawValue:V.rawValue}),!V.success){O={unified:"error",raw:void 0},z.enqueue({type:"error",error:V.error});return}const T=V.value;if(Ha(T)){if(T.item.type==="function_call")Y[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:T.item.name});else if(T.item.type==="custom_tool_call"){const pe=u.toCustomToolName(T.item.name);Y[T.output_index]={toolName:pe,toolCallId:T.item.call_id},z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:pe})}else if(T.item.type==="web_search_call")Y[T.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:T.item.id},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),z.enqueue({type:"tool-input-end",id:T.item.id}),z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(T.item.type==="computer_call")Y[T.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:T.item.id},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(T.item.type==="code_interpreter_call")Y[T.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:T.item.id,codeInterpreter:{containerId:T.item.container_id}},z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),z.enqueue({type:"tool-input-delta",id:T.item.id,delta:`{"containerId":"${T.item.container_id}","code":"`});else if(T.item.type==="file_search_call")z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(T.item.type==="image_generation_call")z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(T.item.type==="mcp_call"||T.item.type==="mcp_list_tools"||T.item.type==="mcp_approval_request"))if(T.item.type==="apply_patch_call"){const{call_id:pe,operation:_t}=T.item;if(Y[T.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:pe,applyPatch:{hasDiff:_t.type==="delete_file",endEmitted:_t.type==="delete_file"}},z.enqueue({type:"tool-input-start",id:pe,toolName:u.toCustomToolName("apply_patch")}),_t.type==="delete_file"){const vt=JSON.stringify({callId:pe,operation:_t});z.enqueue({type:"tool-input-delta",id:pe,delta:vt}),z.enqueue({type:"tool-input-end",id:pe})}else z.enqueue({type:"tool-input-delta",id:pe,delta:`{"callId":"${sr(pe)}","operation":{"type":"${sr(_t.type)}","path":"${sr(_t.path)}","diff":"`})}else T.item.type==="shell_call"?Y[T.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:T.item.call_id}:T.item.type==="shell_call_output"||(T.item.type==="message"?(Z.splice(0,Z.length),$=(M=T.item.phase)!=null?M:void 0,z.enqueue({type:"text-start",id:T.item.id,providerMetadata:{[p]:{itemId:T.item.id,...T.item.phase!=null&&{phase:T.item.phase}}}})):Ha(T)&&T.item.type==="reasoning"&&(re[T.item.id]={encryptedContent:T.item.encrypted_content,summaryParts:{0:"active"}},z.enqueue({type:"reasoning-start",id:`${T.item.id}:0`,providerMetadata:{[p]:{itemId:T.item.id,reasoningEncryptedContent:(we=T.item.encrypted_content)!=null?we:null}}})))}else if(rx(T)){if(T.item.type==="message"){const pe=(le=T.item.phase)!=null?le:$;$=void 0,z.enqueue({type:"text-end",id:T.item.id,providerMetadata:{[p]:{itemId:T.item.id,...pe!=null&&{phase:pe},...Z.length>0&&{annotations:Z}}}})}else if(T.item.type==="function_call")Y[T.output_index]=void 0,H=!0,z.enqueue({type:"tool-input-end",id:T.item.call_id}),z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:T.item.name,input:T.item.arguments,providerMetadata:{[p]:{itemId:T.item.id}}});else if(T.item.type==="custom_tool_call"){Y[T.output_index]=void 0,H=!0;const pe=u.toCustomToolName(T.item.name);z.enqueue({type:"tool-input-end",id:T.item.call_id}),z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:pe,input:JSON.stringify(T.item.input),providerMetadata:{[p]:{itemId:T.item.id}}})}else if(T.item.type==="web_search_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Ga(T.item.action)});else if(T.item.type==="computer_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-input-end",id:T.item.id}),z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:T.item.status||"completed"}});else if(T.item.type==="file_search_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:T.item.queries,results:(ae=(fe=T.item.results)==null?void 0:fe.map(pe=>({attributes:pe.attributes,fileId:pe.file_id,filename:pe.filename,score:pe.score,text:pe.text})))!=null?ae:null}});else if(T.item.type==="code_interpreter_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:T.item.outputs}});else if(T.item.type==="image_generation_call")z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:T.item.result}});else if(T.item.type==="mcp_call"){Y[T.output_index]=void 0;const pe=(X=T.item.approval_request_id)!=null?X:void 0,_t=pe!=null&&(K=(D=B.get(pe))!=null?D:A[pe])!=null?K:T.item.id,vt=`mcp.${T.item.name}`;z.enqueue({type:"tool-call",toolCallId:_t,toolName:vt,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),z.enqueue({type:"tool-result",toolCallId:_t,toolName:vt,result:{type:"call",serverLabel:T.item.server_label,name:T.item.name,arguments:T.item.arguments,...T.item.output!=null?{output:T.item.output}:{},...T.item.error!=null?{error:T.item.error}:{}},providerMetadata:{[p]:{itemId:T.item.id}}})}else if(T.item.type==="mcp_list_tools")Y[T.output_index]=void 0;else if(T.item.type==="apply_patch_call"){const pe=Y[T.output_index];pe?.applyPatch&&!pe.applyPatch.endEmitted&&T.item.operation.type!=="delete_file"&&(pe.applyPatch.hasDiff||z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.item.operation.diff)}),z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}}'}),z.enqueue({type:"tool-input-end",id:pe.toolCallId}),pe.applyPatch.endEmitted=!0),pe&&T.item.status==="completed"&&z.enqueue({type:"tool-call",toolCallId:pe.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:T.item.call_id,operation:T.item.operation}),providerMetadata:{[p]:{itemId:T.item.id}}}),Y[T.output_index]=void 0}else if(T.item.type==="mcp_approval_request"){Y[T.output_index]=void 0;const pe=(he=(ee=(W=C.config).generateId)==null?void 0:ee.call(W))!=null?he:qt(),_t=(ge=T.item.approval_request_id)!=null?ge:T.item.id;B.set(_t,pe);const vt=`mcp.${T.item.name}`;z.enqueue({type:"tool-call",toolCallId:pe,toolName:vt,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),z.enqueue({type:"tool-approval-request",approvalId:_t,toolCallId:pe})}else if(T.item.type==="local_shell_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:T.item.action.command,timeoutMs:T.item.action.timeout_ms,user:T.item.action.user,workingDirectory:T.item.action.working_directory,env:T.item.action.env}}),providerMetadata:{[p]:{itemId:T.item.id}}});else if(T.item.type==="shell_call")Y[T.output_index]=void 0,z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:T.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[p]:{itemId:T.item.id}}});else if(T.item.type==="shell_call_output")z.enqueue({type:"tool-result",toolCallId:T.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:T.item.output.map(pe=>({stdout:pe.stdout,stderr:pe.stderr,outcome:pe.outcome.type==="exit"?{type:"exit",exitCode:pe.outcome.exit_code}:{type:"timeout"}}))}});else if(T.item.type==="reasoning"){const pe=re[T.item.id],_t=Object.entries(pe.summaryParts).filter(([vt,Un])=>Un==="active"||Un==="can-conclude").map(([vt])=>vt);for(const vt of _t)z.enqueue({type:"reasoning-end",id:`${T.item.id}:${vt}`,providerMetadata:{[p]:{itemId:T.item.id,reasoningEncryptedContent:(de=T.item.encrypted_content)!=null?de:null}}});delete re[T.item.id]}}else if(sx(T)){const pe=Y[T.output_index];pe!=null&&z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:T.delta})}else if(ax(T)){const pe=Y[T.output_index];pe!=null&&z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:T.delta})}else if(dx(T)){const pe=Y[T.output_index];pe?.applyPatch&&(z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.delta)}),pe.applyPatch.hasDiff=!0)}else if(fx(T)){const pe=Y[T.output_index];pe?.applyPatch&&!pe.applyPatch.endEmitted&&(pe.applyPatch.hasDiff||(z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.diff)}),pe.applyPatch.hasDiff=!0),z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}}'}),z.enqueue({type:"tool-input-end",id:pe.toolCallId}),pe.applyPatch.endEmitted=!0)}else if(lx(T))z.enqueue({type:"tool-result",toolCallId:T.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:T.partial_image_b64},preliminary:!0});else if(cx(T)){const pe=Y[T.output_index];pe!=null&&z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.delta)})}else if(ux(T)){const pe=Y[T.output_index];pe!=null&&(z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}'}),z.enqueue({type:"tool-input-end",id:pe.toolCallId}),z.enqueue({type:"tool-call",toolCallId:pe.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:T.code,containerId:pe.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ox(T))L=T.response.id,z.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1e3),modelId:T.response.model});else if(nx(T))z.enqueue({type:"text-delta",id:T.item_id,delta:T.delta}),(Ve=(Ce=t.providerOptions)==null?void 0:Ce[p])!=null&&Ve.logprobs&&T.logprobs&&P.push(T.logprobs);else if(T.type==="response.reasoning_summary_part.added"){if(T.summary_index>0){const pe=re[T.item_id];pe.summaryParts[T.summary_index]="active";for(const _t of Object.keys(pe.summaryParts))pe.summaryParts[_t]==="can-conclude"&&(z.enqueue({type:"reasoning-end",id:`${T.item_id}:${_t}`,providerMetadata:{[p]:{itemId:T.item_id}}}),pe.summaryParts[_t]="concluded");z.enqueue({type:"reasoning-start",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[p]:{itemId:T.item_id,reasoningEncryptedContent:(Ye=(Me=re[T.item_id])==null?void 0:Me.encryptedContent)!=null?Ye:null}}})}}else T.type==="response.reasoning_summary_text.delta"?z.enqueue({type:"reasoning-delta",id:`${T.item_id}:${T.summary_index}`,delta:T.delta,providerMetadata:{[p]:{itemId:T.item_id}}}):T.type==="response.reasoning_summary_part.done"?f?(z.enqueue({type:"reasoning-end",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[p]:{itemId:T.item_id}}}),re[T.item_id].summaryParts[T.summary_index]="concluded"):re[T.item_id].summaryParts[T.summary_index]="can-conclude":ix(T)?(O={unified:Za({finishReason:(ie=T.response.incomplete_details)==null?void 0:ie.reason,hasFunctionCall:H}),raw:(Ae=(ke=T.response.incomplete_details)==null?void 0:ke.reason)!=null?Ae:void 0},k=T.response.usage,typeof T.response.service_tier=="string"&&(j=T.response.service_tier)):hx(T)?(Z.push(T.annotation),T.annotation.type==="url_citation"?z.enqueue({type:"source",sourceType:"url",id:(Xe=(ot=(Ne=C.config).generateId)==null?void 0:ot.call(Ne))!=null?Xe:qt(),url:T.annotation.url,title:T.annotation.title}):T.annotation.type==="file_citation"?z.enqueue({type:"source",sourceType:"document",id:(pn=(Ue=($t=C.config).generateId)==null?void 0:Ue.call($t))!=null?pn:qt(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[p]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}}):T.annotation.type==="container_file_citation"?z.enqueue({type:"source",sourceType:"document",id:(wt=(bn=(Vt=C.config).generateId)==null?void 0:bn.call(Vt))!=null?wt:qt(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[p]:{type:T.annotation.type,fileId:T.annotation.file_id,containerId:T.annotation.container_id}}}):T.annotation.type==="file_path"&&z.enqueue({type:"source",sourceType:"document",id:(En=(je=(Je=C.config).generateId)==null?void 0:je.call(Je))!=null?En:qt(),mediaType:"application/octet-stream",title:T.annotation.file_id,filename:T.annotation.file_id,providerMetadata:{[p]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}})):px(T)&&z.enqueue({type:"error",error:T})},flush(V){const z={[p]:{responseId:L,...P.length>0?{logprobs:P}:{},...j!==void 0?{serviceTier:j}:{}}};V.enqueue({type:"finish",finishReason:O,usage:$a(k),providerMetadata:z})}})),request:{body:r},response:{headers:_}}}};function nx(t){return t.type==="response.output_text.delta"}function rx(t){return t.type==="response.output_item.done"}function ix(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ox(t){return t.type==="response.created"}function sx(t){return t.type==="response.function_call_arguments.delta"}function ax(t){return t.type==="response.custom_tool_call_input.delta"}function lx(t){return t.type==="response.image_generation_call.partial_image"}function cx(t){return t.type==="response.code_interpreter_call_code.delta"}function ux(t){return t.type==="response.code_interpreter_call_code.done"}function dx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function fx(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function hx(t){return t.type==="response.output_text.annotation.added"}function px(t){return t.type==="error"}function Ga(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function sr(t){return JSON.stringify(t).slice(1,-1)}var mx=ze(()=>Fe(S({instructions:w().nullish(),speed:Q().min(.25).max(4).default(1).nullish()}))),gx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:o="mp3",speed:c,instructions:u,language:f,providerOptions:p}){const x=[],_=await Bn({provider:"openai",providerOptions:p,schema:mx}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:u};if(o&&(["mp3","opus","aac","flac","wav","pcm"].includes(o)?g.response_format=o:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),_){const C={};for(const A in C){const B=C[A];B!==void 0&&(g[A]=B)}}return f&&x.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:g,warnings:x}}async doGenerate(t){var r,o,c;const u=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{requestBody:f,warnings:p}=await this.getArgs(t),{value:x,responseHeaders:_,rawValue:g}=await Ln({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:f,failedResponseHandler:Cn,successfulResponseHandler:ym(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:p,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:_,body:g}}}},xx=ze(()=>Fe(S({text:w(),language:w().nullish(),duration:Q().nullish(),words:ye(S({word:w(),start:Q(),end:Q()})).nullish(),segments:ye(S({id:Q(),seek:Q(),start:Q(),end:Q(),text:w(),tokens:ye(Q()),temperature:Q(),avg_logprob:Q(),compression_ratio:Q(),no_speech_prob:Q()})).nullish()}))),yx=ze(()=>Fe(S({include:ye(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:Q().min(0).max(1).default(0).optional(),timestampGranularities:ye(Le(["word","segment"])).default(["segment"]).optional()}))),Xa={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},wx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:o}){const c=[],u=await Bn({provider:"openai",providerOptions:o,schema:yx}),f=new FormData,p=t instanceof Uint8Array?new Blob([t]):new Blob([Yo(t)]);f.append("model",this.modelId);const x=yp(r);if(f.append("file",new File([p],"audio",{type:r}),`audio.${x}`),u){const _={include:u.include,language:u.language,prompt:u.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:u.temperature,timestamp_granularities:u.timestampGranularities};for(const[g,C]of Object.entries(_))if(C!=null)if(Array.isArray(C))for(const A of C)f.append(`${g}[]`,String(A));else f.append(g,String(C))}return{formData:f,warnings:c}}async doGenerate(t){var r,o,c,u,f,p,x,_;const g=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{formData:C,warnings:A}=await this.getArgs(t),{value:B,responseHeaders:O,rawValue:k}=await Tc({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),formData:C,failedResponseHandler:Cn,successfulResponseHandler:ur(xx),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=B.language!=null&&B.language in Xa?Xa[B.language]:void 0;return{text:B.text,segments:(x=(p=(u=B.segments)==null?void 0:u.map(L=>({text:L.text,startSecond:L.start,endSecond:L.end})))!=null?p:(f=B.words)==null?void 0:f.map(L=>({text:L.word,startSecond:L.start,endSecond:L.end})))!=null?x:[],language:P,durationInSeconds:(_=B.duration)!=null?_:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:O,body:k}}}},_x="3.0.41";function ku(t={}){var r,o;const c=(r=wm(xp({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>bc({Authorization:`Bearer ${gp({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${_x}`),p=P=>new Jg(P,{provider:`${u}.chat`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),x=P=>new t2(P,{provider:`${u}.completion`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),_=P=>new i2(P,{provider:`${u}.embedding`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),g=P=>new l2(P,{provider:`${u}.image`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),C=P=>new wx(P,{provider:`${u}.transcription`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),A=P=>new gx(P,{provider:`${u}.speech`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),B=P=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return O(P)},O=P=>new tx(P,{provider:`${u}.responses`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),k=function(P){return B(P)};return k.specificationVersion="v3",k.languageModel=B,k.chat=p,k.completion=x,k.responses=O,k.embedding=_,k.embeddingModel=_,k.textEmbedding=_,k.textEmbeddingModel=_,k.image=g,k.imageModel=g,k.transcription=C,k.transcriptionModel=C,k.speech=A,k.speechModel=A,k.tools=G2,k}ku();const vx={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class Cx{constructor(r={}){this.option=r}async traverse(r){const o=v.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",o),(async()=>{let u,f,p,x,_;for await(const g of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+g.type,g),g.type){case"start":u=v.reactive({running:!0,steps:[]}),o.value=u,this.option.onStart?.(u);break;case"start-step":f=v.reactive({running:!0,contents:[],request:g.request}),u.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":p=v.reactive({type:"reasoning",id:g.id,running:!0,text:""}),f.contents.push(p),this.option.onReasoning?.(p);break;case"reasoning-delta":p.text+=g.text;break;case"reasoning-end":p.running=!1;break;case"text-start":x=v.reactive({type:"text",id:g.id,running:!0,text:""}),f.contents.push(x),this.option.onText?.(x);break;case"text-delta":x.text+=g.text;break;case"text-end":x.running=!1;break;case"tool-input-start":_=v.reactive({type:"tool",running:!0,id:g.id,toolCallId:g.id,title:"",toolName:g.toolName,dynamic:g.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(_),this.option.onTool?.(_);break;case"tool-input-delta":_.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":_.input=g.input;break;case"tool-result":_.output=g.output,_.running=!1;break;case"tool-error":_.error=g.error,_.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":u.running=!1,u.finishReason=g.finishReason,u.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":u&&(u.running=!1,u.error=g.error,u.finishReason="error"),this.option.onFinish?.();break;case"abort":u&&(u.running=!1,u.error={message:g.reason},u.finishReason="other"),this.option.onFinish?.();break}})(),o}}function bx(t){const r=[];let o=0;for(;o<t.length;){const c="```schemaJson",u=t.indexOf(c,o),f=c.length;if(u===-1){const g=t.slice(o).trim();g&&r.push({type:"markdown",content:g});break}const p=t.slice(o,u).trim();p&&r.push({type:"markdown",content:p});const x=t.indexOf("```",u+f);let _;x===-1?(_=t.slice(u+f).trim(),o=t.length):(_=t.slice(u+f,x).trim(),o=x+3),r.push({type:"schema-card",content:_})}return r}class Ex{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
|
|
54
|
+
${r}:`]}}function Ba({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o!=null?new Date(o*1e3):void 0}}function La(t){switch(t){case"stop":return"stop";case"length":return"length";case"content_filter":return"content-filter";case"function_call":case"tool_calls":return"tool-calls";default:return"other"}}var Qg=ze(()=>Fe(S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w(),logprobs:S({tokens:ye(w()),token_logprobs:ye(ee()),top_logprobs:ye(gt(w(),ee())).nullish()}).nullish()})),usage:S({prompt_tokens:ee(),completion_tokens:ee(),total_tokens:ee()}).nullish()}))),e2=ze(()=>Fe(Pe([S({id:w().nullish(),created:ee().nullish(),model:w().nullish(),choices:ye(S({text:w(),finish_reason:w().nullish(),index:ee(),logprobs:S({tokens:ye(w()),token_logprobs:ye(ee()),top_logprobs:ye(gt(w(),ee())).nullish()}).nullish()})),usage:S({prompt_tokens:ee(),completion_tokens:ee(),total_tokens:ee()}).nullish()}),ns]))),Fa=ze(()=>Fe(S({echo:Tt().optional(),logitBias:gt(w(),ee()).optional(),suffix:w().optional(),user:w().optional(),logprobs:Pe([Tt(),ee()]).optional()}))),t2=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={},this.modelId=t,this.config=r}get providerOptionsName(){return this.config.provider.split(".")[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:t,maxOutputTokens:r,temperature:o,topP:c,topK:u,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:_,tools:g,toolChoice:C,seed:A,providerOptions:P}){const O=[],k={...await Bn({provider:"openai",providerOptions:P,schema:Fa}),...await Bn({provider:this.providerOptionsName,providerOptions:P,schema:Fa})};u!=null&&O.push({type:"unsupported",feature:"topK"}),g?.length&&O.push({type:"unsupported",feature:"tools"}),C!=null&&O.push({type:"unsupported",feature:"toolChoice"}),_!=null&&_.type!=="text"&&O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:B,stopSequences:L}=Kg({prompt:t}),K=[...L??[],...x??[]];return{args:{model:this.modelId,echo:k.echo,logit_bias:k.logitBias,logprobs:k?.logprobs===!0?0:k?.logprobs===!1?void 0:k?.logprobs,suffix:k.suffix,user:k.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:B,stop:K.length>0?K:void 0},warnings:O}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:m}=await Ln({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:o,failedResponseHandler:Cn,successfulResponseHandler:ur(Qg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],_={openai:{}};return x.logprobs!=null&&(_.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Pa(f.usage),finishReason:{unified:La(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:o},response:{...Ba(f),headers:u,body:m},providerMetadata:_,warnings:c}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await Ln({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:c,failedResponseHandler:Cn,successfulResponseHandler:es(e2),abortSignal:t.abortSignal,fetch:this.config.fetch});let m={unified:"other",raw:void 0};const x={openai:{}};let _,g=!0;return{stream:f.pipeThrough(new TransformStream({start(C){C.enqueue({type:"stream-start",warnings:o})},transform(C,A){if(t.includeRawChunks&&A.enqueue({type:"raw",rawValue:C.rawValue}),!C.success){m={unified:"error",raw:void 0},A.enqueue({type:"error",error:C.error});return}const P=C.value;if("error"in P){m={unified:"error",raw:void 0},A.enqueue({type:"error",error:P.error});return}g&&(g=!1,A.enqueue({type:"response-metadata",...Ba(P)}),A.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(_=P.usage);const O=P.choices[0];O?.finish_reason!=null&&(m={unified:La(O.finish_reason),raw:O.finish_reason}),O?.logprobs!=null&&(x.openai.logprobs=O.logprobs),O?.text!=null&&O.text.length>0&&A.enqueue({type:"text-delta",id:"0",delta:O.text})},flush(C){g||C.enqueue({type:"text-end",id:"0"}),C.enqueue({type:"finish",finishReason:m,providerMetadata:x,usage:Pa(_)})}})),request:{body:c},response:{headers:u}}}},n2=ze(()=>Fe(S({dimensions:ee().optional(),user:w().optional()}))),r2=ze(()=>Fe(S({data:ye(S({embedding:ye(ee())})),usage:S({prompt_tokens:ee()}).nullish()}))),i2=class{constructor(t,r){this.specificationVersion="v3",this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=t,this.config=r}get provider(){return this.config.provider}async doEmbed({values:t,headers:r,abortSignal:o,providerOptions:c}){var u;if(t.length>this.maxEmbeddingsPerCall)throw new Vd({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await Bn({provider:"openai",providerOptions:c,schema:n2}))!=null?u:{},{responseHeaders:m,value:x,rawValue:_}=await Ln({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:vn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:Cn,successfulResponseHandler:ur(r2),abortSignal:o,fetch:this.config.fetch});return{warnings:[],embeddings:x.data.map(g=>g.embedding),usage:x.usage?{tokens:x.usage.prompt_tokens}:void 0,response:{headers:m,body:_}}}},Ua=ze(()=>Fe(S({created:ee().nullish(),data:ye(S({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:S({input_tokens:ee().nullish(),output_tokens:ee().nullish(),total_tokens:ee().nullish(),input_tokens_details:S({image_tokens:ee().nullish(),text_tokens:ee().nullish()}).nullish()}).nullish()}))),o2={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},s2=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function a2(t){return s2.some(r=>t.startsWith(r))}var l2=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=o2[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:o,n:c,size:u,aspectRatio:f,seed:m,providerOptions:x,headers:_,abortSignal:g}){var C,A,P,O,k,B,L,K,z,$,W;const X=[];f!=null&&X.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&X.push({type:"unsupported",feature:"seed"});const H=(P=(A=(C=this.config._internal)==null?void 0:C.currentDate)==null?void 0:A.call(C))!=null?P:new Date;if(r!=null){const{value:M,responseHeaders:we}=await Tc({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:vn(this.config.headers(),_),formData:ip({model:this.modelId,prompt:t,image:await Promise.all(r.map(ce=>ce.type==="file"?new Blob([ce.data instanceof Uint8Array?new Blob([ce.data],{type:ce.mediaType}):new Blob([Yo(ce.data)],{type:ce.mediaType})],{type:ce.mediaType}):Cc(ce.url))),mask:o!=null?await c2(o):void 0,n:c,size:u,...(O=x.openai)!=null?O:{}}),failedResponseHandler:Cn,successfulResponseHandler:ur(Ua),abortSignal:g,fetch:this.config.fetch});return{images:M.data.map(ce=>ce.b64_json),warnings:X,usage:M.usage!=null?{inputTokens:(k=M.usage.input_tokens)!=null?k:void 0,outputTokens:(B=M.usage.output_tokens)!=null?B:void 0,totalTokens:(L=M.usage.total_tokens)!=null?L:void 0}:void 0,response:{timestamp:H,modelId:this.modelId,headers:we},providerMetadata:{openai:{images:M.data.map((ce,fe)=>{var ae,q,D,Q,j,te;return{...ce.revised_prompt?{revisedPrompt:ce.revised_prompt}:{},created:(ae=M.created)!=null?ae:void 0,size:(q=M.size)!=null?q:void 0,quality:(D=M.quality)!=null?D:void 0,background:(Q=M.background)!=null?Q:void 0,outputFormat:(j=M.output_format)!=null?j:void 0,...za((te=M.usage)==null?void 0:te.input_tokens_details,fe,M.data.length)}})}}}}const{value:V,responseHeaders:Z}=await Ln({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:vn(this.config.headers(),_),body:{model:this.modelId,prompt:t,n:c,size:u,...(K=x.openai)!=null?K:{},...a2(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Cn,successfulResponseHandler:ur(Ua),abortSignal:g,fetch:this.config.fetch});return{images:V.data.map(M=>M.b64_json),warnings:X,usage:V.usage!=null?{inputTokens:(z=V.usage.input_tokens)!=null?z:void 0,outputTokens:($=V.usage.output_tokens)!=null?$:void 0,totalTokens:(W=V.usage.total_tokens)!=null?W:void 0}:void 0,response:{timestamp:H,modelId:this.modelId,headers:Z},providerMetadata:{openai:{images:V.data.map((M,we)=>{var ce,fe,ae,q,D,Q;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(ce=V.created)!=null?ce:void 0,size:(fe=V.size)!=null?fe:void 0,quality:(ae=V.quality)!=null?ae:void 0,background:(q=V.background)!=null?q:void 0,outputFormat:(D=V.output_format)!=null?D:void 0,...za((Q=V.usage)==null?void 0:Q.input_tokens_details,we,V.data.length)}})}}}}};function za(t,r,o){if(t==null)return{};const c={};if(t.image_tokens!=null){const u=Math.floor(t.image_tokens/o),f=t.image_tokens-u*(o-1);c.imageTokens=r===o-1?f:u}if(t.text_tokens!=null){const u=Math.floor(t.text_tokens/o),f=t.text_tokens-u*(o-1);c.textTokens=r===o-1?f:u}return c}async function c2(t){if(!t)return;if(t.type==="url")return Cc(t.url);const r=t.data instanceof Uint8Array?t.data:Yo(t.data);return new Blob([r],{type:t.mediaType})}var Eu=ze(()=>Fe(S({callId:w(),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}))),Au=ze(()=>Fe(S({status:Le(["completed","failed"]),output:w().optional()}))),u2=Fn({id:"openai.apply_patch",inputSchema:Eu,outputSchema:Au}),d2=u2,f2=ze(()=>Fe(S({code:w().nullish(),containerId:w()}))),h2=ze(()=>Fe(S({outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullish()}))),p2=ze(()=>Fe(S({container:Pe([w(),S({fileIds:ye(w()).optional()})]).optional()}))),m2=Fn({id:"openai.code_interpreter",inputSchema:f2,outputSchema:h2}),g2=(t={})=>m2(t),x2=ze(()=>Fe(S({name:w(),description:w().optional(),format:Pe([S({type:G("grammar"),syntax:Le(["regex","lark"]),definition:w()}),S({type:G("text")})]).optional()}))),y2=ze(()=>Fe(w())),w2=gm({id:"openai.custom",inputSchema:y2}),_2=t=>w2(t),Iu=S({key:w(),type:Le(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Pe([w(),ee(),Tt(),ye(w())])}),Su=S({type:Le(["and","or"]),filters:ye(Pe([Iu,Xo(()=>Su)]))}),v2=ze(()=>Fe(S({vectorStoreIds:ye(w()),maxNumResults:ee().optional(),ranking:S({ranker:w().optional(),scoreThreshold:ee().optional()}).optional(),filters:Pe([Iu,Su]).optional()}))),C2=ze(()=>Fe(S({queries:ye(w()),results:ye(S({attributes:gt(w(),Tr()),fileId:w(),filename:w(),score:ee(),text:w()})).nullable()}))),b2=Fn({id:"openai.file_search",inputSchema:S({}),outputSchema:C2}),E2=ze(()=>Fe(S({background:Le(["auto","opaque","transparent"]).optional(),inputFidelity:Le(["low","high"]).optional(),inputImageMask:S({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Le(["auto"]).optional(),outputCompression:ee().int().min(0).max(100).optional(),outputFormat:Le(["png","jpeg","webp"]).optional(),partialImages:ee().int().min(0).max(3).optional(),quality:Le(["auto","low","medium","high"]).optional(),size:Le(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),A2=ze(()=>Fe(S({}))),I2=ze(()=>Fe(S({result:w()}))),S2=Fn({id:"openai.image_generation",inputSchema:A2,outputSchema:I2}),T2=(t={})=>S2(t),Tu=ze(()=>Fe(S({action:S({type:G("exec"),command:ye(w()),timeoutMs:ee().optional(),user:w().optional(),workingDirectory:w().optional(),env:gt(w(),w()).optional()})}))),Nu=ze(()=>Fe(S({output:w()}))),N2=Fn({id:"openai.local_shell",inputSchema:Tu,outputSchema:Nu}),Ou=ze(()=>Fe(S({action:S({commands:ye(w()),timeoutMs:ee().optional(),maxOutputLength:ee().optional()})}))),Po=ze(()=>Fe(S({output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exitCode:ee()})])}))}))),O2=ye(lt("type",[S({type:G("skillReference"),skillId:w(),version:w().optional()}),S({type:G("inline"),name:w(),description:w(),source:S({type:G("base64"),mediaType:G("application/zip"),data:w()})})])).optional(),R2=ze(()=>Fe(S({environment:Pe([S({type:G("containerAuto"),fileIds:ye(w()).optional(),memoryLimit:Le(["1g","4g","16g","64g"]).optional(),networkPolicy:lt("type",[S({type:G("disabled")}),S({type:G("allowlist"),allowedDomains:ye(w()),domainSecrets:ye(S({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:O2}),S({type:G("containerReference"),containerId:w()}),S({type:G("local").optional(),skills:ye(S({name:w(),description:w(),path:w()})).optional()})]).optional()}))),k2=Fn({id:"openai.shell",inputSchema:Ou,outputSchema:Po}),M2=ze(()=>Fe(S({externalWebAccess:Tt().optional(),filters:S({allowedDomains:ye(w()).optional()}).optional(),searchContextSize:Le(["low","medium","high"]).optional(),userLocation:S({type:G("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),D2=ze(()=>Fe(S({}))),P2=ze(()=>Fe(S({action:lt("type",[S({type:G("search"),query:w().optional()}),S({type:G("openPage"),url:w().nullish()}),S({type:G("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).optional()}))),B2=Fn({id:"openai.web_search",inputSchema:D2,outputSchema:P2}),L2=(t={})=>B2(t),F2=ze(()=>Fe(S({searchContextSize:Le(["low","medium","high"]).optional(),userLocation:S({type:G("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),U2=ze(()=>Fe(S({}))),z2=ze(()=>Fe(S({action:lt("type",[S({type:G("search"),query:w().optional()}),S({type:G("openPage"),url:w().nullish()}),S({type:G("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),$2=Fn({id:"openai.web_search_preview",inputSchema:U2,outputSchema:z2}),Bo=Xo(()=>Pe([w(),ee(),Tt(),hc(),ye(Bo),gt(w(),Bo)])),V2=ze(()=>Fe(S({serverLabel:w(),allowedTools:Pe([ye(w()),S({readOnly:Tt().optional(),toolNames:ye(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:gt(w(),w()).optional(),requireApproval:Pe([Le(["always","never"]),S({never:S({toolNames:ye(w()).optional()}).optional()})]).optional(),serverDescription:w().optional(),serverUrl:w().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),Z2=ze(()=>Fe(S({}))),j2=ze(()=>Fe(S({type:G("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:Pe([w(),Bo]).optional()}))),W2=Fn({id:"openai.mcp",inputSchema:Z2,outputSchema:j2}),H2=t=>W2(t),G2={applyPatch:d2,customTool:_2,codeInterpreter:g2,fileSearch:b2,imageGeneration:T2,localShell:N2,shell:k2,webSearchPreview:$2,webSearch:L2,mcp:H2};function $a(t){var r,o,c,u;if(t==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};const f=t.input_tokens,m=t.output_tokens,x=(o=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,_=(u=(c=t.output_tokens_details)==null?void 0:c.reasoning_tokens)!=null?u:0;return{inputTokens:{total:f,noCache:f-x,cacheRead:x,cacheWrite:void 0},outputTokens:{total:m,text:m-_,reasoning:_},raw:t}}function Va(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function X2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,store:f,hasConversation:m=!1,hasLocalShellTool:x=!1,hasShellTool:_=!1,hasApplyPatchTool:g=!1,customProviderToolNames:C}){var A,P,O,k,B,L,K,z,$,W,X,H,V;const Z=[],M=[],we=new Set;for(const{role:ce,content:fe}of t)switch(ce){case"system":{switch(o){case"system":{Z.push({role:"system",content:fe});break}case"developer":{Z.push({role:"developer",content:fe});break}case"remove":{M.push({type:"other",message:"system messages are removed for this model"});break}default:{const ae=o;throw new Error(`Unsupported system message mode: ${ae}`)}}break}case"user":{Z.push({role:"user",content:fe.map((ae,q)=>{var D,Q,j;switch(ae.type){case"text":return{type:"input_text",text:ae.text};case"file":if(ae.mediaType.startsWith("image/")){const te=ae.mediaType==="image/*"?"image/jpeg":ae.mediaType;return{type:"input_image",...ae.data instanceof URL?{image_url:ae.data.toString()}:typeof ae.data=="string"&&Va(ae.data,u)?{file_id:ae.data}:{image_url:`data:${te};base64,${Ar(ae.data)}`},detail:(Q=(D=ae.providerOptions)==null?void 0:D[c])==null?void 0:Q.imageDetail}}else{if(ae.mediaType==="application/pdf")return ae.data instanceof URL?{type:"input_file",file_url:ae.data.toString()}:{type:"input_file",...typeof ae.data=="string"&&Va(ae.data,u)?{file_id:ae.data}:{filename:(j=ae.filename)!=null?j:`part-${q}.pdf`,file_data:`data:application/pdf;base64,${Ar(ae.data)}`}};throw new Dn({functionality:`file part media type ${ae.mediaType}`})}}})});break}case"assistant":{const ae={};for(const q of fe)switch(q.type){case"text":{const D=(A=q.providerOptions)==null?void 0:A[c],Q=D?.itemId,j=D?.phase;if(m&&Q!=null)break;if(f&&Q!=null){Z.push({type:"item_reference",id:Q});break}Z.push({role:"assistant",content:[{type:"output_text",text:q.text}],id:Q,...j!=null&&{phase:j}});break}case"tool-call":{const D=(L=(O=(P=q.providerOptions)==null?void 0:P[c])==null?void 0:O.itemId)!=null?L:(B=(k=q.providerMetadata)==null?void 0:k[c])==null?void 0:B.itemId;if(m&&D!=null)break;if(q.providerExecuted){f&&D!=null&&Z.push({type:"item_reference",id:D});break}if(f&&D!=null){Z.push({type:"item_reference",id:D});break}const Q=r.toProviderToolName(q.toolName);if(x&&Q==="local_shell"){const j=await Wt({value:q.input,schema:Tu});Z.push({type:"local_shell_call",call_id:q.toolCallId,id:D,action:{type:"exec",command:j.action.command,timeout_ms:j.action.timeoutMs,user:j.action.user,working_directory:j.action.workingDirectory,env:j.action.env}});break}if(_&&Q==="shell"){const j=await Wt({value:q.input,schema:Ou});Z.push({type:"shell_call",call_id:q.toolCallId,id:D,status:"completed",action:{commands:j.action.commands,timeout_ms:j.action.timeoutMs,max_output_length:j.action.maxOutputLength}});break}if(g&&Q==="apply_patch"){const j=await Wt({value:q.input,schema:Eu});Z.push({type:"apply_patch_call",call_id:j.callId,id:D,status:"completed",operation:j.operation});break}if(C?.has(Q)){Z.push({type:"custom_tool_call",call_id:q.toolCallId,name:Q,input:typeof q.input=="string"?q.input:JSON.stringify(q.input),id:D});break}Z.push({type:"function_call",call_id:q.toolCallId,name:Q,arguments:JSON.stringify(q.input),id:D});break}case"tool-result":{if(q.output.type==="execution-denied"||q.output.type==="json"&&typeof q.output.value=="object"&&q.output.value!=null&&"type"in q.output.value&&q.output.value.type==="execution-denied"||m)break;const D=r.toProviderToolName(q.toolName);if(_&&D==="shell"){if(q.output.type==="json"){const Q=await Wt({value:q.output.value,schema:Po});Z.push({type:"shell_call_output",call_id:q.toolCallId,output:Q.output.map(j=>({stdout:j.stdout,stderr:j.stderr,outcome:j.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:j.outcome.exitCode}}))})}break}if(f){const Q=($=(z=(K=q.providerOptions)==null?void 0:K[c])==null?void 0:z.itemId)!=null?$:q.toolCallId;Z.push({type:"item_reference",id:Q})}else M.push({type:"other",message:`Results for OpenAI tool ${q.toolName} are not sent to the API when store is false`});break}case"reasoning":{const D=await Bn({provider:c,providerOptions:q.providerOptions,schema:q2}),Q=D?.itemId;if(m&&Q!=null)break;if(Q!=null){const j=ae[Q];if(f)j===void 0&&(Z.push({type:"item_reference",id:Q}),ae[Q]={type:"reasoning",id:Q,summary:[]});else{const te=[];q.text.length>0?te.push({type:"summary_text",text:q.text}):j!==void 0&&M.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(q)}.`}),j===void 0?(ae[Q]={type:"reasoning",id:Q,encrypted_content:D?.reasoningEncryptedContent,summary:te},Z.push(ae[Q])):(j.summary.push(...te),D?.reasoningEncryptedContent!=null&&(j.encrypted_content=D.reasoningEncryptedContent))}}else{const j=D?.reasoningEncryptedContent;if(j!=null){const te=[];q.text.length>0&&te.push({type:"summary_text",text:q.text}),Z.push({type:"reasoning",encrypted_content:j,summary:te})}else M.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(q)}.`})}break}}break}case"tool":{for(const ae of fe){if(ae.type==="tool-approval-response"){const j=ae;if(we.has(j.approvalId))continue;we.add(j.approvalId),f&&Z.push({type:"item_reference",id:j.approvalId}),Z.push({type:"mcp_approval_response",approval_request_id:j.approvalId,approve:j.approved});continue}const q=ae.output;if(q.type==="execution-denied"&&((X=(W=q.providerOptions)==null?void 0:W.openai)==null?void 0:X.approvalId))continue;const D=r.toProviderToolName(ae.toolName);if(x&&D==="local_shell"&&q.type==="json"){const j=await Wt({value:q.value,schema:Nu});Z.push({type:"local_shell_call_output",call_id:ae.toolCallId,output:j.output});continue}if(_&&D==="shell"&&q.type==="json"){const j=await Wt({value:q.value,schema:Po});Z.push({type:"shell_call_output",call_id:ae.toolCallId,output:j.output.map(te=>({stdout:te.stdout,stderr:te.stderr,outcome:te.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:te.outcome.exitCode}}))});continue}if(g&&ae.toolName==="apply_patch"&&q.type==="json"){const j=await Wt({value:q.value,schema:Au});Z.push({type:"apply_patch_call_output",call_id:ae.toolCallId,status:j.status,output:j.output});continue}if(C?.has(D)){let j;switch(q.type){case"text":case"error-text":j=q.value;break;case"execution-denied":j=(H=q.reason)!=null?H:"Tool execution denied.";break;case"json":case"error-json":j=JSON.stringify(q.value);break;case"content":j=q.value.map(te=>{var he;switch(te.type){case"text":return{type:"input_text",text:te.text};case"image-data":return{type:"input_image",image_url:`data:${te.mediaType};base64,${te.data}`};case"image-url":return{type:"input_image",image_url:te.url};case"file-data":return{type:"input_file",filename:(he=te.filename)!=null?he:"data",file_data:`data:${te.mediaType};base64,${te.data}`};default:M.push({type:"other",message:`unsupported custom tool content part type: ${te.type}`});return}}).filter(xa);break;default:j=""}Z.push({type:"custom_tool_call_output",call_id:ae.toolCallId,output:j});continue}let Q;switch(q.type){case"text":case"error-text":Q=q.value;break;case"execution-denied":Q=(V=q.reason)!=null?V:"Tool execution denied.";break;case"json":case"error-json":Q=JSON.stringify(q.value);break;case"content":Q=q.value.map(j=>{var te;switch(j.type){case"text":return{type:"input_text",text:j.text};case"image-data":return{type:"input_image",image_url:`data:${j.mediaType};base64,${j.data}`};case"image-url":return{type:"input_image",image_url:j.url};case"file-data":return{type:"input_file",filename:(te=j.filename)!=null?te:"data",file_data:`data:${j.mediaType};base64,${j.data}`};default:{M.push({type:"other",message:`unsupported tool content part type: ${j.type}`});return}}}).filter(xa);break}Z.push({type:"function_call_output",call_id:ae.toolCallId,output:Q})}break}default:{const ae=ce;throw new Error(`Unsupported role: ${ae}`)}}return{input:Z,warnings:M}}var q2=S({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function Za({finishReason:t,hasFunctionCall:r}){switch(t){case void 0:case null:return r?"tool-calls":"stop";case"max_output_tokens":return"length";case"content_filter":return"content-filter";default:return r?"tool-calls":"other"}}var Y2=ze(()=>Fe(Pe([S({type:G("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ye(S({token:w(),logprob:ee(),top_logprobs:ye(S({token:w(),logprob:ee()}))})).nullish()}),S({type:Le(["response.completed","response.incomplete"]),response:S({incomplete_details:S({reason:w()}).nullish(),usage:S({input_tokens:ee(),input_tokens_details:S({cached_tokens:ee().nullish()}).nullish(),output_tokens:ee(),output_tokens_details:S({reasoning_tokens:ee().nullish()}).nullish()}),service_tier:w().nullish()})}),S({type:G("response.created"),response:S({id:w(),created_at:ee(),model:w(),service_tier:w().nullish()})}),S({type:G("response.output_item.added"),output_index:ee(),item:lt("type",[S({type:G("message"),id:w(),phase:Le(["commentary","final_answer"]).nullish()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish()}),S({type:G("function_call"),id:w(),call_id:w(),name:w(),arguments:w()}),S({type:G("web_search_call"),id:w(),status:w()}),S({type:G("computer_call"),id:w(),status:w()}),S({type:G("file_search_call"),id:w()}),S({type:G("image_generation_call"),id:w()}),S({type:G("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable(),status:w()}),S({type:G("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w()}),S({type:G("mcp_approval_request"),id:w()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:ee()})])}))})])}),S({type:G("response.output_item.done"),output_index:ee(),item:lt("type",[S({type:G("message"),id:w(),phase:Le(["commentary","final_answer"]).nullish()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish()}),S({type:G("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:G("completed")}),S({type:G("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:G("completed")}),S({type:G("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable()}),S({type:G("image_generation_call"),id:w(),result:w()}),S({type:G("web_search_call"),id:w(),status:w(),action:lt("type",[S({type:G("search"),query:w().nullish(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).nullish()}),S({type:G("open_page"),url:w().nullish()}),S({type:G("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),S({type:G("file_search_call"),id:w(),queries:ye(w()),results:ye(S({attributes:gt(w(),Pe([w(),ee(),Tt()])),file_id:w(),filename:w(),score:ee(),text:w()})).nullish()}),S({type:G("local_shell_call"),id:w(),call_id:w(),action:S({type:G("exec"),command:ye(w()),timeout_ms:ee().optional(),user:w().optional(),working_directory:w().optional(),env:gt(w(),w()).optional()})}),S({type:G("computer_call"),id:w(),status:G("completed")}),S({type:G("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Pe([w(),S({type:w().optional(),code:Pe([ee(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w(),server_label:w(),tools:ye(S({name:w(),description:w().optional(),input_schema:fr(),annotations:gt(w(),Tr()).optional()})),error:Pe([w(),S({type:w().optional(),code:Pe([ee(),w()]).optional(),message:w().optional()}).loose()]).optional()}),S({type:G("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:ee()})])}))})])}),S({type:G("response.function_call_arguments.delta"),item_id:w(),output_index:ee(),delta:w()}),S({type:G("response.custom_tool_call_input.delta"),item_id:w(),output_index:ee(),delta:w()}),S({type:G("response.image_generation_call.partial_image"),item_id:w(),output_index:ee(),partial_image_b64:w()}),S({type:G("response.code_interpreter_call_code.delta"),item_id:w(),output_index:ee(),delta:w()}),S({type:G("response.code_interpreter_call_code.done"),item_id:w(),output_index:ee(),code:w()}),S({type:G("response.output_text.annotation.added"),annotation:lt("type",[S({type:G("url_citation"),start_index:ee(),end_index:ee(),url:w(),title:w()}),S({type:G("file_citation"),file_id:w(),filename:w(),index:ee()}),S({type:G("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:ee(),end_index:ee()}),S({type:G("file_path"),file_id:w(),index:ee()})])}),S({type:G("response.reasoning_summary_part.added"),item_id:w(),summary_index:ee()}),S({type:G("response.reasoning_summary_text.delta"),item_id:w(),summary_index:ee(),delta:w()}),S({type:G("response.reasoning_summary_part.done"),item_id:w(),summary_index:ee()}),S({type:G("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:ee(),delta:w(),obfuscation:w().nullish()}),S({type:G("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:ee(),diff:w()}),S({type:G("error"),sequence_number:ee(),error:S({type:w(),code:w(),message:w(),param:w().nullish()})}),S({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),J2=ze(()=>Fe(S({id:w().optional(),created_at:ee().optional(),error:S({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ye(lt("type",[S({type:G("message"),role:G("assistant"),id:w(),phase:Le(["commentary","final_answer"]).nullish(),content:ye(S({type:G("output_text"),text:w(),logprobs:ye(S({token:w(),logprob:ee(),top_logprobs:ye(S({token:w(),logprob:ee()}))})).nullish(),annotations:ye(lt("type",[S({type:G("url_citation"),start_index:ee(),end_index:ee(),url:w(),title:w()}),S({type:G("file_citation"),file_id:w(),filename:w(),index:ee()}),S({type:G("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:ee(),end_index:ee()}),S({type:G("file_path"),file_id:w(),index:ee()})]))}))}),S({type:G("web_search_call"),id:w(),status:w(),action:lt("type",[S({type:G("search"),query:w().nullish(),sources:ye(lt("type",[S({type:G("url"),url:w()}),S({type:G("api"),name:w()})])).nullish()}),S({type:G("open_page"),url:w().nullish()}),S({type:G("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),S({type:G("file_search_call"),id:w(),queries:ye(w()),results:ye(S({attributes:gt(w(),Pe([w(),ee(),Tt()])),file_id:w(),filename:w(),score:ee(),text:w()})).nullish()}),S({type:G("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ye(lt("type",[S({type:G("logs"),logs:w()}),S({type:G("image"),url:w()})])).nullable()}),S({type:G("image_generation_call"),id:w(),result:w()}),S({type:G("local_shell_call"),id:w(),call_id:w(),action:S({type:G("exec"),command:ye(w()),timeout_ms:ee().optional(),user:w().optional(),working_directory:w().optional(),env:gt(w(),w()).optional()})}),S({type:G("function_call"),call_id:w(),name:w(),arguments:w(),id:w()}),S({type:G("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),S({type:G("computer_call"),id:w(),status:w().optional()}),S({type:G("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ye(S({type:G("summary_text"),text:w()}))}),S({type:G("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Pe([w(),S({type:w().optional(),code:Pe([ee(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),S({type:G("mcp_list_tools"),id:w(),server_label:w(),tools:ye(S({name:w(),description:w().optional(),input_schema:fr(),annotations:gt(w(),Tr()).optional()})),error:Pe([w(),S({type:w().optional(),code:Pe([ee(),w()]).optional(),message:w().optional()}).loose()]).optional()}),S({type:G("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),S({type:G("apply_patch_call"),id:w(),call_id:w(),status:Le(["in_progress","completed"]),operation:lt("type",[S({type:G("create_file"),path:w(),diff:w()}),S({type:G("delete_file"),path:w()}),S({type:G("update_file"),path:w(),diff:w()})])}),S({type:G("shell_call"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),action:S({commands:ye(w())})}),S({type:G("shell_call_output"),id:w(),call_id:w(),status:Le(["in_progress","completed","incomplete"]),output:ye(S({stdout:w(),stderr:w(),outcome:lt("type",[S({type:G("timeout")}),S({type:G("exit"),exit_code:ee()})])}))})])).optional(),service_tier:w().nullish(),incomplete_details:S({reason:w()}).nullish(),usage:S({input_tokens:ee(),input_tokens_details:S({cached_tokens:ee().nullish()}).nullish(),output_tokens:ee(),output_tokens_details:S({reasoning_tokens:ee().nullish()}).nullish()}).optional()}))),Ru=20,ja=ze(()=>Fe(S({conversation:w().nullish(),include:ye(Le(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:Pe([Tt(),ee().min(1).max(Ru)]).optional(),maxToolCalls:ee().nullish(),metadata:fr().nullish(),parallelToolCalls:Tt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheRetention:Le(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Le(["auto","flex","priority","default"]).nullish(),store:Tt().nullish(),strictJsonSchema:Tt().nullish(),textVerbosity:Le(["low","medium","high"]).nullish(),truncation:Le(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Le(["system","developer","remove"]).optional(),forceReasoning:Tt().optional()})));async function K2({tools:t,toolChoice:r,toolNameMapping:o,customProviderToolNames:c}){var u;t=t?.length?t:void 0;const f=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:f};const m=[],x=c??new Set;for(const g of t)switch(g.type){case"function":m.push({type:"function",name:g.name,description:g.description,parameters:g.inputSchema,...g.strict!=null?{strict:g.strict}:{}});break;case"provider":{switch(g.id){case"openai.file_search":{const C=await Wt({value:g.args,schema:v2});m.push({type:"file_search",vector_store_ids:C.vectorStoreIds,max_num_results:C.maxNumResults,ranking_options:C.ranking?{ranker:C.ranking.ranker,score_threshold:C.ranking.scoreThreshold}:void 0,filters:C.filters});break}case"openai.local_shell":{m.push({type:"local_shell"});break}case"openai.shell":{const C=await Wt({value:g.args,schema:R2});m.push({type:"shell",...C.environment&&{environment:Q2(C.environment)}});break}case"openai.apply_patch":{m.push({type:"apply_patch"});break}case"openai.web_search_preview":{const C=await Wt({value:g.args,schema:F2});m.push({type:"web_search_preview",search_context_size:C.searchContextSize,user_location:C.userLocation});break}case"openai.web_search":{const C=await Wt({value:g.args,schema:M2});m.push({type:"web_search",filters:C.filters!=null?{allowed_domains:C.filters.allowedDomains}:void 0,external_web_access:C.externalWebAccess,search_context_size:C.searchContextSize,user_location:C.userLocation});break}case"openai.code_interpreter":{const C=await Wt({value:g.args,schema:p2});m.push({type:"code_interpreter",container:C.container==null?{type:"auto",file_ids:void 0}:typeof C.container=="string"?C.container:{type:"auto",file_ids:C.container.fileIds}});break}case"openai.image_generation":{const C=await Wt({value:g.args,schema:E2});m.push({type:"image_generation",background:C.background,input_fidelity:C.inputFidelity,input_image_mask:C.inputImageMask?{file_id:C.inputImageMask.fileId,image_url:C.inputImageMask.imageUrl}:void 0,model:C.model,moderation:C.moderation,partial_images:C.partialImages,quality:C.quality,output_compression:C.outputCompression,output_format:C.outputFormat,size:C.size});break}case"openai.mcp":{const C=await Wt({value:g.args,schema:V2}),A=k=>({tool_names:k.toolNames}),P=C.requireApproval,O=P==null?void 0:typeof P=="string"?P:P.never!=null?{never:A(P.never)}:void 0;m.push({type:"mcp",server_label:C.serverLabel,allowed_tools:Array.isArray(C.allowedTools)?C.allowedTools:C.allowedTools?{read_only:C.allowedTools.readOnly,tool_names:C.allowedTools.toolNames}:void 0,authorization:C.authorization,connector_id:C.connectorId,headers:C.headers,require_approval:O??"never",server_description:C.serverDescription,server_url:C.serverUrl});break}case"openai.custom":{const C=await Wt({value:g.args,schema:x2});m.push({type:"custom",name:C.name,description:C.description,format:C.format}),x.add(C.name);break}}break}default:f.push({type:"unsupported",feature:`function tool ${g}`});break}if(r==null)return{tools:m,toolChoice:void 0,toolWarnings:f};const _=r.type;switch(_){case"auto":case"none":case"required":return{tools:m,toolChoice:_,toolWarnings:f};case"tool":{const g=(u=o?.toProviderToolName(r.toolName))!=null?u:r.toolName;return{tools:m,toolChoice:g==="code_interpreter"||g==="file_search"||g==="image_generation"||g==="web_search_preview"||g==="web_search"||g==="mcp"||g==="apply_patch"?{type:g}:x.has(g)?{type:"custom",name:g}:{type:"function",name:g},toolWarnings:f}}default:{const g=_;throw new Dn({functionality:`tool choice type: ${g}`})}}}function Q2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const o=t;return{type:"container_auto",file_ids:o.fileIds,memory_limit:o.memoryLimit,network_policy:o.networkPolicy==null?void 0:o.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:o.networkPolicy.allowedDomains,domain_secrets:o.networkPolicy.domainSecrets},skills:ex(o.skills)}}return{type:"local",skills:t.skills}}function ex(t){return t?.map(r=>r.type==="skillReference"?{type:"skill_reference",skill_id:r.skillId,version:r.version}:{type:"inline",name:r.name,description:r.description,source:{type:"base64",media_type:r.source.mediaType,data:r.source.data}})}function Wa(t){var r,o;const c={};for(const u of t)if(u.role==="assistant")for(const f of u.content){if(f.type!=="tool-call")continue;const m=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var tx=class{constructor(t,r){this.specificationVersion="v3",this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=t,this.config=r}get provider(){return this.config.provider}async getArgs({maxOutputTokens:t,temperature:r,stopSequences:o,topP:c,topK:u,presencePenalty:f,frequencyPenalty:m,seed:x,prompt:_,providerOptions:g,tools:C,toolChoice:A,responseFormat:P}){var O,k,B,L,K,z,$,W,X;const H=[],V=bu(this.modelId);u!=null&&H.push({type:"unsupported",feature:"topK"}),x!=null&&H.push({type:"unsupported",feature:"seed"}),f!=null&&H.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&H.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&H.push({type:"unsupported",feature:"stopSequences"});const Z=this.config.provider.includes("azure")?"azure":"openai";let M=await Bn({provider:Z,providerOptions:g,schema:ja});M==null&&Z!=="openai"&&(M=await Bn({provider:"openai",providerOptions:g,schema:ja}));const we=(O=M?.forceReasoning)!=null?O:V.isReasoningModel;M?.conversation&&M?.previousResponseId&&H.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const ce=Qh({tools:C,providerToolNames:{"openai.code_interpreter":"code_interpreter","openai.file_search":"file_search","openai.image_generation":"image_generation","openai.local_shell":"local_shell","openai.shell":"shell","openai.web_search":"web_search","openai.web_search_preview":"web_search_preview","openai.mcp":"mcp","openai.apply_patch":"apply_patch"},resolveProviderToolName:Ae=>Ae.id==="openai.custom"?Ae.args.name:void 0}),fe=new Set,{tools:ae,toolChoice:q,toolWarnings:D}=await K2({tools:C,toolChoice:A,toolNameMapping:ce,customProviderToolNames:fe}),{input:Q,warnings:j}=await X2({prompt:_,toolNameMapping:ce,systemMessageMode:(k=M?.systemMessageMode)!=null?k:we?"developer":V.systemMessageMode,providerOptionsName:Z,fileIdPrefixes:this.config.fileIdPrefixes,store:(B=M?.store)!=null?B:!0,hasConversation:M?.conversation!=null,hasLocalShellTool:de("openai.local_shell"),hasShellTool:de("openai.shell"),hasApplyPatchTool:de("openai.apply_patch"),customProviderToolNames:fe.size>0?fe:void 0});H.push(...j);const te=(L=M?.strictJsonSchema)!=null?L:!0;let he=M?.include;function ge(Ae){he==null?he=[Ae]:he.includes(Ae)||(he=[...he,Ae])}function de(Ae){return C?.find(Ne=>Ne.type==="provider"&&Ne.id===Ae)!=null}const Ce=typeof M?.logprobs=="number"?M?.logprobs:M?.logprobs===!0?Ru:void 0;Ce&&ge("message.output_text.logprobs");const Ve=(K=C?.find(Ae=>Ae.type==="provider"&&(Ae.id==="openai.web_search"||Ae.id==="openai.web_search_preview")))==null?void 0:K.name;Ve&&ge("web_search_call.action.sources"),de("openai.code_interpreter")&&ge("code_interpreter_call.outputs");const Me=M?.store;Me===!1&&we&&ge("reasoning.encrypted_content");const Ye={model:this.modelId,input:Q,temperature:r,top_p:c,max_output_tokens:t,...(P?.type==="json"||M?.textVerbosity)&&{text:{...P?.type==="json"&&{format:P.schema!=null?{type:"json_schema",strict:te,name:(z=P.name)!=null?z:"response",description:P.description,schema:P.schema}:{type:"json_object"}},...M?.textVerbosity&&{verbosity:M.textVerbosity}}},conversation:M?.conversation,max_tool_calls:M?.maxToolCalls,metadata:M?.metadata,parallel_tool_calls:M?.parallelToolCalls,previous_response_id:M?.previousResponseId,store:Me,user:M?.user,instructions:M?.instructions,service_tier:M?.serviceTier,include:he,prompt_cache_key:M?.promptCacheKey,prompt_cache_retention:M?.promptCacheRetention,safety_identifier:M?.safetyIdentifier,top_logprobs:Ce,truncation:M?.truncation,...we&&(M?.reasoningEffort!=null||M?.reasoningSummary!=null)&&{reasoning:{...M?.reasoningEffort!=null&&{effort:M.reasoningEffort},...M?.reasoningSummary!=null&&{summary:M.reasoningSummary}}}};we?M?.reasoningEffort==="none"&&V.supportsNonReasoningParameters||(Ye.temperature!=null&&(Ye.temperature=void 0,H.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Ye.top_p!=null&&(Ye.top_p=void 0,H.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(M?.reasoningEffort!=null&&H.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),M?.reasoningSummary!=null&&H.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),M?.serviceTier==="flex"&&!V.supportsFlexProcessing&&(H.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Ye.service_tier),M?.serviceTier==="priority"&&!V.supportsPriorityProcessing&&(H.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete Ye.service_tier);const ie=(X=(W=($=C?.find(Ae=>Ae.type==="provider"&&Ae.id==="openai.shell"))==null?void 0:$.args)==null?void 0:W.environment)==null?void 0:X.type,ke=ie==="containerAuto"||ie==="containerReference";return{webSearchToolName:Ve,args:{...Ye,tools:ae,tool_choice:q},warnings:[...H,...D],store:Me,toolNameMapping:ce,providerOptionsName:Z,isShellProviderExecuted:ke}}async doGenerate(t){var r,o,c,u,f,m,x,_,g,C,A,P,O,k,B,L,K,z,$,W,X,H,V,Z,M;const{args:we,warnings:ce,webSearchToolName:fe,toolNameMapping:ae,providerOptionsName:q,isShellProviderExecuted:D}=await this.getArgs(t),Q=this.config.url({path:"/responses",modelId:this.modelId}),j=Wa(t.prompt),{responseHeaders:te,value:he,rawValue:ge}=await Ln({url:Q,headers:vn(this.config.headers(),t.headers),body:we,failedResponseHandler:Cn,successfulResponseHandler:ur(J2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(he.error)throw new sn({message:he.error.message,url:Q,requestBodyValues:we,statusCode:400,responseHeaders:te,responseBody:ge,isRetryable:!1});const de=[],Ce=[];let Ve=!1;for(const ie of he.output)switch(ie.type){case"reasoning":{ie.summary.length===0&&ie.summary.push({type:"summary_text",text:""});for(const ke of ie.summary)de.push({type:"reasoning",text:ke.text,providerMetadata:{[q]:{itemId:ie.id,reasoningEncryptedContent:(r=ie.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("image_generation"),result:{result:ie.result}});break}case"local_shell_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("local_shell"),input:JSON.stringify({action:ie.action}),providerMetadata:{[q]:{itemId:ie.id}}});break}case"shell_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("shell"),input:JSON.stringify({action:{commands:ie.action.commands}}),...D&&{providerExecuted:!0},providerMetadata:{[q]:{itemId:ie.id}}});break}case"shell_call_output":{de.push({type:"tool-result",toolCallId:ie.call_id,toolName:ae.toCustomToolName("shell"),result:{output:ie.output.map(ke=>({stdout:ke.stdout,stderr:ke.stderr,outcome:ke.outcome.type==="exit"?{type:"exit",exitCode:ke.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ke of ie.content){(c=(o=t.providerOptions)==null?void 0:o[q])!=null&&c.logprobs&&ke.logprobs&&Ce.push(ke.logprobs);const Ae={itemId:ie.id,...ie.phase!=null&&{phase:ie.phase},...ke.annotations.length>0&&{annotations:ke.annotations}};de.push({type:"text",text:ke.text,providerMetadata:{[q]:Ae}});for(const Ne of ke.annotations)Ne.type==="url_citation"?de.push({type:"source",sourceType:"url",id:(m=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?m:qt(),url:Ne.url,title:Ne.title}):Ne.type==="file_citation"?de.push({type:"source",sourceType:"document",id:(g=(_=(x=this.config).generateId)==null?void 0:_.call(x))!=null?g:qt(),mediaType:"text/plain",title:Ne.filename,filename:Ne.filename,providerMetadata:{[q]:{type:Ne.type,fileId:Ne.file_id,index:Ne.index}}}):Ne.type==="container_file_citation"?de.push({type:"source",sourceType:"document",id:(P=(A=(C=this.config).generateId)==null?void 0:A.call(C))!=null?P:qt(),mediaType:"text/plain",title:Ne.filename,filename:Ne.filename,providerMetadata:{[q]:{type:Ne.type,fileId:Ne.file_id,containerId:Ne.container_id}}}):Ne.type==="file_path"&&de.push({type:"source",sourceType:"document",id:(B=(k=(O=this.config).generateId)==null?void 0:k.call(O))!=null?B:qt(),mediaType:"application/octet-stream",title:Ne.file_id,filename:Ne.file_id,providerMetadata:{[q]:{type:Ne.type,fileId:Ne.file_id,index:Ne.index}}})}break}case"function_call":{Ve=!0,de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ie.name,input:ie.arguments,providerMetadata:{[q]:{itemId:ie.id}}});break}case"custom_tool_call":{Ve=!0;const ke=ae.toCustomToolName(ie.name);de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ke,input:JSON.stringify(ie.input),providerMetadata:{[q]:{itemId:ie.id}}});break}case"web_search_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName(fe??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName(fe??"web_search"),result:Ga(ie.action)});break}case"mcp_call":{const ke=ie.approval_request_id!=null&&(L=j[ie.approval_request_id])!=null?L:ie.id,Ae=`mcp.${ie.name}`;de.push({type:"tool-call",toolCallId:ke,toolName:Ae,input:ie.arguments,providerExecuted:!0,dynamic:!0}),de.push({type:"tool-result",toolCallId:ke,toolName:Ae,result:{type:"call",serverLabel:ie.server_label,name:ie.name,arguments:ie.arguments,...ie.output!=null?{output:ie.output}:{},...ie.error!=null?{error:ie.error}:{}},providerMetadata:{[q]:{itemId:ie.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ke=(K=ie.approval_request_id)!=null?K:ie.id,Ae=(W=($=(z=this.config).generateId)==null?void 0:$.call(z))!=null?W:qt(),Ne=`mcp.${ie.name}`;de.push({type:"tool-call",toolCallId:Ae,toolName:Ne,input:ie.arguments,providerExecuted:!0,dynamic:!0}),de.push({type:"tool-approval-request",approvalId:ke,toolCallId:Ae});break}case"computer_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:ie.status||"completed"}});break}case"file_search_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("file_search"),result:{queries:ie.queries,results:(H=(X=ie.results)==null?void 0:X.map(ke=>({attributes:ke.attributes,fileId:ke.file_id,filename:ke.filename,score:ke.score,text:ke.text})))!=null?H:null}});break}case"code_interpreter_call":{de.push({type:"tool-call",toolCallId:ie.id,toolName:ae.toCustomToolName("code_interpreter"),input:JSON.stringify({code:ie.code,containerId:ie.container_id}),providerExecuted:!0}),de.push({type:"tool-result",toolCallId:ie.id,toolName:ae.toCustomToolName("code_interpreter"),result:{outputs:ie.outputs}});break}case"apply_patch_call":{de.push({type:"tool-call",toolCallId:ie.call_id,toolName:ae.toCustomToolName("apply_patch"),input:JSON.stringify({callId:ie.call_id,operation:ie.operation}),providerMetadata:{[q]:{itemId:ie.id}}});break}}const Me={[q]:{responseId:he.id,...Ce.length>0?{logprobs:Ce}:{},...typeof he.service_tier=="string"?{serviceTier:he.service_tier}:{}}},Ye=he.usage;return{content:de,finishReason:{unified:Za({finishReason:(V=he.incomplete_details)==null?void 0:V.reason,hasFunctionCall:Ve}),raw:(M=(Z=he.incomplete_details)==null?void 0:Z.reason)!=null?M:void 0},usage:$a(Ye),request:{body:we},response:{id:he.id,timestamp:new Date(he.created_at*1e3),modelId:he.model,headers:te,body:ge},providerMetadata:Me,warnings:ce}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:m,isShellProviderExecuted:x}=await this.getArgs(t),{responseHeaders:_,value:g}=await Ln({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:Cn,successfulResponseHandler:es(Y2),abortSignal:t.abortSignal,fetch:this.config.fetch}),C=this,A=Wa(t.prompt),P=new Map;let O={unified:"other",raw:void 0},k;const B=[];let L=null;const K={},z=[];let $,W=!1;const X={};let H;return{stream:g.pipeThrough(new TransformStream({start(V){V.enqueue({type:"stream-start",warnings:o})},transform(V,Z){var M,we,ce,fe,ae,q,D,Q,j,te,he,ge,de,Ce,Ve,Me,Ye,ie,ke,Ae,Ne,ot,Xe,$t,Ue,pn,Vt,bn,wt,Je,je,En;if(t.includeRawChunks&&Z.enqueue({type:"raw",rawValue:V.rawValue}),!V.success){O={unified:"error",raw:void 0},Z.enqueue({type:"error",error:V.error});return}const T=V.value;if(Ha(T)){if(T.item.type==="function_call")K[T.output_index]={toolName:T.item.name,toolCallId:T.item.call_id},Z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:T.item.name});else if(T.item.type==="custom_tool_call"){const pe=u.toCustomToolName(T.item.name);K[T.output_index]={toolName:pe,toolCallId:T.item.call_id},Z.enqueue({type:"tool-input-start",id:T.item.call_id,toolName:pe})}else if(T.item.type==="web_search_call")K[T.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:T.item.id},Z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),Z.enqueue({type:"tool-input-end",id:T.item.id}),Z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(T.item.type==="computer_call")K[T.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:T.item.id},Z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(T.item.type==="code_interpreter_call")K[T.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:T.item.id,codeInterpreter:{containerId:T.item.container_id}},Z.enqueue({type:"tool-input-start",id:T.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),Z.enqueue({type:"tool-input-delta",id:T.item.id,delta:`{"containerId":"${T.item.container_id}","code":"`});else if(T.item.type==="file_search_call")Z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(T.item.type==="image_generation_call")Z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(T.item.type==="mcp_call"||T.item.type==="mcp_list_tools"||T.item.type==="mcp_approval_request"))if(T.item.type==="apply_patch_call"){const{call_id:pe,operation:_t}=T.item;if(K[T.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:pe,applyPatch:{hasDiff:_t.type==="delete_file",endEmitted:_t.type==="delete_file"}},Z.enqueue({type:"tool-input-start",id:pe,toolName:u.toCustomToolName("apply_patch")}),_t.type==="delete_file"){const vt=JSON.stringify({callId:pe,operation:_t});Z.enqueue({type:"tool-input-delta",id:pe,delta:vt}),Z.enqueue({type:"tool-input-end",id:pe})}else Z.enqueue({type:"tool-input-delta",id:pe,delta:`{"callId":"${sr(pe)}","operation":{"type":"${sr(_t.type)}","path":"${sr(_t.path)}","diff":"`})}else T.item.type==="shell_call"?K[T.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:T.item.call_id}:T.item.type==="shell_call_output"||(T.item.type==="message"?(z.splice(0,z.length),$=(M=T.item.phase)!=null?M:void 0,Z.enqueue({type:"text-start",id:T.item.id,providerMetadata:{[m]:{itemId:T.item.id,...T.item.phase!=null&&{phase:T.item.phase}}}})):Ha(T)&&T.item.type==="reasoning"&&(X[T.item.id]={encryptedContent:T.item.encrypted_content,summaryParts:{0:"active"}},Z.enqueue({type:"reasoning-start",id:`${T.item.id}:0`,providerMetadata:{[m]:{itemId:T.item.id,reasoningEncryptedContent:(we=T.item.encrypted_content)!=null?we:null}}})))}else if(rx(T)){if(T.item.type==="message"){const pe=(ce=T.item.phase)!=null?ce:$;$=void 0,Z.enqueue({type:"text-end",id:T.item.id,providerMetadata:{[m]:{itemId:T.item.id,...pe!=null&&{phase:pe},...z.length>0&&{annotations:z}}}})}else if(T.item.type==="function_call")K[T.output_index]=void 0,W=!0,Z.enqueue({type:"tool-input-end",id:T.item.call_id}),Z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:T.item.name,input:T.item.arguments,providerMetadata:{[m]:{itemId:T.item.id}}});else if(T.item.type==="custom_tool_call"){K[T.output_index]=void 0,W=!0;const pe=u.toCustomToolName(T.item.name);Z.enqueue({type:"tool-input-end",id:T.item.call_id}),Z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:pe,input:JSON.stringify(T.item.input),providerMetadata:{[m]:{itemId:T.item.id}}})}else if(T.item.type==="web_search_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Ga(T.item.action)});else if(T.item.type==="computer_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-input-end",id:T.item.id}),Z.enqueue({type:"tool-call",toolCallId:T.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:T.item.status||"completed"}});else if(T.item.type==="file_search_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:T.item.queries,results:(ae=(fe=T.item.results)==null?void 0:fe.map(pe=>({attributes:pe.attributes,fileId:pe.file_id,filename:pe.filename,score:pe.score,text:pe.text})))!=null?ae:null}});else if(T.item.type==="code_interpreter_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:T.item.outputs}});else if(T.item.type==="image_generation_call")Z.enqueue({type:"tool-result",toolCallId:T.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:T.item.result}});else if(T.item.type==="mcp_call"){K[T.output_index]=void 0;const pe=(q=T.item.approval_request_id)!=null?q:void 0,_t=pe!=null&&(Q=(D=P.get(pe))!=null?D:A[pe])!=null?Q:T.item.id,vt=`mcp.${T.item.name}`;Z.enqueue({type:"tool-call",toolCallId:_t,toolName:vt,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),Z.enqueue({type:"tool-result",toolCallId:_t,toolName:vt,result:{type:"call",serverLabel:T.item.server_label,name:T.item.name,arguments:T.item.arguments,...T.item.output!=null?{output:T.item.output}:{},...T.item.error!=null?{error:T.item.error}:{}},providerMetadata:{[m]:{itemId:T.item.id}}})}else if(T.item.type==="mcp_list_tools")K[T.output_index]=void 0;else if(T.item.type==="apply_patch_call"){const pe=K[T.output_index];pe?.applyPatch&&!pe.applyPatch.endEmitted&&T.item.operation.type!=="delete_file"&&(pe.applyPatch.hasDiff||Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.item.operation.diff)}),Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}}'}),Z.enqueue({type:"tool-input-end",id:pe.toolCallId}),pe.applyPatch.endEmitted=!0),pe&&T.item.status==="completed"&&Z.enqueue({type:"tool-call",toolCallId:pe.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:T.item.call_id,operation:T.item.operation}),providerMetadata:{[m]:{itemId:T.item.id}}}),K[T.output_index]=void 0}else if(T.item.type==="mcp_approval_request"){K[T.output_index]=void 0;const pe=(he=(te=(j=C.config).generateId)==null?void 0:te.call(j))!=null?he:qt(),_t=(ge=T.item.approval_request_id)!=null?ge:T.item.id;P.set(_t,pe);const vt=`mcp.${T.item.name}`;Z.enqueue({type:"tool-call",toolCallId:pe,toolName:vt,input:T.item.arguments,providerExecuted:!0,dynamic:!0}),Z.enqueue({type:"tool-approval-request",approvalId:_t,toolCallId:pe})}else if(T.item.type==="local_shell_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:T.item.action.command,timeoutMs:T.item.action.timeout_ms,user:T.item.action.user,workingDirectory:T.item.action.working_directory,env:T.item.action.env}}),providerMetadata:{[m]:{itemId:T.item.id}}});else if(T.item.type==="shell_call")K[T.output_index]=void 0,Z.enqueue({type:"tool-call",toolCallId:T.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:T.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:T.item.id}}});else if(T.item.type==="shell_call_output")Z.enqueue({type:"tool-result",toolCallId:T.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:T.item.output.map(pe=>({stdout:pe.stdout,stderr:pe.stderr,outcome:pe.outcome.type==="exit"?{type:"exit",exitCode:pe.outcome.exit_code}:{type:"timeout"}}))}});else if(T.item.type==="reasoning"){const pe=X[T.item.id],_t=Object.entries(pe.summaryParts).filter(([vt,Un])=>Un==="active"||Un==="can-conclude").map(([vt])=>vt);for(const vt of _t)Z.enqueue({type:"reasoning-end",id:`${T.item.id}:${vt}`,providerMetadata:{[m]:{itemId:T.item.id,reasoningEncryptedContent:(de=T.item.encrypted_content)!=null?de:null}}});delete X[T.item.id]}}else if(sx(T)){const pe=K[T.output_index];pe!=null&&Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:T.delta})}else if(ax(T)){const pe=K[T.output_index];pe!=null&&Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:T.delta})}else if(dx(T)){const pe=K[T.output_index];pe?.applyPatch&&(Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.delta)}),pe.applyPatch.hasDiff=!0)}else if(fx(T)){const pe=K[T.output_index];pe?.applyPatch&&!pe.applyPatch.endEmitted&&(pe.applyPatch.hasDiff||(Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.diff)}),pe.applyPatch.hasDiff=!0),Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}}'}),Z.enqueue({type:"tool-input-end",id:pe.toolCallId}),pe.applyPatch.endEmitted=!0)}else if(lx(T))Z.enqueue({type:"tool-result",toolCallId:T.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:T.partial_image_b64},preliminary:!0});else if(cx(T)){const pe=K[T.output_index];pe!=null&&Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:sr(T.delta)})}else if(ux(T)){const pe=K[T.output_index];pe!=null&&(Z.enqueue({type:"tool-input-delta",id:pe.toolCallId,delta:'"}'}),Z.enqueue({type:"tool-input-end",id:pe.toolCallId}),Z.enqueue({type:"tool-call",toolCallId:pe.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:T.code,containerId:pe.codeInterpreter.containerId}),providerExecuted:!0}))}else if(ox(T))L=T.response.id,Z.enqueue({type:"response-metadata",id:T.response.id,timestamp:new Date(T.response.created_at*1e3),modelId:T.response.model});else if(nx(T))Z.enqueue({type:"text-delta",id:T.item_id,delta:T.delta}),(Ve=(Ce=t.providerOptions)==null?void 0:Ce[m])!=null&&Ve.logprobs&&T.logprobs&&B.push(T.logprobs);else if(T.type==="response.reasoning_summary_part.added"){if(T.summary_index>0){const pe=X[T.item_id];pe.summaryParts[T.summary_index]="active";for(const _t of Object.keys(pe.summaryParts))pe.summaryParts[_t]==="can-conclude"&&(Z.enqueue({type:"reasoning-end",id:`${T.item_id}:${_t}`,providerMetadata:{[m]:{itemId:T.item_id}}}),pe.summaryParts[_t]="concluded");Z.enqueue({type:"reasoning-start",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[m]:{itemId:T.item_id,reasoningEncryptedContent:(Ye=(Me=X[T.item_id])==null?void 0:Me.encryptedContent)!=null?Ye:null}}})}}else T.type==="response.reasoning_summary_text.delta"?Z.enqueue({type:"reasoning-delta",id:`${T.item_id}:${T.summary_index}`,delta:T.delta,providerMetadata:{[m]:{itemId:T.item_id}}}):T.type==="response.reasoning_summary_part.done"?f?(Z.enqueue({type:"reasoning-end",id:`${T.item_id}:${T.summary_index}`,providerMetadata:{[m]:{itemId:T.item_id}}}),X[T.item_id].summaryParts[T.summary_index]="concluded"):X[T.item_id].summaryParts[T.summary_index]="can-conclude":ix(T)?(O={unified:Za({finishReason:(ie=T.response.incomplete_details)==null?void 0:ie.reason,hasFunctionCall:W}),raw:(Ae=(ke=T.response.incomplete_details)==null?void 0:ke.reason)!=null?Ae:void 0},k=T.response.usage,typeof T.response.service_tier=="string"&&(H=T.response.service_tier)):hx(T)?(z.push(T.annotation),T.annotation.type==="url_citation"?Z.enqueue({type:"source",sourceType:"url",id:(Xe=(ot=(Ne=C.config).generateId)==null?void 0:ot.call(Ne))!=null?Xe:qt(),url:T.annotation.url,title:T.annotation.title}):T.annotation.type==="file_citation"?Z.enqueue({type:"source",sourceType:"document",id:(pn=(Ue=($t=C.config).generateId)==null?void 0:Ue.call($t))!=null?pn:qt(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[m]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}}):T.annotation.type==="container_file_citation"?Z.enqueue({type:"source",sourceType:"document",id:(wt=(bn=(Vt=C.config).generateId)==null?void 0:bn.call(Vt))!=null?wt:qt(),mediaType:"text/plain",title:T.annotation.filename,filename:T.annotation.filename,providerMetadata:{[m]:{type:T.annotation.type,fileId:T.annotation.file_id,containerId:T.annotation.container_id}}}):T.annotation.type==="file_path"&&Z.enqueue({type:"source",sourceType:"document",id:(En=(je=(Je=C.config).generateId)==null?void 0:je.call(Je))!=null?En:qt(),mediaType:"application/octet-stream",title:T.annotation.file_id,filename:T.annotation.file_id,providerMetadata:{[m]:{type:T.annotation.type,fileId:T.annotation.file_id,index:T.annotation.index}}})):px(T)&&Z.enqueue({type:"error",error:T})},flush(V){const Z={[m]:{responseId:L,...B.length>0?{logprobs:B}:{},...H!==void 0?{serviceTier:H}:{}}};V.enqueue({type:"finish",finishReason:O,usage:$a(k),providerMetadata:Z})}})),request:{body:r},response:{headers:_}}}};function nx(t){return t.type==="response.output_text.delta"}function rx(t){return t.type==="response.output_item.done"}function ix(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ox(t){return t.type==="response.created"}function sx(t){return t.type==="response.function_call_arguments.delta"}function ax(t){return t.type==="response.custom_tool_call_input.delta"}function lx(t){return t.type==="response.image_generation_call.partial_image"}function cx(t){return t.type==="response.code_interpreter_call_code.delta"}function ux(t){return t.type==="response.code_interpreter_call_code.done"}function dx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function fx(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function hx(t){return t.type==="response.output_text.annotation.added"}function px(t){return t.type==="error"}function Ga(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function sr(t){return JSON.stringify(t).slice(1,-1)}var mx=ze(()=>Fe(S({instructions:w().nullish(),speed:ee().min(.25).max(4).default(1).nullish()}))),gx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({text:t,voice:r="alloy",outputFormat:o="mp3",speed:c,instructions:u,language:f,providerOptions:m}){const x=[],_=await Bn({provider:"openai",providerOptions:m,schema:mx}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:u};if(o&&(["mp3","opus","aac","flac","wav","pcm"].includes(o)?g.response_format=o:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),_){const C={};for(const A in C){const P=C[A];P!==void 0&&(g[A]=P)}}return f&&x.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:g,warnings:x}}async doGenerate(t){var r,o,c;const u=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:x,responseHeaders:_,rawValue:g}=await Ln({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),body:f,failedResponseHandler:Cn,successfulResponseHandler:ym(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:_,body:g}}}},xx=ze(()=>Fe(S({text:w(),language:w().nullish(),duration:ee().nullish(),words:ye(S({word:w(),start:ee(),end:ee()})).nullish(),segments:ye(S({id:ee(),seek:ee(),start:ee(),end:ee(),text:w(),tokens:ye(ee()),temperature:ee(),avg_logprob:ee(),compression_ratio:ee(),no_speech_prob:ee()})).nullish()}))),yx=ze(()=>Fe(S({include:ye(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:ee().min(0).max(1).default(0).optional(),timestampGranularities:ye(Le(["word","segment"])).default(["segment"]).optional()}))),Xa={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},wx=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get provider(){return this.config.provider}async getArgs({audio:t,mediaType:r,providerOptions:o}){const c=[],u=await Bn({provider:"openai",providerOptions:o,schema:yx}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([Yo(t)]);f.append("model",this.modelId);const x=yp(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${x}`),u){const _={include:u.include,language:u.language,prompt:u.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:u.temperature,timestamp_granularities:u.timestampGranularities};for(const[g,C]of Object.entries(_))if(C!=null)if(Array.isArray(C))for(const A of C)f.append(`${g}[]`,String(A));else f.append(g,String(C))}return{formData:f,warnings:c}}async doGenerate(t){var r,o,c,u,f,m,x,_;const g=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{formData:C,warnings:A}=await this.getArgs(t),{value:P,responseHeaders:O,rawValue:k}=await Tc({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:vn(this.config.headers(),t.headers),formData:C,failedResponseHandler:Cn,successfulResponseHandler:ur(xx),abortSignal:t.abortSignal,fetch:this.config.fetch}),B=P.language!=null&&P.language in Xa?Xa[P.language]:void 0;return{text:P.text,segments:(x=(m=(u=P.segments)==null?void 0:u.map(L=>({text:L.text,startSecond:L.start,endSecond:L.end})))!=null?m:(f=P.words)==null?void 0:f.map(L=>({text:L.word,startSecond:L.start,endSecond:L.end})))!=null?x:[],language:B,durationInSeconds:(_=P.duration)!=null?_:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:O,body:k}}}},_x="3.0.41";function ku(t={}){var r,o;const c=(r=wm(xp({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>bc({Authorization:`Bearer ${gp({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${_x}`),m=B=>new Jg(B,{provider:`${u}.chat`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),x=B=>new t2(B,{provider:`${u}.completion`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),_=B=>new i2(B,{provider:`${u}.embedding`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),g=B=>new l2(B,{provider:`${u}.image`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),C=B=>new wx(B,{provider:`${u}.transcription`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),A=B=>new gx(B,{provider:`${u}.speech`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch}),P=B=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return O(B)},O=B=>new tx(B,{provider:`${u}.responses`,url:({path:L})=>`${c}${L}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),k=function(B){return P(B)};return k.specificationVersion="v3",k.languageModel=P,k.chat=m,k.completion=x,k.responses=O,k.embedding=_,k.embeddingModel=_,k.textEmbedding=_,k.textEmbeddingModel=_,k.image=g,k.imageModel=g,k.transcription=C,k.transcriptionModel=C,k.speech=A,k.speechModel=A,k.tools=G2,k}ku();const vx={deepseek:{prompt:{strategy:"append",id:"5ed1b9071c15d1ed59b5827ea5dcabd4",params:{customComponents:[{name:"选择用户组件",description:"选择用户组件,用于选择用户,支持模糊搜索",component:"TinyUser",schema:{properties:[{property:"modelValue",label:"用户绑定工号",required:!0,description:"用户的工号,双向绑定值",type:"string"},{property:"valueField",label:"值字段",required:!0,description:"用户工号值的绑定字段",type:"string"}]}}],customExamples:[{name:"选择用户示例",schema:{componentName:"Page",state:{reviewer:""},children:[{componentName:"h3",props:{},children:"输入用户名搜索工号并选择用户"},{componentName:"TinyUser",props:{modelValue:{type:"JSExpression",model:!0,value:"this.state.reviewer"},valueField:"uid"}},{componentName:"TinyButton",props:{text:"提交"}}]}}],customActions:[{name:"continueChat",description:"继续对话, 用于表单的提交按钮等",parameters:{type:"object",properties:{message:{type:"string",description:"对话消息,可以是按钮文本等,也可以是其他内容"}}}}]}}}};class Cx{constructor(r={}){this.option=r}async traverse(r){const o=v.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",o),(async()=>{let u,f,m,x,_;for await(const g of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+g.type,g),g.type){case"start":u=v.reactive({running:!0,steps:[]}),o.value=u,this.option.onStart?.(u);break;case"start-step":f=v.reactive({running:!0,contents:[],request:g.request}),u.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=v.reactive({type:"reasoning",id:g.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=g.text;break;case"reasoning-end":m.running=!1;break;case"text-start":x=v.reactive({type:"text",id:g.id,running:!0,text:""}),f.contents.push(x),this.option.onText?.(x);break;case"text-delta":x.text+=g.text;break;case"text-end":x.running=!1;break;case"tool-input-start":_=v.reactive({type:"tool",running:!0,id:g.id,toolCallId:g.id,title:"",toolName:g.toolName,dynamic:g.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(_),this.option.onTool?.(_);break;case"tool-input-delta":_.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":_.input=g.input;break;case"tool-result":_.output=g.output,_.running=!1;break;case"tool-error":_.error=g.error,_.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":u.running=!1,u.finishReason=g.finishReason,u.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":u&&(u.running=!1,u.error=g.error,u.finishReason="error"),this.option.onFinish?.();break;case"abort":u&&(u.running=!1,u.error={message:g.reason},u.finishReason="other"),this.option.onFinish?.();break}})(),o}}function bx(t){const r=[];let o=0;for(;o<t.length;){const c="```schemaJson",u=t.indexOf(c,o),f=c.length;if(u===-1){const g=t.slice(o).trim();g&&r.push({type:"markdown",content:g});break}const m=t.slice(o,u).trim();m&&r.push({type:"markdown",content:m});const x=t.indexOf("```",u+f);let _;x===-1?(_=t.slice(u+f).trim(),o=t.length):(_=t.slice(u+f,x).trim(),o=x+3),r.push({type:"schema-card",content:_})}return r}class Ex{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
|
|
55
55
|
${this.staticPrompt}
|
|
56
56
|
${this.skillMetaPrompt}
|
|
57
57
|
${this.tempPrompt}
|
|
58
|
-
`}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const _o={model:"deepseek-ai/DeepSeek-V3",maxSteps:15,extraTools:{}},qa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function Ax(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const o={...r};for(const[c,u]of Object.entries(t))u&&typeof u=="object"&&!Array.isArray(u)?o[c]={...o[c]||{},...u}:o[c]=u;return o}class Ix extends Hn.BaseModelProvider{transport;agent;promptManager;llmConfig={..._o,...qa};isGenuiEnabled;debugStream=!1;pageToolsOnDemand=!1;_getRouteState=null;setRouteStateGetter(r){this._getRouteState=r}constructor(r,o,c){super(r);let u;c&&"llm"in c?u={..._o,...c}:u={..._o,...qa,...c||{}},this.llmConfig=u;const p={llmConfig:u.llm?{llm:u.llm}:{...u}};this.agent=new Ht.AgentModelProvider(p),this.promptManager=new Ex,this.promptManager.setStatic(o)}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:p,llm:x,providerOptions:_,headers:g}){if(x)this.agent.llm=x,this.llmConfig.model=r,this.llmConfig.useReActMode=p||!1,this.agent.useReActMode=p||!1;else if(f&&o&&u){const C=this.isGenuiEnabled?.value&&c||o;this.llmConfig.model=r,this.llmConfig.apiKey=u,this.llmConfig.baseURL=o,this.llmConfig.providerType=f,this.llmConfig.useReActMode=p||!1,this.agent.useReActMode=p||!1;let A;if(f==="deepseek")A=Cu;else if(f==="openai")A=ku;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:u,baseURL:C,...g?{headers:g}:{}})}this.llmConfig.providerOptions=_,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const o=r[r.length-1];if(o.role==="tool"&&o.content.length>0){const c=o.content[o.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",u=r[r.length-1];if(!u||u.role!==c||!this.isSnapshotContent(u.content))return r;const f=[...r];for(let p=f.length-2;p>=0;p--){const x=f[p];x.role===c&&this.isSnapshotContent(x.content)&&this.replaceSnapshotWithPlaceholder(x)}return f}removeSnapshotData(r){if(!r)return r;const o=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of o){const p=r.indexOf(f);if(p!==-1){c=p;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const u=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of u)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const o=r.content[0];if(o?.output?.value?.content){const c=o.output.value.content;Array.isArray(c)&&(o.output.value.content=c.map(u=>u.type==="image"||u.type==="image_url"?null:u.type==="text"&&u.text&&this.isSnapshotContent(u.text)?{type:"text",text:this.removeSnapshotData(u.text)}:u).filter(u=>u!==null)),o.output.value.screenshot&&delete o.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const o=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return o.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const u=c?.output?.value?.content?.[0]?.text;if(u&&o.some(f=>u.includes(f))||c.type==="text"&&c.text&&o.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,o){let c=r.messages[r.messages.length-1];if(!c)return;const u={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:{"get-today":jm,...this.llmConfig.extraTools||{}},maxSteps:this.llmConfig.maxSteps,providerOptions:Ax(this.llmConfig.providerOptions,vx),prepareStep:({messages:O})=>{this.cleanGetSkillContentToolResult(O);const k=this.cleanupOldSnapshotsInMessages(O),P=["get-today",...Object.keys(this.llmConfig.extraTools||{})],L=new Set;Object.values(this.agent.mcpTools||{}).forEach(Z=>{Object.keys(Z||{}).forEach($=>L.add($)),P.push(...Object.keys(Z||{}))});const Y=Array.from(new Set(P)).filter(Z=>{if(this.agent.ignoreToolnames.includes(Z))return!1;if(!this.pageToolsOnDemand)return!0;const $=this._getRouteState?.()??Gm(),H=$?.toolRouteMap??Ht.getToolRouteMap(),re=$?.activeRoutes??Ht.getActiveRoutes(),j=z=>z.replace(/\/+$/,"")||"/";if($&&$.initialized===!1)return!L.has(Z);const V=H.get(Z);if(V){const z=j(V);return re.has(z)||re.has(V)}return!0});return{system:this.promptManager.getSystemPrompt(),messages:k,activeTools:Y}},onStepFinish:O=>{if(O.finishReason==="tool-calls"&&O.content.length>0){const k=O.content[O.content.length-1];if(k.toolName==="get_skill_content"&&k.type==="tool-result"){const P=k.output.content;this.promptManager.appendTemp(P)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp("")}},f={role:"user",content:c.content},x=[...(O=>O.map(k=>({role:k.role,content:k.content})))(this.agent.responseMessages),f];u.messages=x;const _=await this.agent.chatStream(u),g=new ep,A=await new Cx({debug:this.debugStream,onFinish:()=>{v.nextTick(()=>{g.resolve(),o.onDone()})}}).traverse(_),B={role:"assistant",content:"",uiContent:[]};return v.watch(A,O=>{if(!O)o.onData(B);else{const P=O.steps.map(L=>L.contents).flat().map(L=>{if(L.type==="text")return bx(L.text);if(L.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:L.text,thinkId:L.id};if(L.type==="tool")return{type:"tool",id:L.id,name:L.toolName,content:JSON.stringify({input:L.inputStr,output:L.output}),status:L.error?"failed":L.running?"running":"success"}});if(O?.error){const L={type:"markdown",content:`**错误**:${O.error.responseBody||O.error.message||"未知错误"}`};P.push(L)}(O.steps.length>=1||O?.error)&&o.onData({...B,uiContent:P.flat(),usage:O.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const Sx=({systemPrompt:t,llmConfig:r})=>{const o=new Ix({provider:"custom"},t,r),c=new Hn.AIClient({providerImplementation:o,provider:"custom"}),{messageManager:u,createConversation:f,getCurrentConversation:p,switchConversation:x,deleteConversation:_,updateTitle:g,state:C}=Hn.useConversation({client:c,autoSave:!1,events:{onLoaded(){},onReceiveData(H,re,j){j(),re.value[re.value.length-1].role==="assistant"&&re.value.pop(),re.value.push(H)}}}),{messageState:A,inputMessage:B,sendMessage:O,abortRequest:k,messages:P,addMessage:L,send:Y}=u,Z=v.ref(),$=async(H,re,j)=>{if(j){const{shouldBlock:z}=await j(H);if(z)return!1}B.value=H;const V=p();if(V&&V.title==="新会话"&&g(V.id,B.value.slice(0,15)),re&&re.length>0){const z=[{type:"text",text:B.value},...re],M=[];B.value&&M.push({type:"text",content:B.value});for(const le of re)le.type==="image"&&le.image&&M.push({type:"image",content:le.image});const we={role:"user",content:z,uiContent:M};P.value.push(we),B.value="",Y()}else{const z={role:"user",content:B.value,uiContent:[{type:"text",content:B.value}]};P.value.push(z),B.value="",Y()}return!0};return v.onMounted(()=>{Z.value?.focus()}),v.onUnmounted(()=>{o.agent.closeAll()}),{agent:o.agent,customAgentProvider:o,client:c,messageManager:u,addMessage:L,send:Y,conversationState:C,messages:P,messageState:A,inputMessage:B,sendMessage:O,abortRequest:k,senderRef:Z,handleSendMessage:$,createConversation:f,switchConversation:x,deleteConversation:_,getCurrentConversation:p}};function Tx(){}const kn=Object.assign,rs=typeof window<"u",ji=t=>t!==null&&typeof t=="object",Jn=t=>t!=null,Lo=t=>typeof t=="function",Nx=t=>ji(t)&&Lo(t.then)&&Lo(t.catch),Mu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Ox=()=>rs?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const o=r.split(".");let c=t;return o.forEach(u=>{var f;c=ji(c)&&(f=c[u])!=null?f:""}),c}function Rx(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const Bi=null,an=[Number,String],lr={type:Boolean,default:!0},kx=t=>({type:Number,default:t}),ln=t=>({type:String,default:t});var is=typeof window<"u";function Du(t){let r;v.onMounted(()=>{t(),v.nextTick(()=>{r=!0})}),v.onActivated(()=>{r&&t()})}function Pu(t,r,o={}){if(!is)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let p=!1,x;const _=A=>{if(p)return;const B=v.unref(A);B&&!x&&(B.addEventListener(t,r,{capture:f,passive:u}),x=!0)},g=A=>{if(p)return;const B=v.unref(A);B&&x&&(B.removeEventListener(t,r,f),x=!1)};v.onUnmounted(()=>g(c)),v.onDeactivated(()=>g(c)),Du(()=>_(c));let C;return v.isRef(c)&&(C=v.watch(c,(A,B)=>{g(B),_(A)})),()=>{C?.(),g(c),p=!0}}var Ai,vo;function Mx(){if(!Ai&&(Ai=v.ref(0),vo=v.ref(0),is)){const t=()=>{Ai.value=window.innerWidth,vo.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Ai,height:vo}}var Dx=/scroll|auto|overlay/i,Px=is?window:void 0;function Bx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Lx(t,r=Px){let o=t;for(;o&&o!==r&&Bx(o);){const{overflowY:c}=window.getComputedStyle(o);if(Dx.test(c))return o;o=o.parentNode}return r}Ox();const Fx=t=>t.stopPropagation();function Bu(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Fx(t)}Mx();function _n(t){if(Jn(t))return Mu(t)?`${t}px`:String(t)}function Ux(t){if(Jn(t)){if(Array.isArray(t))return{width:_n(t[0]),height:_n(t[1])};const r=_n(t);return{width:r,height:r}}}function zx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const $x=/-(\w)/g,Lu=t=>t.replace($x,(r,o)=>o.toUpperCase()),Vx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Zx}=Object.prototype;function jx(t,r,o){const c=r[o];Jn(c)&&(!Zx.call(t,o)||!ji(c)?t[o]=c:t[o]=Fu(Object(t[o]),c))}function Fu(t,r){return Object.keys(r).forEach(o=>{jx(t,r,o)}),t}var Wx={name:"姓名",tel:"电话",save:"保存",clear:"清空",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ja=v.ref("zh-CN"),Ka=v.reactive({"zh-CN":Wx}),Hx={messages(){return Ka[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Fu(Ka,t)}};var Gx=Hx;function Xx(t){const r=Lu(t)+".";return(o,...c)=>{const u=Gx.messages(),f=Ya(u,r+o)||Ya(u,o);return Lo(f)?f(...c):f}}function Fo(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((o,c)=>o+Fo(t,c),""):Object.keys(r).reduce((o,c)=>o+(r[c]?Fo(t,c):""),""):""}function qx(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Fo(r,o)}`)}function hr(t){const r=`van-${t}`;return[r,qx(r),Xx(r)]}const Yx="van-haptics-feedback",Qa=5;function Jx(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);Nx(f)?f.then(p=>{p?o():c&&c()}).catch(u||Tx):f?o():c&&c()}else o()}function si(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(Lu(`-${o}`),t))},t}const Kx=Symbol();function Uu(t){const r=v.getCurrentInstance();r&&kn(r.proxy,t)}const[Qx,el]=hr("badge"),ey={dot:Boolean,max:an,tag:ln("div"),color:String,offset:Array,content:an,showZero:lr,position:ln("top-right")};var ty=v.defineComponent({name:Qx,props:ey,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:x,showZero:_}=t;return Jn(x)&&x!==""&&(_||x!==0&&x!=="0")},c=()=>{const{dot:x,max:_,content:g}=t;if(!x&&o())return r.content?r.content():Jn(_)&&Mu(g)&&+g>+_?`${_}+`:g},u=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=v.computed(()=>{const x={background:t.color};if(t.offset){const[_,g]=t.offset,{position:C}=t,[A,B]=C.split("-");r.default?(typeof g=="number"?x[A]=_n(A==="top"?g:-g):x[A]=A==="top"?_n(g):u(g),typeof _=="number"?x[B]=_n(B==="left"?_:-_):x[B]=B==="left"?_n(_):u(_)):(x.marginTop=_n(g),x.marginLeft=_n(_))}return x}),p=()=>{if(o()||t.dot)return v.createVNode("div",{class:el([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return v.createVNode(x,{class:el("wrapper")},{default:()=>[r.default(),p()]})}return p()}}});const ny=si(ty);let zu=2e3;const ry=()=>++zu,iy=t=>{zu=t},[$u,oy]=hr("config-provider"),Vu=Symbol($u),sy={tag:ln("div"),theme:ln("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:ln("local"),iconPrefix:String};function ay(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function ly(t){const r={};return Object.keys(t).forEach(o=>{const c=ay(Vx(o));r[`--van-${c}`]=t[o]}),r}function Ii(t={},r={}){Object.keys(t).forEach(o=>{t[o]!==r[o]&&document.documentElement.style.setProperty(o,t[o])}),Object.keys(r).forEach(o=>{t[o]||document.documentElement.style.removeProperty(o)})}v.defineComponent({name:$u,props:sy,setup(t,{slots:r}){const o=v.computed(()=>ly(kn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(rs){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},u=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};v.watch(()=>t.theme,(f,p)=>{p&&u(p),c()},{immediate:!0}),v.onActivated(c),v.onDeactivated(u),v.onBeforeUnmount(u),v.watch(o,(f,p)=>{t.themeVarsScope==="global"&&Ii(f,p)}),v.watch(()=>t.themeVarsScope,(f,p)=>{p==="global"&&Ii({},o.value),f==="global"&&Ii(o.value,{})}),t.themeVarsScope==="global"&&Ii(o.value,{})}return v.provide(Vu,t),v.watchEffect(()=>{t.zIndex!==void 0&&iy(t.zIndex)}),()=>v.createVNode(t.tag,{class:oy(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[cy,tl]=hr("icon"),uy=t=>t?.includes("/"),dy={dot:Boolean,tag:ln("i"),name:String,size:an,badge:an,color:String,badgeProps:Object,classPrefix:String};var fy=v.defineComponent({name:cy,props:dy,setup(t,{slots:r}){const o=v.inject(Vu,null),c=v.computed(()=>t.classPrefix||o?.iconPrefix||tl());return()=>{const{tag:u,dot:f,name:p,size:x,badge:_,color:g}=t,C=uy(p);return v.createVNode(ny,v.mergeProps({dot:f,tag:u,class:[c.value,C?"":`${c.value}-${p}`],style:{color:g,fontSize:_n(x)},content:_},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),C&&v.createVNode("img",{class:tl("image"),src:p},null)]}})}}});const os=si(fy),[hy,qr]=hr("loading"),py=Array(12).fill(null).map((t,r)=>v.createVNode("i",{class:qr("line",String(r+1))},null)),my=v.createVNode("svg",{class:qr("circular"),viewBox:"25 25 50 50"},[v.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),gy={size:an,type:ln("circular"),color:String,vertical:Boolean,textSize:an,textColor:String};var xy=v.defineComponent({name:hy,props:gy,setup(t,{slots:r}){const o=v.computed(()=>kn({color:t.color},Ux(t.size))),c=()=>{const f=t.type==="spinner"?py:my;return v.createVNode("span",{class:qr("spinner",t.type),style:o.value},[r.icon?r.icon():f])},u=()=>{var f;if(r.default)return v.createVNode("span",{class:qr("text"),style:{fontSize:_n(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:p}=t;return v.createVNode("div",{class:qr([f,{vertical:p}]),"aria-live":"polite","aria-busy":!0},[c(),u()])}}});const yy=si(xy),wy={show:Boolean,zIndex:an,overlay:lr,duration:an,teleport:[String,Object],lockScroll:lr,lazyRender:lr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Bi,transitionAppear:Boolean,closeOnClickOverlay:lr};function _y(t,r){return t>r?"horizontal":r>t?"vertical":""}function vy(){const t=v.ref(0),r=v.ref(0),o=v.ref(0),c=v.ref(0),u=v.ref(0),f=v.ref(0),p=v.ref(""),x=v.ref(!0),_=()=>p.value==="vertical",g=()=>p.value==="horizontal",C=()=>{o.value=0,c.value=0,u.value=0,f.value=0,p.value="",x.value=!0};return{move:(O=>{const k=O.touches[0];o.value=(k.clientX<0?0:k.clientX)-t.value,c.value=k.clientY-r.value,u.value=Math.abs(o.value),f.value=Math.abs(c.value);const P=10;(!p.value||u.value<P&&f.value<P)&&(p.value=_y(u.value,f.value)),x.value&&(u.value>Qa||f.value>Qa)&&(x.value=!1)}),start:(O=>{C(),t.value=O.touches[0].clientX,r.value=O.touches[0].clientY}),reset:C,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:p,isVertical:_,isHorizontal:g,isTap:x}}let $r=0;const nl="van-overflow-hidden";function Cy(t,r){const o=vy(),c="01",u="10",f=C=>{o.move(C);const A=o.deltaY.value>0?u:c,B=Lx(C.target,t.value),{scrollHeight:O,offsetHeight:k,scrollTop:P}=B;let L="11";P===0?L=k>=O?"00":"01":P+k>=O&&(L="10"),L!=="11"&&o.isVertical()&&!(parseInt(L,2)&parseInt(A,2))&&Bu(C)},p=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),$r||document.body.classList.add(nl),$r++},x=()=>{$r&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),$r--,$r||document.body.classList.remove(nl))},_=()=>r()&&p(),g=()=>r()&&x();Du(_),v.onDeactivated(g),v.onBeforeUnmount(g),v.watch(r,C=>{C?p():x()})}function Zu(t){const r=v.ref(!1);return v.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const rl=()=>{var t;const{scopeId:r}=((t=v.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[by,Ey]=hr("overlay"),Ay={show:Boolean,zIndex:an,duration:an,className:Bi,lockScroll:lr,lazyRender:lr,customStyle:Object,teleport:[String,Object]};var Iy=v.defineComponent({name:by,inheritAttrs:!1,props:Ay,setup(t,{attrs:r,slots:o}){const c=v.ref(),u=Zu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Bu(x)},p=u(()=>{var x;const _=kn(zx(t.zIndex),t.customStyle);return Jn(t.duration)&&(_.animationDuration=`${t.duration}s`),v.withDirectives(v.createVNode("div",v.mergeProps({ref:c,style:_,class:[Ey(),t.className]},r),[(x=o.default)==null?void 0:x.call(o)]),[[v.vShow,t.show]])});return Pu("touchmove",f,{target:c}),()=>{const x=v.createVNode(v.Transition,{name:"van-fade",appear:!0},{default:p});return t.teleport?v.createVNode(v.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const Sy=si(Iy),Ty=kn({},wy,{round:Boolean,position:ln("center"),closeIcon:ln("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:ln("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[Ny,il]=hr("popup");var Oy=v.defineComponent({name:Ny,inheritAttrs:!1,props:Ty,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:o,slots:c}){let u,f;const p=v.ref(),x=v.ref(),_=Zu(()=>t.show||!t.lazyRender),g=v.computed(()=>{const j={zIndex:p.value};if(Jn(t.duration)){const V=t.position==="center"?"animationDuration":"transitionDuration";j[V]=`${t.duration}s`}return j}),C=()=>{u||(u=!0,p.value=t.zIndex!==void 0?+t.zIndex:ry(),r("open"))},A=()=>{u&&Jx(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},B=j=>{r("clickOverlay",j),t.closeOnClickOverlay&&A()},O=()=>{if(t.overlay){const j=kn({show:t.show,class:t.overlayClass,zIndex:p.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return v.createVNode(Sy,v.mergeProps(j,rl(),{onClick:B}),{default:c["overlay-content"]})}},k=j=>{r("clickCloseIcon",j),A()},P=()=>{if(t.closeable)return v.createVNode(os,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),Yx],classPrefix:t.iconPrefix,onClick:k},null)};let L;const Y=()=>{L&&clearTimeout(L),L=setTimeout(()=>{r("opened")})},Z=()=>r("closed"),$=j=>r("keydown",j),H=_(()=>{var j;const{destroyOnClose:V,round:z,position:M,safeAreaInsetTop:we,safeAreaInsetBottom:le,show:fe}=t;if(!(!fe&&V))return v.withDirectives(v.createVNode("div",v.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:z,[M]:M}),{"van-safe-area-top":we,"van-safe-area-bottom":le}],onKeydown:$},o,rl()),[(j=c.default)==null?void 0:j.call(c),P()]),[[v.vShow,fe]])}),re=()=>{const{position:j,transition:V,transitionAppear:z}=t,M=j==="center"?"van-fade":`van-popup-slide-${j}`;return v.createVNode(v.Transition,{name:V||M,appear:z,onAfterEnter:Y,onAfterLeave:Z},{default:H})};return v.watch(()=>t.show,j=>{j&&!u&&(C(),o.tabindex===0&&v.nextTick(()=>{var V;(V=x.value)==null||V.focus()})),!j&&u&&(u=!1,r("close"))}),Uu({popupRef:x}),Cy(x,()=>t.show&&t.lockScroll),Pu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),v.onMounted(()=>{t.show&&C()}),v.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),v.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),v.provide(Kx,()=>t.show),()=>t.teleport?v.createVNode(v.Teleport,{to:t.teleport},{default:()=>[O(),re()]}):v.createVNode(v.Fragment,null,[O(),re()])}});const Ry=si(Oy);let Vr=0;function ky(t){t?(Vr||document.body.classList.add("van-toast--unclickable"),Vr++):Vr&&(Vr--,Vr||document.body.classList.remove("van-toast--unclickable"))}const[My,Er]=hr("toast"),Dy=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Py={icon:String,show:Boolean,type:ln("text"),overlay:Boolean,message:an,iconSize:an,duration:kx(2e3),position:ln("middle"),teleport:[String,Object],wordBreak:String,className:Bi,iconPrefix:String,transition:ln("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Bi,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:an};var By=v.defineComponent({name:My,props:Py,emits:["update:show"],setup(t,{emit:r,slots:o}){let c,u=!1;const f=()=>{const A=t.show&&t.forbidClick;u!==A&&(u=A,ky(u))},p=A=>r("update:show",A),x=()=>{t.closeOnClick&&p(!1)},_=()=>clearTimeout(c),g=()=>{const{icon:A,type:B,iconSize:O,iconPrefix:k,loadingType:P}=t;if(A||B==="success"||B==="fail")return v.createVNode(os,{name:A||B,size:O,class:Er("icon"),classPrefix:k},null);if(B==="loading")return v.createVNode(yy,{class:Er("loading"),size:O,type:P},null)},C=()=>{const{type:A,message:B}=t;if(o.message)return v.createVNode("div",{class:Er("text")},[o.message()]);if(Jn(B)&&B!=="")return A==="html"?v.createVNode("div",{key:0,class:Er("text"),innerHTML:String(B)},null):v.createVNode("div",{class:Er("text")},[B])};return v.watch(()=>[t.show,t.forbidClick],f),v.watch(()=>[t.show,t.type,t.message,t.duration],()=>{_(),t.show&&t.duration>0&&(c=setTimeout(()=>{p(!1)},t.duration))}),v.onMounted(f),v.onUnmounted(f),()=>v.createVNode(Ry,v.mergeProps({class:[Er([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:_,"onUpdate:show":p},Rx(t,Dy)),{default:()=>[g(),C()]})}});function Ly(){const t=v.reactive({show:!1}),r=u=>{t.show=u},o=u=>{kn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Uu({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function Fy(t){const r=v.createApp(t),o=document.createElement("div");return document.body.appendChild(o),{instance:r.mount(o),unmount(){r.unmount(),document.body.removeChild(o)}}}const Uy={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let Si=[],zy=!1,ol=kn({},Uy);const $y=new Map;function ju(t){return ji(t)?t:{message:t}}function Vy(){const{instance:t}=Fy({setup(){const r=v.ref(""),{open:o,state:c,close:u,toggle:f}=Ly(),p=()=>{},x=()=>{const _={onClosed:p,"onUpdate:show":f};return v.createVNode(By,v.mergeProps(c,_),null)};return v.watch(r,_=>{c.message=_}),v.getCurrentInstance().render=x,{open:o,close:u,message:r}}});return t}function Zy(){if(!Si.length||zy){const t=Vy();Si.push(t)}return Si[Si.length-1]}function et(t={}){if(!rs)return{};const r=Zy(),o=ju(t);return r.open(kn({},ol,$y.get(o.type||ol.type),o)),r}const jy=t=>r=>et(kn({type:t},ju(r))),Wu=jy("loading"),Wy=t=>{try{const r=JSON.parse(t),o=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,u]of Object.entries(r.mcpServers)){const f=Hy(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Hy=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:o,sessionId:c}=t;return r==="extension"?c?{type:"extension",url:o,sessionId:c,useAISdkClient:!0}:null:r==="streamableHttp"||r==="sse"?{type:r,url:o,useAISdkClient:!0}:{type:"streamableHttp",url:o,useAISdkClient:!0}},Gy=(t,r,o)=>{const c=async(f,p,x,_,g)=>{if(await t.insertMcpServer(f,p)){const A=t.mcpTools[f];if(A){const O={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||o,description:_||(typeof p=="object"&&"url"in p?p.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(k=>({id:k,name:k,description:A[k].description,enabled:!0})),originMcpConfig:v.markRaw(p)};return r.value.push(O),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,p)=>{Wu("添加工具中...");try{if(f==="code"){if(typeof p!="string"){et("添加工具失败:code 类型需要 JSON 字符串格式");return}const Y=Wy(p);if(Y.length===0){et("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let Z=0,$=0;for(const{name:H,config:re}of Y){const j=`mcp-server-${H}`;await c(j,re,H)?Z++:$++}await t.closeAll(),$===0?et(`成功添加 ${Z} 个工具`):Z>0?et(`成功添加 ${Z} 个工具,${$} 个失败`):et("添加工具失败:所有服务器都无法连接");return}if(typeof p=="string"){et("添加工具失败:数据格式不正确");return}const{description:x,headers:_,name:g,thumbnail:C,type:A,url:B}=p;if(!g||!B||!A){et("添加工具失败:缺少必要参数(名称、URL或类型)");return}const k=`mcp-server-${`custom-${g}-${Date.now()}`}`;await c(k,{type:A,url:B,useAISdkClient:!0},g,x,C)?(await t.closeAll(),et("添加工具完成")):et("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),et(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Xy(t,r,o){const c=v.ref([]),u=v.ref([]),f=v.ref(!1),p=H=>H==="mcp-server-localhost",x=(H,re)=>{re?t.ignoreToolnames=t.ignoreToolnames.filter(j=>j!==H):t.ignoreToolnames.includes(H)||t.ignoreToolnames.push(H)},_=(H,re)=>{r.value||(r.value={});const j={...r.value};H===null?Object.keys(j).forEach(V=>{j[V]=re}):j[H]=re,r.value=j},g=H=>{const re=u.value.find(j=>j.id===H);re&&(re.addState="idle")},C=H=>{const re=t.mcpTools[H];if(!re)return[];const j=p(H),V=r.value||{};return Object.keys(re).map(z=>{const M=j?!!V[z]:!0;return x(z,M),{id:z,name:z,description:re[z].description,enabled:M}})},A=async H=>{const re=H.pluginId;if(!await t.insertMcpServer(re,H.mcpServer))return!1;if(!t.mcpTools[re])return await t.removeMcpServer(re),!1;const z=C(re);if(z.length===0)return await t.removeMcpServer(re),!1;const M=c.value.find(le=>le.id===H.pluginId);if(M)return M.tools=z,M.originMcpConfig=v.markRaw(H.mcpServer),!0;const we={id:H.pluginId,name:H.name,icon:H.icon||o,description:H.description,enabled:!0,expanded:!1,tools:z,originMcpConfig:v.markRaw(H.mcpServer)};return c.value.push(we),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async(H,re)=>{let j,V;if("type"in re&&re.type==="local")j="本地工具",V="本地工具列表";else{const z=new URL(re.url);j=z.origin,V=z.searchParams.get("sessionId")||("sessionId"in re?re.sessionId:"")||""}await A({pluginId:H,name:j,description:V,mcpServer:re})},togglePlugin:(H,re)=>{const j=p(H.id);H.tools.forEach(V=>{V.enabled=re,x(V.id,re),j&&_(V.id,re)})},toggleTool:(H,re,j)=>{const V=p(H.id);H.tools.forEach(z=>{z.id===re&&(z.enabled=j)}),x(re,j),V&&_(re,j)},deletePlugin:async H=>{const re=c.value.find(V=>V.id===H.id);if(!re)return;c.value=c.value.filter(V=>V.id!==re.id),g(re.id);const j=H.id;await t.removeMcpServer(j)},addPluginCore:A,addPluginFromMarket:async H=>{H.addState="loading";const re={type:H.type,url:H.url,useAISdkClient:!0},j=await A({pluginId:H.id,name:H.name,description:H.description||"",icon:H.icon,mcpServer:re});H.addState=j?"added":"idle"},addPluginFromScan:async(H,re)=>{const j={type:"streamableHttp",url:`${re}mcp?sessionId=${H}`},V=new URL(`${re}mcp?sessionId=${H}`);return await A({pluginId:`plugin-${H}`,name:V.origin,description:H,mcpServer:j})},handleClientDisconnected:async H=>{const re=H,j=c.value.find(V=>V.id===re);return await t.removeMcpServer(H),j?(c.value=c.value.filter(V=>V.id!==re),g(re),j):null},searchPlugin:(H,re)=>H.trim()===""||re.name.toLowerCase().includes(H.toLowerCase())}}function qy(t){const{skillsRef:r,customAgentProvider:o}=t,c=v.computed(()=>{const x=r?.value;return x?Ht.getSkillOverviews(x):[]}),u=v.computed(()=>{const x=c.value;return x.length>0?Ht.formatSkillsForSystemPrompt(x):""}),f=v.computed(()=>{const x=r?.value;return x?Ht.createSkillTools(x):{}});return v.watchEffect(()=>{if(o.promptManager.setSkillMeta(u.value),o.llmConfig){const x=o.llmConfig.extraTools??{};o.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:u,skillTools:f,skillOverviews:c}}const Yy=["title"],Jy=v.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,o=v.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=v.computed(()=>{const{inputTokens:f=0,outputTokens:p=0,totalTokens:x=0,inputTokenDetails:_,outputTokenDetails:g}=r.usage,C=_?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[C/x*100+"%",C],inputTokens:[(f-C)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(p-A)/x*100+"%",p]}}),u=v.computed(()=>{const{inputTokens:f=0,outputTokens:p=0,totalTokens:x=0,inputTokenDetails:_,outputTokenDetails:g}=r.usage,C=_?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${p}`,`totalTokens: ${x}`,`cachedInputTokens: ${C}`,`reasoningTokens: ${A}`].join(`
|
|
59
|
-
`)});return(f,p)=>o.value?v.createCommentVNode("",!0):(v.openBlock(),v.createElementBlock("div",{key:0,class:"token-usage-wrap",title:u.value},[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(c.value,(x,_)=>(v.openBlock(),v.createElementBlock("div",{key:_,class:v.normalizeClass(_),style:v.normalizeStyle({width:x[0]})},null,6))),128))],8,Yy))}}),Kn=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},Ky=Kn(Jy,[["__scopeId","data-v-000098b4"]]),Qy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function ew(t,r){return v.openBlock(),v.createElementBlock("svg",Qy,[...r[0]||(r[0]=[v.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),v.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[v.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),v.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const Hu={render:ew};function tw(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=v.h(Hu,{style:{width:"48px",height:"48px"}}),p=v.ref({}),x=v.computed(()=>Hn.GeneratingStatus.includes(o.status)),_=v.computed(()=>r.value.findLastIndex(O=>O.role==="assistant")),g=O=>O===void 0?"复制":p.value[O]?"复制成功":"复制",C=async O=>{const k=r.value[O],P=typeof k.content=="string"?k.content:JSON.stringify(k.content);try{await navigator.clipboard.writeText(P),O!==void 0&&(p.value[O]=!0,setTimeout(()=>{p.value[O]=!1},3e3))}catch(L){console.error("复制失败:",L),et("复制失败,请重试")}},A=async O=>{const k=r.value.findLastIndex((L,Y)=>L.role==="user"&&Y<=O);if(k===-1){console.warn("未找到可重新生成的用户消息"),et("无法重新生成消息");return}const P=r.value[k];if(r.value=r.value.slice(0,k),Array.isArray(P.content)){const Y=P.content.find($=>$.type==="text")?.text||"",Z=P.content.filter($=>$.type!=="text");c.value=Y,await u(Y,Z.length>0?Z:void 0)}else c.value=P.content,await u(P.content)},B={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:O})=>{const k=_.value===O;return x.value&&k?"":v.h("div",{class:["assistant-actions",{"latest-assistant":k,"historical-assistant":!k}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[v.h(Pt.IconButton,{icon:Sr.IconRefresh,size:24,onClick:()=>A(O)}),v.h(Td,{effect:"light",content:g(O),placement:"right",visibleArrow:!1},()=>v.h(Pt.IconButton,{icon:Sr.IconCopy,size:24,onClick:()=>C(O)})),r.value[O].usage?v.h(Ky,{usage:r.value[O].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:B,copyingStates:p,isProcessing:x,latestAssistantMessageIndex:_,copyTooltipContent:g,copyMessageToClipboard:C,regenerateMessage:A}}function nw(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:p,customAgentProvider:x}=t,_=v.ref(!1),g=()=>{v.nextTick(()=>{const k=document.querySelector("div.tr-bubble-list");k&&k.scrollTo({top:k.scrollHeight,behavior:"smooth"})})};return{showHistory:_,handleCreateConversation:()=>{f();const k=[];x.agent.responseMessages=k,r();const P=u();P.aiSdkMessages=k},handleHistorySelect:k=>{f(),o(k.id);const P=u();x.agent.responseMessages=P.aiSdkMessages,_.value=!1,g()},handleHistoryUpdateTitle:(k,P)=>{P.title=k},handleHistoryDelete:(k,P)=>{if(k.id==="delete"){if(p.currentId===P.id){et("不允许删除当前会话");return}c(P.id)}},scrollToBottom:g}}function rw(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:p,AILogoUrl:x,show:_,addPluginFromScan:g,inputMessage:C}=t;let A=null,B=!1;const O=async Z=>{if(Wu("添加工具中..."),Z){const $=await g(Z,o);et($?"添加工具完成":"重复添加工具或添加失败")}else et("添加工具失败")},k=async Z=>{if(/^\/[A-Za-z0-9-]{6,}$/.test(Z)){try{const $=await fetch(`${o}client?sessionId=${Z.slice(1)}`);if(!$.ok)throw new Error(`HTTP ${$.status}`);const re=(await $.json())?.data?.sessionId;re?await O(re):et("添加工具失败,请检查识别码是否正确"),C.value=""}catch($){console.error("识别码处理失败:",$),et("添加工具失败,请检查识别码是否正确"),C.value=""}return!0}return!1},P=()=>{v.watch(r,Z=>{if(c!=="remoter")return;const $=!!Z;A?!B&&$&&(A.destroy(),A=Ht.createRemoter({sessionId:Z,qrCodeUrl:u,remoteUrl:f,menuItems:p,logoUrl:x,onShowAIChat:()=>_.value=!0}),B=!0):(A=Ht.createRemoter({sessionId:Z||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:p,logoUrl:x,onShowAIChat:()=>_.value=!0}),B=$),A&&_.value&&A.hide()},{immediate:!0}),v.watch(_,Z=>{A&&(Z?A.hide():A.show())},{immediate:!0})},L=()=>{v.watch(r,Z=>{Z&&O(Z)})};return{handleScanSuccess:O,handleSessionIdInput:k,initialize:()=>{r.value&&O(r.value),c==="remoter"&&P(),L()},initializeRemoter:P,watchSessionIdChanges:L}}function iw(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function ow(t){return t.type.startsWith("image/")}function sw(t,r){const o=r*1024*1024;return t.size<=o}async function aw(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await iw(o.rawFile);ow(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),et({type:"fail",message:"文件处理失败"})}return r}function lw(t={}){const r=v.ref([]),o=async u=>{if(!u||u.length===0)return;c();const f=v.unref(t.maxFileSize)||10,p=v.unref(t.supportedTypes)||["image/"];for(const x of u){if(!p.some(g=>x.type.startsWith(g))){et({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!sw(x,f)){et({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(u=>{u.url&&URL.revokeObjectURL(u.url)}),r.value=[]};return{attachments:r,handleFilesSelected:o,clearAttachments:c}}function cw(t){const{selectedModel:r,selectedModelId:o}=t,c=v.computed(()=>r.value?.multimodal?.supportImages??!1),u=v.computed(()=>r.value?.multimodal?.maxFileSize||10),f=v.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:p,handleFilesSelected:x,clearAttachments:_}=lw({maxFileSize:u,supportedTypes:f});return v.watch(o,()=>{if(p.value.length>0&&r.value){const O=r.value.multimodal?.maxFileSize||10,k=r.value.multimodal?.supportedMimeTypes||["image/"];p.value.filter(L=>{if(!L.rawFile||!k.some($=>L.rawFile.type.startsWith($)))return!0;const Z=O*1024*1024;return L.rawFile.size>Z}).length>0&&(_(),et("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:p,onFilesSelected:O=>{x(O)},checkCanSendAttachments:()=>p.value.length>0&&!c.value?(et("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>p.value.length===0?[]:await aw(p.value),cleanupAttachments:()=>{p.value.length>0&&_()},clearAttachments:_}}var ve;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ve||(ve={}));var sl=new Map([[ve.QR_CODE,"QR_CODE"],[ve.AZTEC,"AZTEC"],[ve.CODABAR,"CODABAR"],[ve.CODE_39,"CODE_39"],[ve.CODE_93,"CODE_93"],[ve.CODE_128,"CODE_128"],[ve.DATA_MATRIX,"DATA_MATRIX"],[ve.MAXICODE,"MAXICODE"],[ve.ITF,"ITF"],[ve.EAN_13,"EAN_13"],[ve.EAN_8,"EAN_8"],[ve.PDF_417,"PDF_417"],[ve.RSS_14,"RSS_14"],[ve.RSS_EXPANDED,"RSS_EXPANDED"],[ve.UPC_A,"UPC_A"],[ve.UPC_E,"UPC_E"],[ve.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),al;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(al||(al={}));function uw(t){return Object.values(ve).includes(t)}var ti;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(ti||(ti={}));var dw=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[ti.SCAN_TYPE_CAMERA,ti.SCAN_TYPE_FILE],t})(),Gu=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!sl.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,sl.get(r))},t})(),ll=(function(){function t(){}return t.createFromText=function(r){var o={text:r};return{decodedText:r,result:o}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Uo;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Uo||(Uo={}));var fw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Uo.UNKWOWN_ERROR}},t})(),hw=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,o){(this.verbose||o===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function Mn(t){return typeof t>"u"||t===null}var Ir=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Xu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,o){if(typeof r!="object"){var c=typeof r;return o.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var u=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(u),p=Object.keys(r),x=0,_=p;x<_.length;x++){var g=_[x];if(f.has(g))return o.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),Hr={exports:{}},pw=Hr.exports,cl;function mw(){return cl||(cl=1,(function(t,r){(function(o,c){c(r)})(pw,(function(o){function c(b){return b==null}var u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var n in e)e.hasOwnProperty(n)&&(b[n]=e[n])};function f(b,e){u(b,e);function n(){this.constructor=b}b.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function p(b,e){var n=Object.setPrototypeOf;n?n(b,e):b.__proto__=e}function x(b,e){e===void 0&&(e=b.constructor);var n=Error.captureStackTrace;n&&n(b,e)}var _=(function(b){f(e,b);function e(n){var i=this.constructor,s=b.call(this,n)||this;return Object.defineProperty(s,"name",{value:i.name,enumerable:!1}),p(s,i.prototype),x(s),s}return e})(Error);class g extends _{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class C extends g{}C.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class B{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,i,s){const a=this.binarizer.getLuminanceSource().crop(e,n,i,s);return new B(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new B(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new B(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class O extends g{static getChecksumInstance(){return new O}}O.kind="ChecksumException";class k{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class P{static arraycopy(e,n,i,s,a){for(;a--;)i[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class L extends g{}L.kind="IndexOutOfBoundsException";class Y extends L{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}Y.kind="ArrayIndexOutOfBoundsException";class Z{static fill(e,n){for(let i=0,s=e.length;i<s;i++)e[i]=n}static fillWithin(e,n,i,s){Z.rangeCheck(e.length,n,i);for(let a=n;a<i;a++)e[a]=s}static rangeCheck(e,n,i){if(n>i)throw new A("fromIndex("+n+") > toIndex("+i+")");if(n<0)throw new Y(n);if(i>e)throw new Y(i)}static asList(...e){return e}static create(e,n,i){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(i))}static createInt32Array(e,n,i){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(i))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let i=0,s=e.length;i<s;i++)if(e[i]!==n[i])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const i of e)n=31*n+i;return n}static fillUint8Array(e,n){for(let i=0;i!==e.length;i++)e[i]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const i=new Uint8Array(n);return i.set(e),i}return e.slice(0,n)}static copyOfRange(e,n,i){const s=i-n,a=new Int32Array(s);return P.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,i){i===void 0&&(i=Z.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,d=i(n,e[l]);if(d>0)s=l+1;else if(d<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class ${static numberOfTrailingZeros(e){let n;if(e===0)return 32;let i=31;return n=e<<16,n!==0&&(i-=16,e=n),n=e<<8,n!==0&&(i-=8,e=n),n=e<<4,n!==0&&(i-=4,e=n),n=e<<2,n!==0&&(i-=2,e=n),i-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}$.MIN_VALUE_32_BITS=-2147483648,$.MAX_VALUE=Number.MAX_SAFE_INTEGER;class H{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=H.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=H.makeArray(e);P.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=i[s]}const d=s*32+$.numberOfTrailingZeros(a);return d>n?n:d}getNextUnset(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=~i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=~i[s]}const d=s*32+$.numberOfTrailingZeros(a);return d>n?n:d}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new A;if(n===e)return;n--;const i=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=i;l<=s;l++){const d=l>i?0:e&31,m=(2<<(l<s?31:n&31))-(1<<d);a[l]|=m}}clear(){const e=this.bits.length,n=this.bits;for(let i=0;i<e;i++)n[i]=0}isRange(e,n,i){if(n<e||e<0||n>this.size)throw new A;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let d=s;d<=a;d++){const h=d>s?0:e&31,y=(2<<(d<a?31:n&31))-(1<<h)&4294967295;if((l[d]&y)!==(i?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let i=n;i>0;i--)this.appendBit((e>>i-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let i=0;i<n;i++)this.appendBit(e.get(i))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let i=0,s=n.length;i<s;i++)n[i]^=e.bits[i]}toBytes(e,n,i,s){for(let a=0;a<s;a++){let l=0;for(let d=0;d<8;d++)this.get(e)&&(l|=1<<7-d),e++;n[i+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),i=n+1,s=this.bits;for(let a=0;a<i;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==i*32){const a=i*32-this.size;let l=e[0]>>>a;for(let d=1;d<i;d++){const h=e[d];l|=h<<32-a,e[d-1]=l,l=h>>>a}e[i-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof H))return!1;const n=e;return this.size===n.size&&Z.equals(this.bits,n.bits)}hashCode(){return 31*this.size+Z.hashCode(this.bits)}toString(){let e="";for(let n=0,i=this.size;n<i;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new H(this.size,this.bits.slice())}}var re;(function(b){b[b.OTHER=0]="OTHER",b[b.PURE_BARCODE=1]="PURE_BARCODE",b[b.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",b[b.TRY_HARDER=3]="TRY_HARDER",b[b.CHARACTER_SET=4]="CHARACTER_SET",b[b.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",b[b.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",b[b.ASSUME_GS1=7]="ASSUME_GS1",b[b.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",b[b.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",b[b.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(re||(re={}));var j=re;class V extends g{static getFormatInstance(){return new V}}V.kind="FormatException";var z;(function(b){b[b.Cp437=0]="Cp437",b[b.ISO8859_1=1]="ISO8859_1",b[b.ISO8859_2=2]="ISO8859_2",b[b.ISO8859_3=3]="ISO8859_3",b[b.ISO8859_4=4]="ISO8859_4",b[b.ISO8859_5=5]="ISO8859_5",b[b.ISO8859_6=6]="ISO8859_6",b[b.ISO8859_7=7]="ISO8859_7",b[b.ISO8859_8=8]="ISO8859_8",b[b.ISO8859_9=9]="ISO8859_9",b[b.ISO8859_10=10]="ISO8859_10",b[b.ISO8859_11=11]="ISO8859_11",b[b.ISO8859_13=12]="ISO8859_13",b[b.ISO8859_14=13]="ISO8859_14",b[b.ISO8859_15=14]="ISO8859_15",b[b.ISO8859_16=15]="ISO8859_16",b[b.SJIS=16]="SJIS",b[b.Cp1250=17]="Cp1250",b[b.Cp1251=18]="Cp1251",b[b.Cp1252=19]="Cp1252",b[b.Cp1256=20]="Cp1256",b[b.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",b[b.UTF8=22]="UTF8",b[b.ASCII=23]="ASCII",b[b.Big5=24]="Big5",b[b.GB18030=25]="GB18030",b[b.EUC_KR=26]="EUC_KR"})(z||(z={}));class M{constructor(e,n,i,...s){this.valueIdentifier=e,this.name=i,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,M.VALUE_IDENTIFIER_TO_ECI.set(e,this),M.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];M.VALUES_TO_ECI.set(h,this)}for(const l of s)M.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new V("incorect value");const n=M.VALUES_TO_ECI.get(e);if(n===void 0)throw new V("incorect value");return n}static getCharacterSetECIByName(e){const n=M.NAME_TO_ECI.get(e);if(n===void 0)throw new V("incorect value");return n}equals(e){if(!(e instanceof M))return!1;const n=e;return this.getName()===n.getName()}}M.VALUE_IDENTIFIER_TO_ECI=new Map,M.VALUES_TO_ECI=new Map,M.NAME_TO_ECI=new Map,M.Cp437=new M(z.Cp437,Int32Array.from([0,2]),"Cp437"),M.ISO8859_1=new M(z.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),M.ISO8859_2=new M(z.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),M.ISO8859_3=new M(z.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),M.ISO8859_4=new M(z.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),M.ISO8859_5=new M(z.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),M.ISO8859_6=new M(z.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),M.ISO8859_7=new M(z.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),M.ISO8859_8=new M(z.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),M.ISO8859_9=new M(z.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),M.ISO8859_10=new M(z.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),M.ISO8859_11=new M(z.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),M.ISO8859_13=new M(z.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),M.ISO8859_14=new M(z.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),M.ISO8859_15=new M(z.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),M.ISO8859_16=new M(z.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),M.SJIS=new M(z.SJIS,20,"SJIS","Shift_JIS"),M.Cp1250=new M(z.Cp1250,21,"Cp1250","windows-1250"),M.Cp1251=new M(z.Cp1251,22,"Cp1251","windows-1251"),M.Cp1252=new M(z.Cp1252,23,"Cp1252","windows-1252"),M.Cp1256=new M(z.Cp1256,24,"Cp1256","windows-1256"),M.UnicodeBigUnmarked=new M(z.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),M.UTF8=new M(z.UTF8,26,"UTF8","UTF-8"),M.ASCII=new M(z.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),M.Big5=new M(z.Big5,28,"Big5"),M.GB18030=new M(z.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),M.EUC_KR=new M(z.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class le{static decode(e,n){const i=this.encodingName(n);return this.customDecoder?this.customDecoder(e,i):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(i)?this.decodeFallback(e,i):new TextDecoder(i).decode(e)}static shouldDecodeOnFallback(e){return!le.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const i=this.encodingName(n);return this.customEncoder?this.customEncoder(e,i):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof M?e:M.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(le.isDecodeFallbackSupported(i)){let s="";for(let a=0,l=e.length;a<l;a++){let d=e[a].toString(16);d.length<2&&(d="0"+d),s+="%"+d}return decodeURIComponent(s)}if(i.equals(M.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new we(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(M.UTF8)||e.equals(M.ISO8859_1)||e.equals(M.ASCII)}static encodeFallback(e){const i=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<i.length;a++)s.push(i[a].charCodeAt(0));return new Uint8Array(s)}}class fe{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return le.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(j.CHARACTER_SET)!==void 0)return n.get(j.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,m=0,y=0,E=0,I=0,R=0,F=0,U=0,q=0,ne=0;const me=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let xe=0;xe<i&&(s||a||l);xe++){const ue=e[xe]&255;l&&(d>0?(ue&128)===0?l=!1:d--:(ue&128)!==0&&((ue&64)===0?l=!1:(d++,(ue&32)===0?h++:(d++,(ue&16)===0?m++:(d++,(ue&8)===0?y++:l=!1))))),s&&(ue>127&&ue<160?s=!1:ue>159&&(ue<192||ue===215||ue===247)&&ne++),a&&(E>0?ue<64||ue===127||ue>252?a=!1:E--:ue===128||ue===160||ue>239?a=!1:ue>160&&ue<224?(I++,F=0,R++,R>U&&(U=R)):ue>127?(E++,R=0,F++,F>q&&(q=F)):(R=0,F=0))}return l&&d>0&&(l=!1),a&&E>0&&(a=!1),l&&(me||h+m+y>0)?fe.UTF8:a&&(fe.ASSUME_SHIFT_JIS||U>=3||q>=3)?fe.SHIFT_JIS:s&&a?U===2&&I===2||ne*10>=i?fe.SHIFT_JIS:fe.ISO88591:s?fe.ISO88591:a?fe.SHIFT_JIS:l?fe.UTF8:fe.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,m,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=m?parseInt(m.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(E){case"s":R=n[i];break;case"c":R=n[i][0];break;case"f":R=parseFloat(n[i]).toFixed(l);break;case"p":R=parseFloat(n[i]).toPrecision(l);break;case"e":R=parseFloat(n[i]).toExponential(l);break;case"x":R=parseInt(n[i]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let F=parseInt(h),U=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+U:U+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return le.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}fe.SHIFT_JIS=M.SJIS.getName(),fe.GB2312="GB2312",fe.ISO88591=M.ISO8859_1.getName(),fe.EUC_JP="EUC_JP",fe.UTF8=M.UTF8.getName(),fe.PLATFORM_DEFAULT_ENCODING=fe.UTF8,fe.ASSUME_SHIFT_JIS=!1;class ae{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=fe.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,i){for(let s=n;n<n+i;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class X{constructor(e,n,i,s){if(this.width=e,this.height=n,this.rowSize=i,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");i==null&&(i=Math.floor((e+31)/32)),this.rowSize=i,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,i=e[0].length,s=new X(i,n);for(let a=0;a<n;a++){const l=e[a];for(let d=0;d<i;d++)l[d]&&s.set(d,a)}return s}static parseFromString(e,n,i){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,d=-1,h=0,m=0;for(;m<e.length;)if(e.charAt(m)===`
|
|
60
|
-
`||e.charAt(
|
|
61
|
-
`){return this.buildToString(e,n,i)}buildToString(e,n,i){let s=new ae;for(let a=0,l=this.height;a<l;a++){for(let d=0,h=this.width;d<h;d++)s.append(this.get(d,a)?e:n);s.append(i)}return s.toString()}clone(){return new
|
|
62
|
-
`)}return n.toString()}}class he extends ee{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const i=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)i[a]=255-(i[a]&255);return i}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),i=new Uint8ClampedArray(n);for(let s=0;s<n;s++)i[s]=255-(e[s]&255);return i}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,i,s){return new he(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new he(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new he(this.delegate.rotateCounterClockwise45())}}class ge extends ee{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=ge.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return ge.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,i){const s=new Uint8ClampedArray(n*i);for(let a=0,l=0,d=e.length;a<d;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],E=e[a+1],I=e[a+2];h=306*y+601*E+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth(),s=e*i;return n===null?n=this.buffer.slice(s,s+i):(n.length<i&&(n=new Uint8ClampedArray(i)),n.set(this.buffer.slice(s,s+i))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,i,s){return super.crop(e,n,i,s),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const n=this.getTempCanvasElement(),i=n.getContext("2d"),s=e*ge.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,d=Math.ceil(Math.abs(Math.cos(s))*a+Math.abs(Math.sin(s))*l),h=Math.ceil(Math.abs(Math.sin(s))*a+Math.abs(Math.cos(s))*l);return n.width=d,n.height=h,i.translate(d/2,h/2),i.rotate(s),i.drawImage(this.canvas,a/-2,l/-2),this.buffer=ge.makeBufferFromCanvasImageData(n),this}invert(){return new he(this)}}ge.DEGREE_TO_RADIANS=Math.PI/180;class de{constructor(e,n,i){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=i||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var Ce=(globalThis||Ci||self||window||void 0)&&(globalThis||Ci||self||window||void 0).__awaiter||function(b,e,n,i){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function d(y){try{m(i.next(y))}catch(E){l(E)}}function h(y){try{m(i.throw(y))}catch(E){l(E)}}function m(y){y.done?a(y.value):s(y.value).then(d,h)}m((i=i.apply(b,e||[])).next())})};class Ve{constructor(e,n=500,i){this.reader=e,this.timeBetweenScansMillis=n,this._hints=i,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return Ce(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),n=[];for(const i of e){const s=i.kind==="video"?"videoinput":i.kind;if(s!=="videoinput")continue;const a=i.deviceId||i.id,l=i.label||`Video device ${n.length+1}`,d=i.groupId,h={deviceId:a,label:l,kind:s,groupId:d};n.push(h)}return n})}getVideoInputDevices(){return Ce(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new de(n.deviceId,n.label))})}findDeviceById(e){return Ce(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ce(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ce(this,void 0,void 0,function*(){this.reset();let i;e?i={deviceId:{exact:e}}:i={facingMode:"environment"};const s={video:i};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return Ce(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return Ce(this,void 0,void 0,function*(){this.reset();const i=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(i)})}decodeFromInputVideoDeviceContinuously(e,n,i){return Ce(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return Ce(this,void 0,void 0,function*(){let s;e?s={deviceId:{exact:e}}:s={facingMode:"environment"};const a={video:s};return yield this.decodeFromConstraints(a,n,i)})}decodeFromConstraints(e,n,i){return Ce(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,i)})}decodeFromStream(e,n,i){return Ce(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,i)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return Ce(this,void 0,void 0,function*(){const i=this.prepareVideoElement(n);return this.addVideoSource(i,e),this.videoElement=i,this.stream=e,yield this.playVideoOnLoadAsync(i),i})}playVideoOnLoadAsync(e){return new Promise((n,i)=>this.playVideoOnLoad(e,()=>n()))}playVideoOnLoad(e,n){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",n),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return Ce(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,n){const i=document.getElementById(e);if(!i)throw new C(`element with id '${e}' not found`);if(i.nodeName.toLowerCase()!==n.toLowerCase())throw new C(`element with id '${e}' must be an ${n} element`);return i}decodeFromImage(e,n){if(!e&&!n)throw new C("either imageElement with a src set or an url must be provided");return n&&!e?this.decodeFromImageUrl(n):this.decodeFromImageElement(e)}decodeFromVideo(e,n){if(!e&&!n)throw new C("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,n,i){if(e===void 0&&n===void 0)throw new C("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,i):this.decodeFromVideoElementContinuously(e,i)}decodeFromImageElement(e){if(!e)throw new C("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let i;return this.isImageLoaded(n)?i=this.decodeOnce(n,!1,!0):i=this._decodeOnLoadImage(n),i}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const i=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(i,n)}_decodeFromVideoElementSetup(e){if(!e)throw new C("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new C("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const i=this._decodeOnLoadImage(n);return n.src=e,i}decodeFromVideoUrl(e){if(!e)throw new C("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),i=this.decodeFromVideoElement(n);return n.src=e,i}decodeFromVideoUrlContinuously(e,n){if(!e)throw new C("An URL must be provided.");this.reset();const i=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(i,n);return i.src=e,s}_decodeOnLoadImage(e){return new Promise((n,i)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,i),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return Ce(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ce(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,n)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let n;return typeof e>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(n=e),n}prepareVideoElement(e){let n;return!e&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(n=e),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n}decodeOnce(e,n=!0,i=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new D("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const d=this.decode(e);a(d)}catch(d){const h=n&&d instanceof D,y=(d instanceof O||d instanceof V)&&i;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(d)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const i=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(i,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof O||s instanceof V,l=s instanceof D;(a||l)&&setTimeout(i,this._timeBetweenDecodingAttempts)}};i()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,i){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,i=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const n=this.getCaptureCanvas(e),i=new ge(n),s=new W(i);return new B(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const i=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=i}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let i,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(i=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=i+"px",n.style.height=s+"px",n.width=i,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Me{constructor(e,n,i=n==null?0:8*n.length,s,a,l=P.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=i,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,i==null?this.numBits=n==null?0:8*n.length:this.numBits=i,this.resultPoints=s,this.format=a,this.resultMetadata=null,l==null?this.timestamp=P.currentTimeMillis():this.timestamp=l}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,n)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const n=this.resultPoints;if(n===null)this.resultPoints=e;else if(e!==null&&e.length>0){const i=new Array(n.length+e.length);P.arraycopy(n,0,i,0,n.length),P.arraycopy(e,0,i,n.length,e.length),this.resultPoints=i}}getTimestamp(){return this.timestamp}toString(){return this.text}}var Ye;(function(b){b[b.AZTEC=0]="AZTEC",b[b.CODABAR=1]="CODABAR",b[b.CODE_39=2]="CODE_39",b[b.CODE_93=3]="CODE_93",b[b.CODE_128=4]="CODE_128",b[b.DATA_MATRIX=5]="DATA_MATRIX",b[b.EAN_8=6]="EAN_8",b[b.EAN_13=7]="EAN_13",b[b.ITF=8]="ITF",b[b.MAXICODE=9]="MAXICODE",b[b.PDF_417=10]="PDF_417",b[b.QR_CODE=11]="QR_CODE",b[b.RSS_14=12]="RSS_14",b[b.RSS_EXPANDED=13]="RSS_EXPANDED",b[b.UPC_A=14]="UPC_A",b[b.UPC_E=15]="UPC_E",b[b.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Ye||(Ye={}));var ie=Ye,ke;(function(b){b[b.OTHER=0]="OTHER",b[b.ORIENTATION=1]="ORIENTATION",b[b.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",b[b.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",b[b.ISSUE_NUMBER=4]="ISSUE_NUMBER",b[b.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",b[b.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",b[b.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",b[b.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",b[b.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",b[b.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(ke||(ke={}));var Ae=ke;class Ne{constructor(e,n,i,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=i,this.ecLevel=s,this.structuredAppendSequenceNumber=a,this.structuredAppendParity=l,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class ot{exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class Xe{constructor(e,n){if(n.length===0)throw new A;this.field=e;const i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(i-s),P.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const n=this.coefficients;let i;if(e===1){i=0;for(let l=0,d=n.length;l!==d;l++){const h=n[l];i=ot.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=ot.addOrSubtract(a.multiply(e,i),n[l]);return i}addOrSubtract(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){const l=n;n=i,i=l}let s=new Int32Array(i.length);const a=i.length-n.length;P.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=ot.addOrSubtract(n[l-a],i[l]);return new Xe(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1),d=this.field;for(let h=0;h<i;h++){const m=n[h];for(let y=0;y<a;y++)l[h+y]=ot.addOrSubtract(l[h+y],d.multiply(m,s[y]))}return new Xe(d,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,i=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=i.multiply(a[l],e);return new Xe(i,s)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return this.field.getZero();const i=this.coefficients,s=i.length,a=new Int32Array(s+e),l=this.field;for(let d=0;d<s;d++)a[d]=l.multiply(i[d],n);return new Xe(l,a)}divide(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new A("Divide by 0");const n=this.field;let i=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const d=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),m=e.multiplyByMonomial(d,h),y=n.buildMonomial(d,h);i=i.addOrSubtract(y),s=s.addOrSubtract(m)}return[i,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);if(i!==0){if(i<0?(e+=" - ",i=-i):e.length>0&&(e+=" + "),n===0||i!==1){const s=this.field.log(i);s===0?e+="1":s===1?e+="a":(e+="a^",e+=s)}n!==0&&(n===1?e+="x":(e+="x^",e+=n))}}return e}}class $t extends g{}$t.kind="ArithmeticException";class Ue extends ot{constructor(e,n,i){super(),this.primitive=e,this.size=n,this.generatorBase=i;const s=new Int32Array(n);let a=1;for(let d=0;d<n;d++)s[d]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let d=0;d<n-1;d++)l[s[d]]=d;this.logTable=l,this.zero=new Xe(this,Int32Array.from([0])),this.one=new Xe(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;const i=new Int32Array(e+1);return i[0]=n,new Xe(this,i)}inverse(e){if(e===0)throw new $t;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+$.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Ue.AZTEC_DATA_12=new Ue(4201,4096,1),Ue.AZTEC_DATA_10=new Ue(1033,1024,1),Ue.AZTEC_DATA_6=new Ue(67,64,1),Ue.AZTEC_PARAM=new Ue(19,16,1),Ue.QR_CODE_FIELD_256=new Ue(285,256,0),Ue.DATA_MATRIX_FIELD_256=new Ue(301,256,1),Ue.AZTEC_DATA_8=Ue.DATA_MATRIX_FIELD_256,Ue.MAXICODE_FIELD_64=Ue.AZTEC_DATA_6;class pn extends g{}pn.kind="ReedSolomonException";class Vt extends g{}Vt.kind="IllegalStateException";class bn{constructor(e){this.field=e}decode(e,n){const i=this.field,s=new Xe(i,e),a=new Int32Array(n);let l=!0;for(let R=0;R<n;R++){const F=s.evaluateAt(i.exp(R+i.getGeneratorBase()));a[a.length-1-R]=F,F!==0&&(l=!1)}if(l)return;const d=new Xe(i,a),h=this.runEuclideanAlgorithm(i.buildMonomial(n,1),d,n),m=h[0],y=h[1],E=this.findErrorLocations(m),I=this.findErrorMagnitudes(y,E);for(let R=0;R<E.length;R++){const F=e.length-1-i.log(E[R]);if(F<0)throw new pn("Bad error location");e[F]=Ue.addOrSubtract(e[F],I[R])}}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){const R=e;e=n,n=R}const s=this.field;let a=e,l=n,d=s.getZero(),h=s.getOne();for(;l.getDegree()>=(i/2|0);){let R=a,F=d;if(a=l,d=h,a.isZero())throw new pn("r_{i-1} was zero");l=R;let U=s.getZero();const q=a.getCoefficient(a.getDegree()),ne=s.inverse(q);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const me=l.getDegree()-a.getDegree(),xe=s.multiply(l.getCoefficient(l.getDegree()),ne);U=U.addOrSubtract(s.buildMonomial(me,xe)),l=l.addOrSubtract(a.multiplyByMonomial(me,xe))}if(h=U.multiply(d).addOrSubtract(F),l.getDegree()>=a.getDegree())throw new Vt("Division algorithm failed to reduce polynomial?")}const m=h.getCoefficient(0);if(m===0)throw new pn("sigmaTilde(0) was zero");const y=s.inverse(m),E=h.multiplyScalar(y),I=l.multiplyScalar(y);return[E,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const i=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(i[s]=a.inverse(l),s++);if(s!==n)throw new pn("Error locator degree does not match number of roots");return i}findErrorMagnitudes(e,n){const i=n.length,s=new Int32Array(i),a=this.field;for(let l=0;l<i;l++){const d=a.inverse(n[l]);let h=1;for(let m=0;m<i;m++)if(l!==m){const y=a.multiply(n[m],d),E=(y&1)===0?y|1:y&-2;h=a.multiply(h,E)}s[l]=a.multiply(e.evaluateAt(d),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],d))}return s}}var wt;(function(b){b[b.UPPER=0]="UPPER",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.DIGIT=3]="DIGIT",b[b.PUNCT=4]="PUNCT",b[b.BINARY=5]="BINARY"})(wt||(wt={}));class Je{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=Je.convertBoolArrayToByteArray(s),l=Je.getEncodedData(s),d=new Ne(a,l,null,null);return d.setNumBits(s.length),d}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,i=wt.UPPER,s=wt.UPPER,a="",l=0;for(;l<n;)if(s===wt.BINARY){if(n-l<5)break;let d=Je.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=Je.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const m=Je.readCode(e,l,8);a+=fe.castAsNonUtf8Char(m),l+=8}s=i}else{let d=s===wt.DIGIT?4:5;if(n-l<d)break;let h=Je.readCode(e,l,d);l+=d;let m=Je.getCharacter(s,h);m.startsWith("CTRL_")?(i=s,s=Je.getTable(m.charAt(5)),m.charAt(6)==="L"&&(i=s)):(a+=m,s=i)}return a}static getTable(e){switch(e){case"L":return wt.LOWER;case"P":return wt.PUNCT;case"M":return wt.MIXED;case"D":return wt.DIGIT;case"B":return wt.BINARY;case"U":default:return wt.UPPER}}static getCharacter(e,n){switch(e){case wt.UPPER:return Je.UPPER_TABLE[n];case wt.LOWER:return Je.LOWER_TABLE[n];case wt.MIXED:return Je.MIXED_TABLE[n];case wt.PUNCT:return Je.PUNCT_TABLE[n];case wt.DIGIT:return Je.DIGIT_TABLE[n];default:throw new Vt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=Ue.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=Ue.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=Ue.AZTEC_DATA_10):(i=12,n=Ue.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new V;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=Je.readCode(e,l,i);try{new bn(n).decode(d,a-s)}catch(I){throw new V(I)}let h=(1<<i)-1,m=0;for(let I=0;I<s;I++){let R=d[I];if(R===0||R===h)throw new V;(R===1||R===h-1)&&m++}let y=new Array(s*i-m),E=0;for(let I=0;I<s;I++){let R=d[I];if(R===1||R===h-1)y.fill(R>1,E,E+i-1),E+=i-1;else for(let F=i-1;F>=0;--F)y[E++]=(R&1<<F)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),i=this.ddata.getNbLayers(),s=(n?11:14)+i*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(i,n));if(n)for(let d=0;d<a.length;d++)a[d]=d;else{let d=s+1+2*$.truncDivision($.truncDivision(s,2)-1,15),h=s/2,m=$.truncDivision(d,2);for(let y=0;y<h;y++){let E=y+$.truncDivision(y,15);a[h-y-1]=m-E-1,a[h+y]=m+E+1}}for(let d=0,h=0;d<i;d++){let m=(i-d)*4+(n?9:12),y=d*2,E=s-1-y;for(let I=0;I<m;I++){let R=I*2;for(let F=0;F<2;F++)l[h+R+F]=e.get(a[y+F],a[y+I]),l[h+2*m+R+F]=e.get(a[y+I],a[E-F]),l[h+4*m+R+F]=e.get(a[E-F],a[E-I]),l[h+6*m+R+F]=e.get(a[E-I],a[y+F])}h+=m*8}return l}static readCode(e,n,i){let s=0;for(let a=n;a<n+i;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let i=e.length-n;return i>=8?Je.readCode(e,n,8):Je.readCode(e,n,i)<<8-i}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let i=0;i<n.length;i++)n[i]=Je.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Je.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],Je.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],Je.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
|
|
58
|
+
`}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const _o={model:"deepseek-ai/DeepSeek-V3",maxSteps:15,extraTools:{}},qa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function Ax(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const o={...r};for(const[c,u]of Object.entries(t))u&&typeof u=="object"&&!Array.isArray(u)?o[c]={...o[c]||{},...u}:o[c]=u;return o}class Ix extends Hn.BaseModelProvider{transport;agent;promptManager;llmConfig={..._o,...qa};isGenuiEnabled;debugStream=!1;pageToolsOnDemand=!1;_getRouteState=null;setRouteStateGetter(r){this._getRouteState=r}constructor(r,o,c){super(r);let u;c&&"llm"in c?u={..._o,...c}:u={..._o,...qa,...c||{}},this.llmConfig=u;const m={llmConfig:u.llm?{llm:u.llm}:{...u}};this.agent=new Ht.AgentModelProvider(m),this.promptManager=new Ex,this.promptManager.setStatic(o)}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:m,llm:x,providerOptions:_,headers:g}){if(x)this.agent.llm=x,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&o&&u){const C=this.isGenuiEnabled?.value&&c||o;this.llmConfig.model=r,this.llmConfig.apiKey=u,this.llmConfig.baseURL=o,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let A;if(f==="deepseek")A=Cu;else if(f==="openai")A=ku;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:u,baseURL:C,...g?{headers:g}:{}})}this.llmConfig.providerOptions=_,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const o=r[r.length-1];if(o.role==="tool"&&o.content.length>0){const c=o.content[o.content.length-1];c.type==="tool-result"&&c.toolName==="get_skill_content"&&(c.output.value.content="查询到技能内容已添加到系统提示词中。")}}cleanupOldSnapshotsInMessages(r){if(!r||r.length===0)return r;const c=this.agent.useReActMode===!0?"user":"tool",u=r[r.length-1];if(!u||u.role!==c||!this.isSnapshotContent(u.content))return r;const f=[...r];for(let m=f.length-2;m>=0;m--){const x=f[m];x.role===c&&this.isSnapshotContent(x.content)&&this.replaceSnapshotWithPlaceholder(x)}return f}removeSnapshotData(r){if(!r)return r;const o=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of o){const m=r.indexOf(f);if(m!==-1){c=m;break}}if(c!==-1){const f=r.substring(0,c).trim();return f?`${f} 📸 [历史快照已清理]`:"📸 历史快照已清理"}const u=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of u)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const o=r.content[0];if(o?.output?.value?.content){const c=o.output.value.content;Array.isArray(c)&&(o.output.value.content=c.map(u=>u.type==="image"||u.type==="image_url"?null:u.type==="text"&&u.text&&this.isSnapshotContent(u.text)?{type:"text",text:this.removeSnapshotData(u.text)}:u).filter(u=>u!==null)),o.output.value.screenshot&&delete o.output.value.screenshot}else r.content=r.content.filter(c=>c.type!=="image"&&c.type!=="image_url")}else typeof r.content=="string"&&this.isSnapshotContent(r.content)&&(r.content=this.removeSnapshotData(r.content))}isSnapshotContent(r){if(!r)return!1;const o=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return o.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const u=c?.output?.value?.content?.[0]?.text;if(u&&o.some(f=>u.includes(f))||c.type==="text"&&c.text&&o.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,o){let c=r.messages[r.messages.length-1];if(!c)return;const u={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:{"get-today":jm,...this.llmConfig.extraTools||{}},maxSteps:this.llmConfig.maxSteps,providerOptions:Ax(this.llmConfig.providerOptions,vx),prepareStep:({messages:O})=>{this.cleanGetSkillContentToolResult(O);const k=this.cleanupOldSnapshotsInMessages(O),B=["get-today",...Object.keys(this.llmConfig.extraTools||{})],L=new Set;Object.values(this.agent.mcpTools||{}).forEach(z=>{Object.keys(z||{}).forEach($=>L.add($)),B.push(...Object.keys(z||{}))});const K=Array.from(new Set(B)).filter(z=>{if(this.agent.ignoreToolnames.includes(z))return!1;if(!this.pageToolsOnDemand)return!0;const $=this._getRouteState?.()??Gm(),W=$?.toolRouteMap??Ht.getToolRouteMap(),X=$?.activeRoutes??Ht.getActiveRoutes(),H=Z=>Z.replace(/\/+$/,"")||"/";if($&&$.initialized===!1)return!L.has(z);const V=W.get(z);if(V){const Z=H(V);return X.has(Z)||X.has(V)}return!0});return{system:this.promptManager.getSystemPrompt(),messages:k,activeTools:K}},onStepFinish:O=>{if(O.finishReason==="tool-calls"&&O.content.length>0){const k=O.content[O.content.length-1];if(k.toolName==="get_skill_content"&&k.type==="tool-result"){const B=k.output.content;this.promptManager.appendTemp(B)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp("")}},f={role:"user",content:c.content},x=[...(O=>O.map(k=>({role:k.role,content:k.content})))(this.agent.responseMessages),f];u.messages=x;const _=await this.agent.chatStream(u),g=new ep,A=await new Cx({debug:this.debugStream,onFinish:()=>{v.nextTick(()=>{g.resolve(),o.onDone()})}}).traverse(_),P={role:"assistant",content:"",uiContent:[]};return v.watch(A,O=>{if(!O)o.onData(P);else{const B=O.steps.map(L=>L.contents).flat().map(L=>{if(L.type==="text")return bx(L.text);if(L.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:L.text,thinkId:L.id};if(L.type==="tool")return{type:"tool",id:L.id,name:L.toolName,content:JSON.stringify({input:L.inputStr,output:L.output}),status:L.error?"failed":L.running?"running":"success"}});if(O?.error){const L={type:"markdown",content:`**错误**:${O.error.responseBody||O.error.message||"未知错误"}`};B.push(L)}(O.steps.length>=1||O?.error)&&o.onData({...P,uiContent:B.flat(),usage:O.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const Sx=({systemPrompt:t,llmConfig:r})=>{const o=new Ix({provider:"custom"},t,r),c=new Hn.AIClient({providerImplementation:o,provider:"custom"}),{messageManager:u,createConversation:f,getCurrentConversation:m,switchConversation:x,deleteConversation:_,updateTitle:g,state:C}=Hn.useConversation({client:c,autoSave:!1,events:{onLoaded(){},onReceiveData(W,X,H){H(),X.value[X.value.length-1].role==="assistant"&&X.value.pop(),X.value.push(W)}}}),{messageState:A,inputMessage:P,sendMessage:O,abortRequest:k,messages:B,addMessage:L,send:K}=u,z=v.ref(),$=async(W,X,H)=>{if(H){const{shouldBlock:Z}=await H(W);if(Z)return!1}P.value=W;const V=m();if(V&&V.title==="新会话"&&g(V.id,P.value.slice(0,15)),X&&X.length>0){const Z=[{type:"text",text:P.value},...X],M=[];P.value&&M.push({type:"text",content:P.value});for(const ce of X)ce.type==="image"&&ce.image&&M.push({type:"image",content:ce.image});const we={role:"user",content:Z,uiContent:M};B.value.push(we),P.value="",K()}else{const Z={role:"user",content:P.value,uiContent:[{type:"text",content:P.value}]};B.value.push(Z),P.value="",K()}return!0};return v.onMounted(()=>{z.value?.focus()}),v.onUnmounted(()=>{o.agent.closeAll()}),{agent:o.agent,customAgentProvider:o,client:c,messageManager:u,addMessage:L,send:K,conversationState:C,messages:B,messageState:A,inputMessage:P,sendMessage:O,abortRequest:k,senderRef:z,handleSendMessage:$,createConversation:f,switchConversation:x,deleteConversation:_,getCurrentConversation:m}};function Tx(){}const kn=Object.assign,rs=typeof window<"u",ji=t=>t!==null&&typeof t=="object",Jn=t=>t!=null,Lo=t=>typeof t=="function",Nx=t=>ji(t)&&Lo(t.then)&&Lo(t.catch),Mu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),Ox=()=>rs?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const o=r.split(".");let c=t;return o.forEach(u=>{var f;c=ji(c)&&(f=c[u])!=null?f:""}),c}function Rx(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const Bi=null,an=[Number,String],lr={type:Boolean,default:!0},kx=t=>({type:Number,default:t}),ln=t=>({type:String,default:t});var is=typeof window<"u";function Du(t){let r;v.onMounted(()=>{t(),v.nextTick(()=>{r=!0})}),v.onActivated(()=>{r&&t()})}function Pu(t,r,o={}){if(!is)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let m=!1,x;const _=A=>{if(m)return;const P=v.unref(A);P&&!x&&(P.addEventListener(t,r,{capture:f,passive:u}),x=!0)},g=A=>{if(m)return;const P=v.unref(A);P&&x&&(P.removeEventListener(t,r,f),x=!1)};v.onUnmounted(()=>g(c)),v.onDeactivated(()=>g(c)),Du(()=>_(c));let C;return v.isRef(c)&&(C=v.watch(c,(A,P)=>{g(P),_(A)})),()=>{C?.(),g(c),m=!0}}var Ai,vo;function Mx(){if(!Ai&&(Ai=v.ref(0),vo=v.ref(0),is)){const t=()=>{Ai.value=window.innerWidth,vo.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Ai,height:vo}}var Dx=/scroll|auto|overlay/i,Px=is?window:void 0;function Bx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Lx(t,r=Px){let o=t;for(;o&&o!==r&&Bx(o);){const{overflowY:c}=window.getComputedStyle(o);if(Dx.test(c))return o;o=o.parentNode}return r}Ox();const Fx=t=>t.stopPropagation();function Bu(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Fx(t)}Mx();function _n(t){if(Jn(t))return Mu(t)?`${t}px`:String(t)}function Ux(t){if(Jn(t)){if(Array.isArray(t))return{width:_n(t[0]),height:_n(t[1])};const r=_n(t);return{width:r,height:r}}}function zx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const $x=/-(\w)/g,Lu=t=>t.replace($x,(r,o)=>o.toUpperCase()),Vx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Zx}=Object.prototype;function jx(t,r,o){const c=r[o];Jn(c)&&(!Zx.call(t,o)||!ji(c)?t[o]=c:t[o]=Fu(Object(t[o]),c))}function Fu(t,r){return Object.keys(r).forEach(o=>{jx(t,r,o)}),t}var Wx={name:"姓名",tel:"电话",save:"保存",clear:"清空",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ja=v.ref("zh-CN"),Ka=v.reactive({"zh-CN":Wx}),Hx={messages(){return Ka[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Fu(Ka,t)}};var Gx=Hx;function Xx(t){const r=Lu(t)+".";return(o,...c)=>{const u=Gx.messages(),f=Ya(u,r+o)||Ya(u,o);return Lo(f)?f(...c):f}}function Fo(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((o,c)=>o+Fo(t,c),""):Object.keys(r).reduce((o,c)=>o+(r[c]?Fo(t,c):""),""):""}function qx(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Fo(r,o)}`)}function hr(t){const r=`van-${t}`;return[r,qx(r),Xx(r)]}const Yx="van-haptics-feedback",Qa=5;function Jx(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);Nx(f)?f.then(m=>{m?o():c&&c()}).catch(u||Tx):f?o():c&&c()}else o()}function si(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(Lu(`-${o}`),t))},t}const Kx=Symbol();function Uu(t){const r=v.getCurrentInstance();r&&kn(r.proxy,t)}const[Qx,el]=hr("badge"),ey={dot:Boolean,max:an,tag:ln("div"),color:String,offset:Array,content:an,showZero:lr,position:ln("top-right")};var ty=v.defineComponent({name:Qx,props:ey,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:x,showZero:_}=t;return Jn(x)&&x!==""&&(_||x!==0&&x!=="0")},c=()=>{const{dot:x,max:_,content:g}=t;if(!x&&o())return r.content?r.content():Jn(_)&&Mu(g)&&+g>+_?`${_}+`:g},u=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=v.computed(()=>{const x={background:t.color};if(t.offset){const[_,g]=t.offset,{position:C}=t,[A,P]=C.split("-");r.default?(typeof g=="number"?x[A]=_n(A==="top"?g:-g):x[A]=A==="top"?_n(g):u(g),typeof _=="number"?x[P]=_n(P==="left"?_:-_):x[P]=P==="left"?_n(_):u(_)):(x.marginTop=_n(g),x.marginLeft=_n(_))}return x}),m=()=>{if(o()||t.dot)return v.createVNode("div",{class:el([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return v.createVNode(x,{class:el("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const ny=si(ty);let zu=2e3;const ry=()=>++zu,iy=t=>{zu=t},[$u,oy]=hr("config-provider"),Vu=Symbol($u),sy={tag:ln("div"),theme:ln("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:ln("local"),iconPrefix:String};function ay(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function ly(t){const r={};return Object.keys(t).forEach(o=>{const c=ay(Vx(o));r[`--van-${c}`]=t[o]}),r}function Ii(t={},r={}){Object.keys(t).forEach(o=>{t[o]!==r[o]&&document.documentElement.style.setProperty(o,t[o])}),Object.keys(r).forEach(o=>{t[o]||document.documentElement.style.removeProperty(o)})}v.defineComponent({name:$u,props:sy,setup(t,{slots:r}){const o=v.computed(()=>ly(kn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(rs){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},u=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};v.watch(()=>t.theme,(f,m)=>{m&&u(m),c()},{immediate:!0}),v.onActivated(c),v.onDeactivated(u),v.onBeforeUnmount(u),v.watch(o,(f,m)=>{t.themeVarsScope==="global"&&Ii(f,m)}),v.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Ii({},o.value),f==="global"&&Ii(o.value,{})}),t.themeVarsScope==="global"&&Ii(o.value,{})}return v.provide(Vu,t),v.watchEffect(()=>{t.zIndex!==void 0&&iy(t.zIndex)}),()=>v.createVNode(t.tag,{class:oy(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[cy,tl]=hr("icon"),uy=t=>t?.includes("/"),dy={dot:Boolean,tag:ln("i"),name:String,size:an,badge:an,color:String,badgeProps:Object,classPrefix:String};var fy=v.defineComponent({name:cy,props:dy,setup(t,{slots:r}){const o=v.inject(Vu,null),c=v.computed(()=>t.classPrefix||o?.iconPrefix||tl());return()=>{const{tag:u,dot:f,name:m,size:x,badge:_,color:g}=t,C=uy(m);return v.createVNode(ny,v.mergeProps({dot:f,tag:u,class:[c.value,C?"":`${c.value}-${m}`],style:{color:g,fontSize:_n(x)},content:_},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),C&&v.createVNode("img",{class:tl("image"),src:m},null)]}})}}});const os=si(fy),[hy,qr]=hr("loading"),py=Array(12).fill(null).map((t,r)=>v.createVNode("i",{class:qr("line",String(r+1))},null)),my=v.createVNode("svg",{class:qr("circular"),viewBox:"25 25 50 50"},[v.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),gy={size:an,type:ln("circular"),color:String,vertical:Boolean,textSize:an,textColor:String};var xy=v.defineComponent({name:hy,props:gy,setup(t,{slots:r}){const o=v.computed(()=>kn({color:t.color},Ux(t.size))),c=()=>{const f=t.type==="spinner"?py:my;return v.createVNode("span",{class:qr("spinner",t.type),style:o.value},[r.icon?r.icon():f])},u=()=>{var f;if(r.default)return v.createVNode("span",{class:qr("text"),style:{fontSize:_n(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return v.createVNode("div",{class:qr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),u()])}}});const yy=si(xy),wy={show:Boolean,zIndex:an,overlay:lr,duration:an,teleport:[String,Object],lockScroll:lr,lazyRender:lr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Bi,transitionAppear:Boolean,closeOnClickOverlay:lr};function _y(t,r){return t>r?"horizontal":r>t?"vertical":""}function vy(){const t=v.ref(0),r=v.ref(0),o=v.ref(0),c=v.ref(0),u=v.ref(0),f=v.ref(0),m=v.ref(""),x=v.ref(!0),_=()=>m.value==="vertical",g=()=>m.value==="horizontal",C=()=>{o.value=0,c.value=0,u.value=0,f.value=0,m.value="",x.value=!0};return{move:(O=>{const k=O.touches[0];o.value=(k.clientX<0?0:k.clientX)-t.value,c.value=k.clientY-r.value,u.value=Math.abs(o.value),f.value=Math.abs(c.value);const B=10;(!m.value||u.value<B&&f.value<B)&&(m.value=_y(u.value,f.value)),x.value&&(u.value>Qa||f.value>Qa)&&(x.value=!1)}),start:(O=>{C(),t.value=O.touches[0].clientX,r.value=O.touches[0].clientY}),reset:C,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:m,isVertical:_,isHorizontal:g,isTap:x}}let $r=0;const nl="van-overflow-hidden";function Cy(t,r){const o=vy(),c="01",u="10",f=C=>{o.move(C);const A=o.deltaY.value>0?u:c,P=Lx(C.target,t.value),{scrollHeight:O,offsetHeight:k,scrollTop:B}=P;let L="11";B===0?L=k>=O?"00":"01":B+k>=O&&(L="10"),L!=="11"&&o.isVertical()&&!(parseInt(L,2)&parseInt(A,2))&&Bu(C)},m=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),$r||document.body.classList.add(nl),$r++},x=()=>{$r&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),$r--,$r||document.body.classList.remove(nl))},_=()=>r()&&m(),g=()=>r()&&x();Du(_),v.onDeactivated(g),v.onBeforeUnmount(g),v.watch(r,C=>{C?m():x()})}function Zu(t){const r=v.ref(!1);return v.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const rl=()=>{var t;const{scopeId:r}=((t=v.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[by,Ey]=hr("overlay"),Ay={show:Boolean,zIndex:an,duration:an,className:Bi,lockScroll:lr,lazyRender:lr,customStyle:Object,teleport:[String,Object]};var Iy=v.defineComponent({name:by,inheritAttrs:!1,props:Ay,setup(t,{attrs:r,slots:o}){const c=v.ref(),u=Zu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Bu(x)},m=u(()=>{var x;const _=kn(zx(t.zIndex),t.customStyle);return Jn(t.duration)&&(_.animationDuration=`${t.duration}s`),v.withDirectives(v.createVNode("div",v.mergeProps({ref:c,style:_,class:[Ey(),t.className]},r),[(x=o.default)==null?void 0:x.call(o)]),[[v.vShow,t.show]])});return Pu("touchmove",f,{target:c}),()=>{const x=v.createVNode(v.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?v.createVNode(v.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const Sy=si(Iy),Ty=kn({},wy,{round:Boolean,position:ln("center"),closeIcon:ln("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:ln("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[Ny,il]=hr("popup");var Oy=v.defineComponent({name:Ny,inheritAttrs:!1,props:Ty,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:o,slots:c}){let u,f;const m=v.ref(),x=v.ref(),_=Zu(()=>t.show||!t.lazyRender),g=v.computed(()=>{const H={zIndex:m.value};if(Jn(t.duration)){const V=t.position==="center"?"animationDuration":"transitionDuration";H[V]=`${t.duration}s`}return H}),C=()=>{u||(u=!0,m.value=t.zIndex!==void 0?+t.zIndex:ry(),r("open"))},A=()=>{u&&Jx(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},P=H=>{r("clickOverlay",H),t.closeOnClickOverlay&&A()},O=()=>{if(t.overlay){const H=kn({show:t.show,class:t.overlayClass,zIndex:m.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return v.createVNode(Sy,v.mergeProps(H,rl(),{onClick:P}),{default:c["overlay-content"]})}},k=H=>{r("clickCloseIcon",H),A()},B=()=>{if(t.closeable)return v.createVNode(os,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),Yx],classPrefix:t.iconPrefix,onClick:k},null)};let L;const K=()=>{L&&clearTimeout(L),L=setTimeout(()=>{r("opened")})},z=()=>r("closed"),$=H=>r("keydown",H),W=_(()=>{var H;const{destroyOnClose:V,round:Z,position:M,safeAreaInsetTop:we,safeAreaInsetBottom:ce,show:fe}=t;if(!(!fe&&V))return v.withDirectives(v.createVNode("div",v.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:Z,[M]:M}),{"van-safe-area-top":we,"van-safe-area-bottom":ce}],onKeydown:$},o,rl()),[(H=c.default)==null?void 0:H.call(c),B()]),[[v.vShow,fe]])}),X=()=>{const{position:H,transition:V,transitionAppear:Z}=t,M=H==="center"?"van-fade":`van-popup-slide-${H}`;return v.createVNode(v.Transition,{name:V||M,appear:Z,onAfterEnter:K,onAfterLeave:z},{default:W})};return v.watch(()=>t.show,H=>{H&&!u&&(C(),o.tabindex===0&&v.nextTick(()=>{var V;(V=x.value)==null||V.focus()})),!H&&u&&(u=!1,r("close"))}),Uu({popupRef:x}),Cy(x,()=>t.show&&t.lockScroll),Pu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),v.onMounted(()=>{t.show&&C()}),v.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),v.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),v.provide(Kx,()=>t.show),()=>t.teleport?v.createVNode(v.Teleport,{to:t.teleport},{default:()=>[O(),X()]}):v.createVNode(v.Fragment,null,[O(),X()])}});const Ry=si(Oy);let Vr=0;function ky(t){t?(Vr||document.body.classList.add("van-toast--unclickable"),Vr++):Vr&&(Vr--,Vr||document.body.classList.remove("van-toast--unclickable"))}const[My,Er]=hr("toast"),Dy=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Py={icon:String,show:Boolean,type:ln("text"),overlay:Boolean,message:an,iconSize:an,duration:kx(2e3),position:ln("middle"),teleport:[String,Object],wordBreak:String,className:Bi,iconPrefix:String,transition:ln("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Bi,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:an};var By=v.defineComponent({name:My,props:Py,emits:["update:show"],setup(t,{emit:r,slots:o}){let c,u=!1;const f=()=>{const A=t.show&&t.forbidClick;u!==A&&(u=A,ky(u))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},_=()=>clearTimeout(c),g=()=>{const{icon:A,type:P,iconSize:O,iconPrefix:k,loadingType:B}=t;if(A||P==="success"||P==="fail")return v.createVNode(os,{name:A||P,size:O,class:Er("icon"),classPrefix:k},null);if(P==="loading")return v.createVNode(yy,{class:Er("loading"),size:O,type:B},null)},C=()=>{const{type:A,message:P}=t;if(o.message)return v.createVNode("div",{class:Er("text")},[o.message()]);if(Jn(P)&&P!=="")return A==="html"?v.createVNode("div",{key:0,class:Er("text"),innerHTML:String(P)},null):v.createVNode("div",{class:Er("text")},[P])};return v.watch(()=>[t.show,t.forbidClick],f),v.watch(()=>[t.show,t.type,t.message,t.duration],()=>{_(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),v.onMounted(f),v.onUnmounted(f),()=>v.createVNode(Ry,v.mergeProps({class:[Er([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:_,"onUpdate:show":m},Rx(t,Dy)),{default:()=>[g(),C()]})}});function Ly(){const t=v.reactive({show:!1}),r=u=>{t.show=u},o=u=>{kn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Uu({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function Fy(t){const r=v.createApp(t),o=document.createElement("div");return document.body.appendChild(o),{instance:r.mount(o),unmount(){r.unmount(),document.body.removeChild(o)}}}const Uy={icon:"",type:"text",message:"",className:"",overlay:!1,onClose:void 0,onOpened:void 0,duration:2e3,teleport:"body",iconSize:void 0,iconPrefix:void 0,position:"middle",transition:"van-fade",forbidClick:!1,loadingType:void 0,overlayClass:"",overlayStyle:void 0,closeOnClick:!1,closeOnClickOverlay:!1};let Si=[],zy=!1,ol=kn({},Uy);const $y=new Map;function ju(t){return ji(t)?t:{message:t}}function Vy(){const{instance:t}=Fy({setup(){const r=v.ref(""),{open:o,state:c,close:u,toggle:f}=Ly(),m=()=>{},x=()=>{const _={onClosed:m,"onUpdate:show":f};return v.createVNode(By,v.mergeProps(c,_),null)};return v.watch(r,_=>{c.message=_}),v.getCurrentInstance().render=x,{open:o,close:u,message:r}}});return t}function Zy(){if(!Si.length||zy){const t=Vy();Si.push(t)}return Si[Si.length-1]}function et(t={}){if(!rs)return{};const r=Zy(),o=ju(t);return r.open(kn({},ol,$y.get(o.type||ol.type),o)),r}const jy=t=>r=>et(kn({type:t},ju(r))),Wu=jy("loading"),Wy=t=>{try{const r=JSON.parse(t),o=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,u]of Object.entries(r.mcpServers)){const f=Hy(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Hy=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:o,sessionId:c}=t;return r==="extension"?c?{type:"extension",url:o,sessionId:c,useAISdkClient:!0}:null:r==="streamableHttp"||r==="sse"?{type:r,url:o,useAISdkClient:!0}:{type:"streamableHttp",url:o,useAISdkClient:!0}},Gy=(t,r,o)=>{const c=async(f,m,x,_,g)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const O={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||o,description:_||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(k=>({id:k,name:k,description:A[k].description,enabled:!0})),originMcpConfig:v.markRaw(m)};return r.value.push(O),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{Wu("添加工具中...");try{if(f==="code"){if(typeof m!="string"){et("添加工具失败:code 类型需要 JSON 字符串格式");return}const K=Wy(m);if(K.length===0){et("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let z=0,$=0;for(const{name:W,config:X}of K){const H=`mcp-server-${W}`;await c(H,X,W)?z++:$++}await t.closeAll(),$===0?et(`成功添加 ${z} 个工具`):z>0?et(`成功添加 ${z} 个工具,${$} 个失败`):et("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){et("添加工具失败:数据格式不正确");return}const{description:x,headers:_,name:g,thumbnail:C,type:A,url:P}=m;if(!g||!P||!A){et("添加工具失败:缺少必要参数(名称、URL或类型)");return}const k=`mcp-server-${`custom-${g}-${Date.now()}`}`;await c(k,{type:A,url:P,useAISdkClient:!0},g,x,C)?(await t.closeAll(),et("添加工具完成")):et("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),et(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Xy(t,r,o){const c=v.ref([]),u=v.ref([]),f=v.ref(!1),m=W=>W==="mcp-server-localhost",x=(W,X)=>{X?t.ignoreToolnames=t.ignoreToolnames.filter(H=>H!==W):t.ignoreToolnames.includes(W)||t.ignoreToolnames.push(W)},_=(W,X)=>{r.value||(r.value={});const H={...r.value};W===null?Object.keys(H).forEach(V=>{H[V]=X}):H[W]=X,r.value=H},g=W=>{const X=u.value.find(H=>H.id===W);X&&(X.addState="idle")},C=W=>{const X=t.mcpTools[W];if(!X)return[];const H=m(W),V=r.value||{};return Object.keys(X).map(Z=>{const M=H?!!V[Z]:!0;return x(Z,M),{id:Z,name:Z,description:X[Z].description,enabled:M}})},A=async W=>{const X=W.pluginId;if(!await t.insertMcpServer(X,W.mcpServer))return!1;if(!t.mcpTools[X])return await t.removeMcpServer(X),!1;const Z=C(X);if(Z.length===0)return await t.removeMcpServer(X),!1;const M=c.value.find(ce=>ce.id===W.pluginId);if(M)return M.tools=Z,M.originMcpConfig=v.markRaw(W.mcpServer),!0;const we={id:W.pluginId,name:W.name,icon:W.icon||o,description:W.description,enabled:!0,expanded:!1,tools:Z,originMcpConfig:v.markRaw(W.mcpServer)};return c.value.push(we),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async(W,X)=>{let H,V;if("type"in X&&X.type==="local")H="本地工具",V="本地工具列表";else{const Z=new URL(X.url);H=Z.origin,V=Z.searchParams.get("sessionId")||("sessionId"in X?X.sessionId:"")||""}await A({pluginId:W,name:H,description:V,mcpServer:X})},togglePlugin:(W,X)=>{const H=m(W.id);W.tools.forEach(V=>{V.enabled=X,x(V.id,X),H&&_(V.id,X)})},toggleTool:(W,X,H)=>{const V=m(W.id);W.tools.forEach(Z=>{Z.id===X&&(Z.enabled=H)}),x(X,H),V&&_(X,H)},deletePlugin:async W=>{const X=c.value.find(V=>V.id===W.id);if(!X)return;c.value=c.value.filter(V=>V.id!==X.id),g(X.id);const H=W.id;await t.removeMcpServer(H)},addPluginCore:A,addPluginFromMarket:async W=>{W.addState="loading";const X={type:W.type,url:W.url,useAISdkClient:!0},H=await A({pluginId:W.id,name:W.name,description:W.description||"",icon:W.icon,mcpServer:X});W.addState=H?"added":"idle"},addPluginFromScan:async(W,X)=>{const H={type:"streamableHttp",url:`${X}mcp?sessionId=${W}`},V=new URL(`${X}mcp?sessionId=${W}`);return await A({pluginId:`plugin-${W}`,name:V.origin,description:W,mcpServer:H})},handleClientDisconnected:async W=>{const X=W,H=c.value.find(V=>V.id===X);return await t.removeMcpServer(W),H?(c.value=c.value.filter(V=>V.id!==X),g(X),H):null},searchPlugin:(W,X)=>W.trim()===""||X.name.toLowerCase().includes(W.toLowerCase())}}function qy(t){const{skillsRef:r,customAgentProvider:o}=t,c=v.computed(()=>{const x=r?.value;return x?Ht.getSkillOverviews(x):[]}),u=v.computed(()=>{const x=c.value;return x.length>0?Ht.formatSkillsForSystemPrompt(x):""}),f=v.computed(()=>{const x=r?.value;return x?Ht.createSkillTools(x):{}});return v.watchEffect(()=>{if(o.promptManager.setSkillMeta(u.value),o.llmConfig){const x=o.llmConfig.extraTools??{};o.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:u,skillTools:f,skillOverviews:c}}const Yy=["title"],Jy=v.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,o=v.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=v.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:_,outputTokenDetails:g}=r.usage,C=_?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[C/x*100+"%",C],inputTokens:[(f-C)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(m-A)/x*100+"%",m]}}),u=v.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:_,outputTokenDetails:g}=r.usage,C=_?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${x}`,`cachedInputTokens: ${C}`,`reasoningTokens: ${A}`].join(`
|
|
59
|
+
`)});return(f,m)=>o.value?v.createCommentVNode("",!0):(v.openBlock(),v.createElementBlock("div",{key:0,class:"token-usage-wrap",title:u.value},[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(c.value,(x,_)=>(v.openBlock(),v.createElementBlock("div",{key:_,class:v.normalizeClass(_),style:v.normalizeStyle({width:x[0]})},null,6))),128))],8,Yy))}}),Kn=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},Ky=Kn(Jy,[["__scopeId","data-v-000098b4"]]),Qy={width:"100.000000",height:"100.000000",viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"};function ew(t,r){return v.openBlock(),v.createElementBlock("svg",Qy,[...r[0]||(r[0]=[v.createStaticVNode('<desc> Created with Pixso. </desc><defs><radialGradient gradientTransform="translate(32.4474 65.1156) rotate(128.932) scale(22.991 20.6919)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3090_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient><linearGradient x1="30.999874" y1="85.000229" x2="30.499891" y2="70.500214" id="paint_linear_9_3092_0" gradientUnits="userSpaceOnUse"><stop stop-color="#000000" stop-opacity="0.000000"></stop><stop offset="1.000000" stop-color="#000000"></stop></linearGradient><radialGradient gradientTransform="translate(26.9999 24.7118) rotate(38.3655) scale(77.7996 109.496)" cx="0.000000" cy="0.000000" r="1.000000" id="paint_radial_9_3094_0" gradientUnits="userSpaceOnUse"><stop stop-color="#5ADDF8"></stop><stop stop-color="#AEBFFF"></stop><stop offset="0.329153" stop-color="#1476FF"></stop><stop offset="0.667785" stop-color="#655AF8"></stop><stop offset="0.868255" stop-color="#948CFF"></stop><stop offset="1.000000" stop-color="#D25AF8"></stop><stop offset="1.000000" stop-color="#5A8BF8"></stop></radialGradient></defs><rect id="NEXT-LOGO-无背景渐变-右" width="100.000000" height="99.999939" transform="matrix(-1 0 0 1 100 0)" fill="#FFFFFF" fill-opacity="0"></rect>',3),v.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[v.createElementVNode("rect",{id:"画板 1773",width:"99.999962",height:"99.999947",transform:"matrix(-1 0 0 1 100 6.10352e-05)",fill:"#000000","fill-opacity":"1.000000"})],-1),v.createStaticVNode('<g mask="url(#mask9_3088)"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_radial_9_3090_0)" fill-opacity="1.000000" fill-rule="evenodd"></path><g opacity="0.100000" style="mix-blend-mode:normal;"><path id="矢量 1" d="M35.93 81.01L36 63L18 63.07L32.48 82.23C33.61 83.71 35.93 82.9 35.93 81.01Z" fill="url(#paint_linear_9_3092_0)" fill-opacity="1.000000" fill-rule="evenodd"></path></g><rect id="矩形 5" x="12.000000" y="19.000183" rx="26.999992" width="75.999977" height="53.999985" fill="url(#paint_radial_9_3094_0)" fill-opacity="1.000000"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" fill="#000000" fill-opacity="0"></rect><rect id="矩形 5" rx="26.499992" width="74.999977" height="52.999985" transform="matrix(-1 0 0 1 87.5 19.5002)" stroke="#000000" stroke-opacity="0" stroke-width="1.000000"></rect><path id="path" d="M45.39 59.06C44.22 60.05 42.9 60.66 41.43 60.89C39.95 61.12 38.57 61.04 37.28 60.65C36 60.26 34.04 58.58 34.04 58.58C34.04 58.58 29.02 54.73 29.02 45.61C29.02 36.5 33.5 32.5 33.5 32.5C33.5 32.5 34.72 31.31 36.5 31C38.29 30.68 39.43 30.98 40.66 31.33C50.89 34.23 62.38 34.33 72.58 31.33C73.81 30.98 74.91 30.93 75.89 31.17C76.87 31.42 77.71 31.89 78.42 32.59C81.65 35.81 82.87 41.06 83 45.61C83.12 50.09 81.97 55.24 78.94 58.54C78.04 59.52 76.98 60.22 75.78 60.63C74.58 61.04 73.32 61.12 71.99 60.89C70.66 60.66 69.48 60.05 68.46 59.06C68.01 58.62 67.39 58.07 66.57 57.4C65.76 56.73 64.83 56.08 63.79 55.44C62.75 54.8 61.62 54.25 60.39 53.8C59.16 53.35 57.91 53.13 56.62 53.13C55.36 53.13 54.16 53.36 53 53.83C51.85 54.29 50.79 54.84 49.82 55.48C48.86 56.12 48 56.78 47.26 57.45C46.51 58.11 45.89 58.65 45.39 59.06Z" fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero"></path><rect id="矩形 841" rx="2.000000" width="3.999999" height="11.999996" transform="matrix(-0.999983 0.00577157 0.00577157 0.999983 76.1109 38.0356)" fill="#1476FF" fill-opacity="1.000000"></rect><path id="合并" d="M42.96 38C43.77 37.97 44.55 38.42 44.92 39.19L48.73 47.11C49.22 48.13 48.79 49.34 47.75 49.81C46.72 50.28 45.48 49.83 44.99 48.8L42.96 44.59L40.94 48.81C40.45 49.83 39.21 50.28 38.18 49.81C37.14 49.34 36.7 48.13 37.2 47.11L41 39.19C41.37 38.42 42.16 37.98 42.96 38Z" fill="#1476FF" fill-opacity="1.000000" fill-rule="evenodd"></path></g>',1)])])}const Hu={render:ew};function tw(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=v.h(Hu,{style:{width:"48px",height:"48px"}}),m=v.ref({}),x=v.computed(()=>Hn.GeneratingStatus.includes(o.status)),_=v.computed(()=>r.value.findLastIndex(O=>O.role==="assistant")),g=O=>O===void 0?"复制":m.value[O]?"复制成功":"复制",C=async O=>{const k=r.value[O],B=typeof k.content=="string"?k.content:JSON.stringify(k.content);try{await navigator.clipboard.writeText(B),O!==void 0&&(m.value[O]=!0,setTimeout(()=>{m.value[O]=!1},3e3))}catch(L){console.error("复制失败:",L),et("复制失败,请重试")}},A=async O=>{const k=r.value.findLastIndex((L,K)=>L.role==="user"&&K<=O);if(k===-1){console.warn("未找到可重新生成的用户消息"),et("无法重新生成消息");return}const B=r.value[k];if(r.value=r.value.slice(0,k),Array.isArray(B.content)){const K=B.content.find($=>$.type==="text")?.text||"",z=B.content.filter($=>$.type!=="text");c.value=K,await u(K,z.length>0?z:void 0)}else c.value=B.content,await u(B.content)},P={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:O})=>{const k=_.value===O;return x.value&&k?"":v.h("div",{class:["assistant-actions",{"latest-assistant":k,"historical-assistant":!k}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[v.h(Pt.IconButton,{icon:Sr.IconRefresh,size:24,onClick:()=>A(O)}),v.h(Td,{effect:"light",content:g(O),placement:"right",visibleArrow:!1},()=>v.h(Pt.IconButton,{icon:Sr.IconCopy,size:24,onClick:()=>C(O)})),r.value[O].usage?v.h(Ky,{usage:r.value[O].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:P,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:_,copyTooltipContent:g,copyMessageToClipboard:C,regenerateMessage:A}}function nw(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:m,customAgentProvider:x}=t,_=v.ref(!1),g=()=>{v.nextTick(()=>{const k=document.querySelector("div.tr-bubble-list");k&&k.scrollTo({top:k.scrollHeight,behavior:"smooth"})})};return{showHistory:_,handleCreateConversation:()=>{f();const k=[];x.agent.responseMessages=k,r();const B=u();B.aiSdkMessages=k},handleHistorySelect:k=>{f(),o(k.id);const B=u();x.agent.responseMessages=B.aiSdkMessages,_.value=!1,g()},handleHistoryUpdateTitle:(k,B)=>{B.title=k},handleHistoryDelete:(k,B)=>{if(k.id==="delete"){if(m.currentId===B.id){et("不允许删除当前会话");return}c(B.id)}},scrollToBottom:g}}function rw(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:m,AILogoUrl:x,show:_,addPluginFromScan:g,inputMessage:C}=t;let A=null,P=!1;const O=async z=>{if(Wu("添加工具中..."),z){const $=await g(z,o);et($?"添加工具完成":"重复添加工具或添加失败")}else et("添加工具失败")},k=async z=>{if(/^\/[A-Za-z0-9-]{6,}$/.test(z)){try{const $=await fetch(`${o}client?sessionId=${z.slice(1)}`);if(!$.ok)throw new Error(`HTTP ${$.status}`);const X=(await $.json())?.data?.sessionId;X?await O(X):et("添加工具失败,请检查识别码是否正确"),C.value=""}catch($){console.error("识别码处理失败:",$),et("添加工具失败,请检查识别码是否正确"),C.value=""}return!0}return!1},B=()=>{v.watch(r,z=>{if(c!=="remoter")return;const $=!!z;A?!P&&$&&(A.destroy(),A=Ht.createRemoter({sessionId:z,qrCodeUrl:u,remoteUrl:f,menuItems:m,logoUrl:x,onShowAIChat:()=>_.value=!0}),P=!0):(A=Ht.createRemoter({sessionId:z||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:m,logoUrl:x,onShowAIChat:()=>_.value=!0}),P=$),A&&_.value&&A.hide()},{immediate:!0}),v.watch(_,z=>{A&&(z?A.hide():A.show())},{immediate:!0})},L=()=>{v.watch(r,z=>{z&&O(z)})};return{handleScanSuccess:O,handleSessionIdInput:k,initialize:()=>{r.value&&O(r.value),c==="remoter"&&B(),L()},initializeRemoter:B,watchSessionIdChanges:L}}function iw(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function ow(t){return t.type.startsWith("image/")}function sw(t,r){const o=r*1024*1024;return t.size<=o}async function aw(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await iw(o.rawFile);ow(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),et({type:"fail",message:"文件处理失败"})}return r}function lw(t={}){const r=v.ref([]),o=async u=>{if(!u||u.length===0)return;c();const f=v.unref(t.maxFileSize)||10,m=v.unref(t.supportedTypes)||["image/"];for(const x of u){if(!m.some(g=>x.type.startsWith(g))){et({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!sw(x,f)){et({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(u=>{u.url&&URL.revokeObjectURL(u.url)}),r.value=[]};return{attachments:r,handleFilesSelected:o,clearAttachments:c}}function cw(t){const{selectedModel:r,selectedModelId:o}=t,c=v.computed(()=>r.value?.multimodal?.supportImages??!1),u=v.computed(()=>r.value?.multimodal?.maxFileSize||10),f=v.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:x,clearAttachments:_}=lw({maxFileSize:u,supportedTypes:f});return v.watch(o,()=>{if(m.value.length>0&&r.value){const O=r.value.multimodal?.maxFileSize||10,k=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(L=>{if(!L.rawFile||!k.some($=>L.rawFile.type.startsWith($)))return!0;const z=O*1024*1024;return L.rawFile.size>z}).length>0&&(_(),et("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:O=>{x(O)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(et("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await aw(m.value),cleanupAttachments:()=>{m.value.length>0&&_()},clearAttachments:_}}var ve;(function(t){t[t.QR_CODE=0]="QR_CODE",t[t.AZTEC=1]="AZTEC",t[t.CODABAR=2]="CODABAR",t[t.CODE_39=3]="CODE_39",t[t.CODE_93=4]="CODE_93",t[t.CODE_128=5]="CODE_128",t[t.DATA_MATRIX=6]="DATA_MATRIX",t[t.MAXICODE=7]="MAXICODE",t[t.ITF=8]="ITF",t[t.EAN_13=9]="EAN_13",t[t.EAN_8=10]="EAN_8",t[t.PDF_417=11]="PDF_417",t[t.RSS_14=12]="RSS_14",t[t.RSS_EXPANDED=13]="RSS_EXPANDED",t[t.UPC_A=14]="UPC_A",t[t.UPC_E=15]="UPC_E",t[t.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ve||(ve={}));var sl=new Map([[ve.QR_CODE,"QR_CODE"],[ve.AZTEC,"AZTEC"],[ve.CODABAR,"CODABAR"],[ve.CODE_39,"CODE_39"],[ve.CODE_93,"CODE_93"],[ve.CODE_128,"CODE_128"],[ve.DATA_MATRIX,"DATA_MATRIX"],[ve.MAXICODE,"MAXICODE"],[ve.ITF,"ITF"],[ve.EAN_13,"EAN_13"],[ve.EAN_8,"EAN_8"],[ve.PDF_417,"PDF_417"],[ve.RSS_14,"RSS_14"],[ve.RSS_EXPANDED,"RSS_EXPANDED"],[ve.UPC_A,"UPC_A"],[ve.UPC_E,"UPC_E"],[ve.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),al;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(al||(al={}));function uw(t){return Object.values(ve).includes(t)}var ti;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(ti||(ti={}));var dw=(function(){function t(){}return t.GITHUB_PROJECT_URL="https://github.com/mebjas/html5-qrcode",t.SCAN_DEFAULT_FPS=2,t.DEFAULT_DISABLE_FLIP=!1,t.DEFAULT_REMEMBER_LAST_CAMERA_USED=!0,t.DEFAULT_SUPPORTED_SCAN_TYPE=[ti.SCAN_TYPE_CAMERA,ti.SCAN_TYPE_FILE],t})(),Gu=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!sl.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,sl.get(r))},t})(),ll=(function(){function t(){}return t.createFromText=function(r){var o={text:r};return{decodedText:r,result:o}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Uo;(function(t){t[t.UNKWOWN_ERROR=0]="UNKWOWN_ERROR",t[t.IMPLEMENTATION_ERROR=1]="IMPLEMENTATION_ERROR",t[t.NO_CODE_FOUND_ERROR=2]="NO_CODE_FOUND_ERROR"})(Uo||(Uo={}));var fw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Uo.UNKWOWN_ERROR}},t})(),hw=(function(){function t(r){this.verbose=r}return t.prototype.log=function(r){this.verbose&&console.log(r)},t.prototype.warn=function(r){this.verbose&&console.warn(r)},t.prototype.logError=function(r,o){(this.verbose||o===!0)&&console.error(r)},t.prototype.logErrors=function(r){if(r.length===0)throw"Logger#logError called without arguments";this.verbose&&console.error(r)},t})();function Mn(t){return typeof t>"u"||t===null}var Ir=(function(){function t(){}return t.codeParseError=function(r){return"QR code parse error, error = ".concat(r)},t.errorGettingUserMedia=function(r){return"Error getting userMedia, error = ".concat(r)},t.onlyDeviceSupportedError=function(){return"The device doesn't support navigator.mediaDevices , only supported cameraIdOrConfig in this case is deviceId parameter (string)."},t.cameraStreamingNotSupported=function(){return"Camera streaming not supported by the browser."},t.unableToQuerySupportedDevices=function(){return"Unable to query supported devices, unknown error."},t.insecureContextCameraQueryError=function(){return"Camera access is only supported in secure context like https or localhost."},t.scannerPaused=function(){return"Scanner paused"},t})(),Xu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,o){if(typeof r!="object"){var c=typeof r;return o.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var u=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(u),m=Object.keys(r),x=0,_=m;x<_.length;x++){var g=_[x];if(f.has(g))return o.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),Hr={exports:{}},pw=Hr.exports,cl;function mw(){return cl||(cl=1,(function(t,r){(function(o,c){c(r)})(pw,(function(o){function c(b){return b==null}var u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var n in e)e.hasOwnProperty(n)&&(b[n]=e[n])};function f(b,e){u(b,e);function n(){this.constructor=b}b.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(b,e){var n=Object.setPrototypeOf;n?n(b,e):b.__proto__=e}function x(b,e){e===void 0&&(e=b.constructor);var n=Error.captureStackTrace;n&&n(b,e)}var _=(function(b){f(e,b);function e(n){var i=this.constructor,s=b.call(this,n)||this;return Object.defineProperty(s,"name",{value:i.name,enumerable:!1}),m(s,i.prototype),x(s),s}return e})(Error);class g extends _{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class C extends g{}C.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class P{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,i,s){const a=this.binarizer.getLuminanceSource().crop(e,n,i,s);return new P(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new P(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new P(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class O extends g{static getChecksumInstance(){return new O}}O.kind="ChecksumException";class k{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class B{static arraycopy(e,n,i,s,a){for(;a--;)i[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class L extends g{}L.kind="IndexOutOfBoundsException";class K extends L{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}K.kind="ArrayIndexOutOfBoundsException";class z{static fill(e,n){for(let i=0,s=e.length;i<s;i++)e[i]=n}static fillWithin(e,n,i,s){z.rangeCheck(e.length,n,i);for(let a=n;a<i;a++)e[a]=s}static rangeCheck(e,n,i){if(n>i)throw new A("fromIndex("+n+") > toIndex("+i+")");if(n<0)throw new K(n);if(i>e)throw new K(i)}static asList(...e){return e}static create(e,n,i){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(i))}static createInt32Array(e,n,i){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(i))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let i=0,s=e.length;i<s;i++)if(e[i]!==n[i])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const i of e)n=31*n+i;return n}static fillUint8Array(e,n){for(let i=0;i!==e.length;i++)e[i]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const i=new Uint8Array(n);return i.set(e),i}return e.slice(0,n)}static copyOfRange(e,n,i){const s=i-n,a=new Int32Array(s);return B.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,i){i===void 0&&(i=z.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,d=i(n,e[l]);if(d>0)s=l+1;else if(d<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class ${static numberOfTrailingZeros(e){let n;if(e===0)return 32;let i=31;return n=e<<16,n!==0&&(i-=16,e=n),n=e<<8,n!==0&&(i-=8,e=n),n=e<<4,n!==0&&(i-=4,e=n),n=e<<2,n!==0&&(i-=2,e=n),i-(e<<1>>>31)}static numberOfLeadingZeros(e){if(e===0)return 32;let n=1;return e>>>16||(n+=16,e<<=16),e>>>24||(n+=8,e<<=8),e>>>28||(n+=4,e<<=4),e>>>30||(n+=2,e<<=2),n-=e>>>31,n}static toHexString(e){return e.toString(16)}static toBinaryString(e){return String(parseInt(String(e),2))}static bitCount(e){return e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),e=e+(e>>>4)&252645135,e=e+(e>>>8),e=e+(e>>>16),e&63}static truncDivision(e,n){return Math.trunc(e/n)}static parseInt(e,n=void 0){return parseInt(e,n)}}$.MIN_VALUE_32_BITS=-2147483648,$.MAX_VALUE=Number.MAX_SAFE_INTEGER;class W{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=W.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=W.makeArray(e);B.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}}get(e){return(this.bits[Math.floor(e/32)]&1<<(e&31))!==0}set(e){this.bits[Math.floor(e/32)]|=1<<(e&31)}flip(e){this.bits[Math.floor(e/32)]^=1<<(e&31)}getNextSet(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=i[s]}const d=s*32+$.numberOfTrailingZeros(a);return d>n?n:d}getNextUnset(e){const n=this.size;if(e>=n)return n;const i=this.bits;let s=Math.floor(e/32),a=~i[s];a&=~((1<<(e&31))-1);const l=i.length;for(;a===0;){if(++s===l)return n;a=~i[s]}const d=s*32+$.numberOfTrailingZeros(a);return d>n?n:d}setBulk(e,n){this.bits[Math.floor(e/32)]=n}setRange(e,n){if(n<e||e<0||n>this.size)throw new A;if(n===e)return;n--;const i=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=i;l<=s;l++){const d=l>i?0:e&31,p=(2<<(l<s?31:n&31))-(1<<d);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let i=0;i<e;i++)n[i]=0}isRange(e,n,i){if(n<e||e<0||n>this.size)throw new A;if(n===e)return!0;n--;const s=Math.floor(e/32),a=Math.floor(n/32),l=this.bits;for(let d=s;d<=a;d++){const h=d>s?0:e&31,y=(2<<(d<a?31:n&31))-(1<<h)&4294967295;if((l[d]&y)!==(i?y:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let i=n;i>0;i--)this.appendBit((e>>i-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let i=0;i<n;i++)this.appendBit(e.get(i))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let i=0,s=n.length;i<s;i++)n[i]^=e.bits[i]}toBytes(e,n,i,s){for(let a=0;a<s;a++){let l=0;for(let d=0;d<8;d++)this.get(e)&&(l|=1<<7-d),e++;n[i+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),i=n+1,s=this.bits;for(let a=0;a<i;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==i*32){const a=i*32-this.size;let l=e[0]>>>a;for(let d=1;d<i;d++){const h=e[d];l|=h<<32-a,e[d-1]=l,l=h>>>a}e[i-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof W))return!1;const n=e;return this.size===n.size&&z.equals(this.bits,n.bits)}hashCode(){return 31*this.size+z.hashCode(this.bits)}toString(){let e="";for(let n=0,i=this.size;n<i;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new W(this.size,this.bits.slice())}}var X;(function(b){b[b.OTHER=0]="OTHER",b[b.PURE_BARCODE=1]="PURE_BARCODE",b[b.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",b[b.TRY_HARDER=3]="TRY_HARDER",b[b.CHARACTER_SET=4]="CHARACTER_SET",b[b.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",b[b.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",b[b.ASSUME_GS1=7]="ASSUME_GS1",b[b.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",b[b.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",b[b.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(X||(X={}));var H=X;class V extends g{static getFormatInstance(){return new V}}V.kind="FormatException";var Z;(function(b){b[b.Cp437=0]="Cp437",b[b.ISO8859_1=1]="ISO8859_1",b[b.ISO8859_2=2]="ISO8859_2",b[b.ISO8859_3=3]="ISO8859_3",b[b.ISO8859_4=4]="ISO8859_4",b[b.ISO8859_5=5]="ISO8859_5",b[b.ISO8859_6=6]="ISO8859_6",b[b.ISO8859_7=7]="ISO8859_7",b[b.ISO8859_8=8]="ISO8859_8",b[b.ISO8859_9=9]="ISO8859_9",b[b.ISO8859_10=10]="ISO8859_10",b[b.ISO8859_11=11]="ISO8859_11",b[b.ISO8859_13=12]="ISO8859_13",b[b.ISO8859_14=13]="ISO8859_14",b[b.ISO8859_15=14]="ISO8859_15",b[b.ISO8859_16=15]="ISO8859_16",b[b.SJIS=16]="SJIS",b[b.Cp1250=17]="Cp1250",b[b.Cp1251=18]="Cp1251",b[b.Cp1252=19]="Cp1252",b[b.Cp1256=20]="Cp1256",b[b.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",b[b.UTF8=22]="UTF8",b[b.ASCII=23]="ASCII",b[b.Big5=24]="Big5",b[b.GB18030=25]="GB18030",b[b.EUC_KR=26]="EUC_KR"})(Z||(Z={}));class M{constructor(e,n,i,...s){this.valueIdentifier=e,this.name=i,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,M.VALUE_IDENTIFIER_TO_ECI.set(e,this),M.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];M.VALUES_TO_ECI.set(h,this)}for(const l of s)M.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new V("incorect value");const n=M.VALUES_TO_ECI.get(e);if(n===void 0)throw new V("incorect value");return n}static getCharacterSetECIByName(e){const n=M.NAME_TO_ECI.get(e);if(n===void 0)throw new V("incorect value");return n}equals(e){if(!(e instanceof M))return!1;const n=e;return this.getName()===n.getName()}}M.VALUE_IDENTIFIER_TO_ECI=new Map,M.VALUES_TO_ECI=new Map,M.NAME_TO_ECI=new Map,M.Cp437=new M(Z.Cp437,Int32Array.from([0,2]),"Cp437"),M.ISO8859_1=new M(Z.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),M.ISO8859_2=new M(Z.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),M.ISO8859_3=new M(Z.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),M.ISO8859_4=new M(Z.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),M.ISO8859_5=new M(Z.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),M.ISO8859_6=new M(Z.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),M.ISO8859_7=new M(Z.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),M.ISO8859_8=new M(Z.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),M.ISO8859_9=new M(Z.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),M.ISO8859_10=new M(Z.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),M.ISO8859_11=new M(Z.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),M.ISO8859_13=new M(Z.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),M.ISO8859_14=new M(Z.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),M.ISO8859_15=new M(Z.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),M.ISO8859_16=new M(Z.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),M.SJIS=new M(Z.SJIS,20,"SJIS","Shift_JIS"),M.Cp1250=new M(Z.Cp1250,21,"Cp1250","windows-1250"),M.Cp1251=new M(Z.Cp1251,22,"Cp1251","windows-1251"),M.Cp1252=new M(Z.Cp1252,23,"Cp1252","windows-1252"),M.Cp1256=new M(Z.Cp1256,24,"Cp1256","windows-1256"),M.UnicodeBigUnmarked=new M(Z.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),M.UTF8=new M(Z.UTF8,26,"UTF8","UTF-8"),M.ASCII=new M(Z.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),M.Big5=new M(Z.Big5,28,"Big5"),M.GB18030=new M(Z.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),M.EUC_KR=new M(Z.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class ce{static decode(e,n){const i=this.encodingName(n);return this.customDecoder?this.customDecoder(e,i):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(i)?this.decodeFallback(e,i):new TextDecoder(i).decode(e)}static shouldDecodeOnFallback(e){return!ce.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const i=this.encodingName(n);return this.customEncoder?this.customEncoder(e,i):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof M?e:M.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(ce.isDecodeFallbackSupported(i)){let s="";for(let a=0,l=e.length;a<l;a++){let d=e[a].toString(16);d.length<2&&(d="0"+d),s+="%"+d}return decodeURIComponent(s)}if(i.equals(M.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new we(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(M.UTF8)||e.equals(M.ISO8859_1)||e.equals(M.ASCII)}static encodeFallback(e){const i=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<i.length;a++)s.push(i[a].charCodeAt(0));return new Uint8Array(s)}}class fe{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return ce.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(H.CHARACTER_SET)!==void 0)return n.get(H.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,p=0,y=0,E=0,I=0,R=0,F=0,U=0,Y=0,re=0;const me=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let xe=0;xe<i&&(s||a||l);xe++){const ue=e[xe]&255;l&&(d>0?(ue&128)===0?l=!1:d--:(ue&128)!==0&&((ue&64)===0?l=!1:(d++,(ue&32)===0?h++:(d++,(ue&16)===0?p++:(d++,(ue&8)===0?y++:l=!1))))),s&&(ue>127&&ue<160?s=!1:ue>159&&(ue<192||ue===215||ue===247)&&re++),a&&(E>0?ue<64||ue===127||ue>252?a=!1:E--:ue===128||ue===160||ue>239?a=!1:ue>160&&ue<224?(I++,F=0,R++,R>U&&(U=R)):ue>127?(E++,R=0,F++,F>Y&&(Y=F)):(R=0,F=0))}return l&&d>0&&(l=!1),a&&E>0&&(a=!1),l&&(me||h+p+y>0)?fe.UTF8:a&&(fe.ASSUME_SHIFT_JIS||U>=3||Y>=3)?fe.SHIFT_JIS:s&&a?U===2&&I===2||re*10>=i?fe.SHIFT_JIS:fe.ISO88591:s?fe.ISO88591:a?fe.SHIFT_JIS:l?fe.UTF8:fe.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(E){case"s":R=n[i];break;case"c":R=n[i][0];break;case"f":R=parseFloat(n[i]).toFixed(l);break;case"p":R=parseFloat(n[i]).toPrecision(l);break;case"e":R=parseFloat(n[i]).toExponential(l);break;case"x":R=parseInt(n[i]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let F=parseInt(h),U=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+U:U+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return ce.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}fe.SHIFT_JIS=M.SJIS.getName(),fe.GB2312="GB2312",fe.ISO88591=M.ISO8859_1.getName(),fe.EUC_JP="EUC_JP",fe.UTF8=M.UTF8.getName(),fe.PLATFORM_DEFAULT_ENCODING=fe.UTF8,fe.ASSUME_SHIFT_JIS=!1;class ae{constructor(e=""){this.value=e}enableDecoding(e){return this.encoding=e,this}append(e){return typeof e=="string"?this.value+=e.toString():this.encoding?this.value+=fe.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,i){for(let s=n;n<n+i;s++)this.append(e[s]);return this}length(){return this.value.length}charAt(e){return this.value.charAt(e)}deleteCharAt(e){this.value=this.value.substr(0,e)+this.value.substring(e+1)}setCharAt(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+1)}substring(e,n){return this.value.substring(e,n)}setLengthToZero(){this.value=""}toString(){return this.value}insert(e,n){this.value=this.value.substr(0,e)+n+this.value.substr(e+n.length)}}class q{constructor(e,n,i,s){if(this.width=e,this.height=n,this.rowSize=i,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");i==null&&(i=Math.floor((e+31)/32)),this.rowSize=i,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,i=e[0].length,s=new q(i,n);for(let a=0;a<n;a++){const l=e[a];for(let d=0;d<i;d++)l[d]&&s.set(d,a)}return s}static parseFromString(e,n,i){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,d=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
|
|
60
|
+
`||e.charAt(p)==="\r"){if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new A("row lengths do not match");l=a,h++}p++}else if(e.substring(p,p+n.length)===n)p+=n.length,s[a]=!0,a++;else if(e.substring(p,p+i.length)===i)p+=i.length,s[a]=!1,a++;else throw new A("illegal character encountered: "+e.substring(p));if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new A("row lengths do not match");h++}const y=new q(d,h);for(let E=0;E<a;E++)s[E]&&y.set(Math.floor(E%d),Math.floor(E/d));return y}get(e,n){const i=n*this.rowSize+Math.floor(e/32);return(this.bits[i]>>>(e&31)&1)!==0}set(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]|=1<<(e&31)&4294967295}unset(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]&=~(1<<(e&31)&4294967295)}flip(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new A("input matrix dimensions do not match");const n=new W(Math.floor(this.width/32)+1),i=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const d=a*i,h=e.getRow(a,n).getBitArray();for(let p=0;p<i;p++)s[d+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let i=0;i<n;i++)e[i]=0}setRegion(e,n,i,s){if(n<0||e<0)throw new A("Left and top must be nonnegative");if(s<1||i<1)throw new A("Height and width must be at least 1");const a=e+i,l=n+s;if(l>this.height||a>this.width)throw new A("The region must fit inside the matrix");const d=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*d;for(let E=e;E<a;E++)h[y+Math.floor(E/32)]|=1<<(E&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new W(this.width):n.clear();const i=this.rowSize,s=this.bits,a=e*i;for(let l=0;l<i;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){B.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let i=new W(e),s=new W(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)i=this.getRow(a,i),s=this.getRow(n-1-a,s),i.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,i)}getEnclosingRectangle(){const e=this.width,n=this.height,i=this.rowSize,s=this.bits;let a=e,l=n,d=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<i;y++){const E=s[p*i+y];if(E!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(E<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>d){let I=31;for(;!(E>>>I);)I--;y*32+I>d&&(d=y*32+I)}}}return d<a||h<l?null:Int32Array.from([a,l,d-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let i=0;for(;i<n.length&&n[i]===0;)i++;if(i===n.length)return null;const s=i/e;let a=i%e*32;const l=n[i];let d=0;for(;(l<<31-d&4294967295)===0;)d++;return a+=d,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let i=n.length-1;for(;i>=0&&n[i]===0;)i--;if(i<0)return null;const s=Math.floor(i/e);let a=Math.floor(i%e)*32;const l=n[i];let d=31;for(;!(l>>>d);)d--;return a+=d,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof q))return!1;const n=e;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&z.equals(this.bits,n.bits)}hashCode(){let e=this.width;return e=31*e+this.width,e=31*e+this.height,e=31*e+this.rowSize,e=31*e+z.hashCode(this.bits),e}toString(e="X ",n=" ",i=`
|
|
61
|
+
`){return this.buildToString(e,n,i)}buildToString(e,n,i){let s=new ae;for(let a=0,l=this.height;a<l;a++){for(let d=0,h=this.width;d<h;d++)s.append(this.get(d,a)?e:n);s.append(i)}return s.toString()}clone(){return new q(this.width,this.height,this.rowSize,this.bits.slice())}}class D extends g{static getNotFoundInstance(){return new D}}D.kind="NotFoundException";class Q extends k{constructor(e){super(e),this.luminances=Q.EMPTY,this.buckets=new Int32Array(Q.LUMINANCE_BUCKETS)}getBlackRow(e,n){const i=this.getLuminanceSource(),s=i.getWidth();n==null||n.getSize()<s?n=new W(s):n.clear(),this.initArrays(s);const a=i.getRow(e,this.luminances),l=this.buckets;for(let h=0;h<s;h++)l[(a[h]&255)>>Q.LUMINANCE_SHIFT]++;const d=Q.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<d&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const E=a[y+1]&255;(p*4-h-E)/2<d&&n.set(y),h=p,p=E}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight(),s=new q(n,i);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(i*h/5),y=e.getRow(p,this.luminances),E=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<E;I++){const R=y[I]&255;a[R>>Q.LUMINANCE_SHIFT]++}}const l=Q.estimateBlackPoint(a),d=e.getMatrix();for(let h=0;h<i;h++){const p=h*n;for(let y=0;y<n;y++)(d[p+y]&255)<l&&s.set(y,h)}return s}createBinarizer(e){return new Q(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let i=0;i<Q.LUMINANCE_BUCKETS;i++)n[i]=0}static estimateBlackPoint(e){const n=e.length;let i=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>i&&(i=e[y]);let l=0,d=0;for(let y=0;y<n;y++){const E=y-s,I=e[y]*E*E;I>d&&(l=y,d=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new D;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const E=y-s,I=E*E*(l-y)*(i-e[y]);I>p&&(h=y,p=I)}return h<<Q.LUMINANCE_SHIFT}}Q.LUMINANCE_BITS=5,Q.LUMINANCE_SHIFT=8-Q.LUMINANCE_BITS,Q.LUMINANCE_BUCKETS=1<<Q.LUMINANCE_BITS,Q.EMPTY=Uint8ClampedArray.from([0]);class j extends Q{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight();if(n>=j.MINIMUM_DIMENSION&&i>=j.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>j.BLOCK_SIZE_POWER;(n&j.BLOCK_SIZE_MASK)!==0&&a++;let l=i>>j.BLOCK_SIZE_POWER;(i&j.BLOCK_SIZE_MASK)!==0&&l++;const d=j.calculateBlackPoints(s,a,l,n,i),h=new q(n,i);j.calculateThresholdForBlock(s,a,l,n,i,d,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new j(e)}static calculateThresholdForBlock(e,n,i,s,a,l,d){const h=a-j.BLOCK_SIZE,p=s-j.BLOCK_SIZE;for(let y=0;y<i;y++){let E=y<<j.BLOCK_SIZE_POWER;E>h&&(E=h);const I=j.cap(y,2,i-3);for(let R=0;R<n;R++){let F=R<<j.BLOCK_SIZE_POWER;F>p&&(F=p);const U=j.cap(R,2,n-3);let Y=0;for(let me=-2;me<=2;me++){const xe=l[I+me];Y+=xe[U-2]+xe[U-1]+xe[U]+xe[U+1]+xe[U+2]}const re=Y/25;j.thresholdBlock(e,F,E,re,s,d)}}}static cap(e,n,i){return e<n?n:e>i?i:e}static thresholdBlock(e,n,i,s,a,l){for(let d=0,h=i*a+n;d<j.BLOCK_SIZE;d++,h+=a)for(let p=0;p<j.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,i+d)}static calculateBlackPoints(e,n,i,s,a){const l=a-j.BLOCK_SIZE,d=s-j.BLOCK_SIZE,h=new Array(i);for(let p=0;p<i;p++){h[p]=new Int32Array(n);let y=p<<j.BLOCK_SIZE_POWER;y>l&&(y=l);for(let E=0;E<n;E++){let I=E<<j.BLOCK_SIZE_POWER;I>d&&(I=d);let R=0,F=255,U=0;for(let re=0,me=y*s+I;re<j.BLOCK_SIZE;re++,me+=s){for(let xe=0;xe<j.BLOCK_SIZE;xe++){const ue=e[me+xe]&255;R+=ue,ue<F&&(F=ue),ue>U&&(U=ue)}if(U-F>j.MIN_DYNAMIC_RANGE)for(re++,me+=s;re<j.BLOCK_SIZE;re++,me+=s)for(let xe=0;xe<j.BLOCK_SIZE;xe++)R+=e[me+xe]&255}let Y=R>>j.BLOCK_SIZE_POWER*2;if(U-F<=j.MIN_DYNAMIC_RANGE&&(Y=F/2,p>0&&E>0)){const re=(h[p-1][E]+2*h[p][E-1]+h[p-1][E-1])/4;F<re&&(Y=re)}h[p][E]=Y}}return h}}j.BLOCK_SIZE_POWER=3,j.BLOCK_SIZE=1<<j.BLOCK_SIZE_POWER,j.BLOCK_SIZE_MASK=j.BLOCK_SIZE-1,j.MINIMUM_DIMENSION=j.BLOCK_SIZE*5,j.MIN_DYNAMIC_RANGE=24;class te{constructor(e,n){this.width=e,this.height=n}getWidth(){return this.width}getHeight(){return this.height}isCropSupported(){return!1}crop(e,n,i,s){throw new we("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new we("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new we("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new ae;for(let i=0;i<this.height;i++){const s=this.getRow(i,e);for(let a=0;a<this.width;a++){const l=s[a]&255;let d;l<64?d="#":l<128?d="+":l<192?d=".":d=" ",n.append(d)}n.append(`
|
|
62
|
+
`)}return n.toString()}}class he extends te{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const i=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)i[a]=255-(i[a]&255);return i}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),i=new Uint8ClampedArray(n);for(let s=0;s<n;s++)i[s]=255-(e[s]&255);return i}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,i,s){return new he(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new he(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new he(this.delegate.rotateCounterClockwise45())}}class ge extends te{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=ge.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return ge.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,i){const s=new Uint8ClampedArray(n*i);for(let a=0,l=0,d=e.length;a<d;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],E=e[a+1],I=e[a+2];h=306*y+601*E+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth(),s=e*i;return n===null?n=this.buffer.slice(s,s+i):(n.length<i&&(n=new Uint8ClampedArray(i)),n.set(this.buffer.slice(s,s+i))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,i,s){return super.crop(e,n,i,s),this}isRotateSupported(){return!0}rotateCounterClockwise(){return this.rotate(-90),this}rotateCounterClockwise45(){return this.rotate(-45),this}getTempCanvasElement(){if(this.tempCanvasElement===null){const e=this.canvas.ownerDocument.createElement("canvas");e.width=this.canvas.width,e.height=this.canvas.height,this.tempCanvasElement=e}return this.tempCanvasElement}rotate(e){const n=this.getTempCanvasElement(),i=n.getContext("2d"),s=e*ge.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,d=Math.ceil(Math.abs(Math.cos(s))*a+Math.abs(Math.sin(s))*l),h=Math.ceil(Math.abs(Math.sin(s))*a+Math.abs(Math.cos(s))*l);return n.width=d,n.height=h,i.translate(d/2,h/2),i.rotate(s),i.drawImage(this.canvas,a/-2,l/-2),this.buffer=ge.makeBufferFromCanvasImageData(n),this}invert(){return new he(this)}}ge.DEGREE_TO_RADIANS=Math.PI/180;class de{constructor(e,n,i){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=i||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var Ce=(globalThis||Ci||self||window||void 0)&&(globalThis||Ci||self||window||void 0).__awaiter||function(b,e,n,i){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function d(y){try{p(i.next(y))}catch(E){l(E)}}function h(y){try{p(i.throw(y))}catch(E){l(E)}}function p(y){y.done?a(y.value):s(y.value).then(d,h)}p((i=i.apply(b,e||[])).next())})};class Ve{constructor(e,n=500,i){this.reader=e,this.timeBetweenScansMillis=n,this._hints=i,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}get hasNavigator(){return typeof navigator<"u"}get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices}get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)}get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts}set timeBetweenDecodingAttempts(e){this._timeBetweenDecodingAttempts=e<0?0:e}set hints(e){this._hints=e||null}get hints(){return this._hints}listVideoInputDevices(){return Ce(this,void 0,void 0,function*(){if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");const e=yield navigator.mediaDevices.enumerateDevices(),n=[];for(const i of e){const s=i.kind==="video"?"videoinput":i.kind;if(s!=="videoinput")continue;const a=i.deviceId||i.id,l=i.label||`Video device ${n.length+1}`,d=i.groupId,h={deviceId:a,label:l,kind:s,groupId:d};n.push(h)}return n})}getVideoInputDevices(){return Ce(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new de(n.deviceId,n.label))})}findDeviceById(e){return Ce(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ce(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ce(this,void 0,void 0,function*(){this.reset();let i;e?i={deviceId:{exact:e}}:i={facingMode:"environment"};const s={video:i};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return Ce(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return Ce(this,void 0,void 0,function*(){this.reset();const i=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(i)})}decodeFromInputVideoDeviceContinuously(e,n,i){return Ce(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return Ce(this,void 0,void 0,function*(){let s;e?s={deviceId:{exact:e}}:s={facingMode:"environment"};const a={video:s};return yield this.decodeFromConstraints(a,n,i)})}decodeFromConstraints(e,n,i){return Ce(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,i)})}decodeFromStream(e,n,i){return Ce(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,i)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return Ce(this,void 0,void 0,function*(){const i=this.prepareVideoElement(n);return this.addVideoSource(i,e),this.videoElement=i,this.stream=e,yield this.playVideoOnLoadAsync(i),i})}playVideoOnLoadAsync(e){return new Promise((n,i)=>this.playVideoOnLoad(e,()=>n()))}playVideoOnLoad(e,n){this.videoEndedListener=()=>this.stopStreams(),this.videoCanPlayListener=()=>this.tryPlayVideo(e),e.addEventListener("ended",this.videoEndedListener),e.addEventListener("canplay",this.videoCanPlayListener),e.addEventListener("playing",n),this.tryPlayVideo(e)}isVideoPlaying(e){return e.currentTime>0&&!e.paused&&!e.ended&&e.readyState>2}tryPlayVideo(e){return Ce(this,void 0,void 0,function*(){if(this.isVideoPlaying(e)){console.warn("Trying to play video that is already playing.");return}try{yield e.play()}catch{console.warn("It was not possible to play the video.")}})}getMediaElement(e,n){const i=document.getElementById(e);if(!i)throw new C(`element with id '${e}' not found`);if(i.nodeName.toLowerCase()!==n.toLowerCase())throw new C(`element with id '${e}' must be an ${n} element`);return i}decodeFromImage(e,n){if(!e&&!n)throw new C("either imageElement with a src set or an url must be provided");return n&&!e?this.decodeFromImageUrl(n):this.decodeFromImageElement(e)}decodeFromVideo(e,n){if(!e&&!n)throw new C("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(e)}decodeFromVideoContinuously(e,n,i){if(e===void 0&&n===void 0)throw new C("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,i):this.decodeFromVideoElementContinuously(e,i)}decodeFromImageElement(e){if(!e)throw new C("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let i;return this.isImageLoaded(n)?i=this.decodeOnce(n,!1,!0):i=this._decodeOnLoadImage(n),i}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const i=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(i,n)}_decodeFromVideoElementSetup(e){if(!e)throw new C("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new C("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const i=this._decodeOnLoadImage(n);return n.src=e,i}decodeFromVideoUrl(e){if(!e)throw new C("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),i=this.decodeFromVideoElement(n);return n.src=e,i}decodeFromVideoUrlContinuously(e,n){if(!e)throw new C("An URL must be provided.");this.reset();const i=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(i,n);return i.src=e,s}_decodeOnLoadImage(e){return new Promise((n,i)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,i),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return Ce(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ce(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(e),this.decodeContinuously(e,n)})}isImageLoaded(e){return!(!e.complete||e.naturalWidth===0)}prepareImageElement(e){let n;return typeof e>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"img")),e instanceof HTMLImageElement&&(n=e),n}prepareVideoElement(e){let n;return!e&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof e=="string"&&(n=this.getMediaElement(e,"video")),e instanceof HTMLVideoElement&&(n=e),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n}decodeOnce(e,n=!0,i=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new D("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const d=this.decode(e);a(d)}catch(d){const h=n&&d instanceof D,y=(d instanceof O||d instanceof V)&&i;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(d)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const i=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(i,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof O||s instanceof V,l=s instanceof D;(a||l)&&setTimeout(i,this._timeBetweenDecodingAttempts)}};i()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,i){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,i=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),i||(i=this.captureCanvasContext),i.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}createBinaryBitmap(e){this.getCaptureCanvasContext(e),this._isHTMLVideoElement(e)?this.drawFrameOnCanvas(e):this.drawImageOnCanvas(e);const n=this.getCaptureCanvas(e),i=new ge(n),s=new j(i);return new P(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const i=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=i}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let i,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(i=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=i+"px",n.style.height=s+"px",n.width=i,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Me{constructor(e,n,i=n==null?0:8*n.length,s,a,l=B.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=i,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,i==null?this.numBits=n==null?0:8*n.length:this.numBits=i,this.resultPoints=s,this.format=a,this.resultMetadata=null,l==null?this.timestamp=B.currentTimeMillis():this.timestamp=l}getText(){return this.text}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}getResultPoints(){return this.resultPoints}getBarcodeFormat(){return this.format}getResultMetadata(){return this.resultMetadata}putMetadata(e,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(e,n)}putAllMetadata(e){e!==null&&(this.resultMetadata===null?this.resultMetadata=e:this.resultMetadata=new Map(e))}addResultPoints(e){const n=this.resultPoints;if(n===null)this.resultPoints=e;else if(e!==null&&e.length>0){const i=new Array(n.length+e.length);B.arraycopy(n,0,i,0,n.length),B.arraycopy(e,0,i,n.length,e.length),this.resultPoints=i}}getTimestamp(){return this.timestamp}toString(){return this.text}}var Ye;(function(b){b[b.AZTEC=0]="AZTEC",b[b.CODABAR=1]="CODABAR",b[b.CODE_39=2]="CODE_39",b[b.CODE_93=3]="CODE_93",b[b.CODE_128=4]="CODE_128",b[b.DATA_MATRIX=5]="DATA_MATRIX",b[b.EAN_8=6]="EAN_8",b[b.EAN_13=7]="EAN_13",b[b.ITF=8]="ITF",b[b.MAXICODE=9]="MAXICODE",b[b.PDF_417=10]="PDF_417",b[b.QR_CODE=11]="QR_CODE",b[b.RSS_14=12]="RSS_14",b[b.RSS_EXPANDED=13]="RSS_EXPANDED",b[b.UPC_A=14]="UPC_A",b[b.UPC_E=15]="UPC_E",b[b.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Ye||(Ye={}));var ie=Ye,ke;(function(b){b[b.OTHER=0]="OTHER",b[b.ORIENTATION=1]="ORIENTATION",b[b.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",b[b.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",b[b.ISSUE_NUMBER=4]="ISSUE_NUMBER",b[b.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",b[b.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",b[b.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",b[b.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",b[b.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",b[b.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(ke||(ke={}));var Ae=ke;class Ne{constructor(e,n,i,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=i,this.ecLevel=s,this.structuredAppendSequenceNumber=a,this.structuredAppendParity=l,this.numBits=e==null?0:8*e.length}getRawBytes(){return this.rawBytes}getNumBits(){return this.numBits}setNumBits(e){this.numBits=e}getText(){return this.text}getByteSegments(){return this.byteSegments}getECLevel(){return this.ecLevel}getErrorsCorrected(){return this.errorsCorrected}setErrorsCorrected(e){this.errorsCorrected=e}getErasures(){return this.erasures}setErasures(e){this.erasures=e}getOther(){return this.other}setOther(e){this.other=e}hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0}getStructuredAppendParity(){return this.structuredAppendParity}getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber}}class ot{exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class Xe{constructor(e,n){if(n.length===0)throw new A;this.field=e;const i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(i-s),B.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);const n=this.coefficients;let i;if(e===1){i=0;for(let l=0,d=n.length;l!==d;l++){const h=n[l];i=ot.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=ot.addOrSubtract(a.multiply(e,i),n[l]);return i}addOrSubtract(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){const l=n;n=i,i=l}let s=new Int32Array(i.length);const a=i.length-n.length;B.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=ot.addOrSubtract(n[l-a],i[l]);return new Xe(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(this.isZero()||e.isZero())return this.field.getZero();const n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1),d=this.field;for(let h=0;h<i;h++){const p=n[h];for(let y=0;y<a;y++)l[h+y]=ot.addOrSubtract(l[h+y],d.multiply(p,s[y]))}return new Xe(d,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,i=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=i.multiply(a[l],e);return new Xe(i,s)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return this.field.getZero();const i=this.coefficients,s=i.length,a=new Int32Array(s+e),l=this.field;for(let d=0;d<s;d++)a[d]=l.multiply(i[d],n);return new Xe(l,a)}divide(e){if(!this.field.equals(e.field))throw new A("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new A("Divide by 0");const n=this.field;let i=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const d=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),p=e.multiplyByMonomial(d,h),y=n.buildMonomial(d,h);i=i.addOrSubtract(y),s=s.addOrSubtract(p)}return[i,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);if(i!==0){if(i<0?(e+=" - ",i=-i):e.length>0&&(e+=" + "),n===0||i!==1){const s=this.field.log(i);s===0?e+="1":s===1?e+="a":(e+="a^",e+=s)}n!==0&&(n===1?e+="x":(e+="x^",e+=n))}}return e}}class $t extends g{}$t.kind="ArithmeticException";class Ue extends ot{constructor(e,n,i){super(),this.primitive=e,this.size=n,this.generatorBase=i;const s=new Int32Array(n);let a=1;for(let d=0;d<n;d++)s[d]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let d=0;d<n-1;d++)l[s[d]]=d;this.logTable=l,this.zero=new Xe(this,Int32Array.from([0])),this.one=new Xe(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;const i=new Int32Array(e+1);return i[0]=n,new Xe(this,i)}inverse(e){if(e===0)throw new $t;return this.expTable[this.size-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.size-1)]}getSize(){return this.size}getGeneratorBase(){return this.generatorBase}toString(){return"GF(0x"+$.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Ue.AZTEC_DATA_12=new Ue(4201,4096,1),Ue.AZTEC_DATA_10=new Ue(1033,1024,1),Ue.AZTEC_DATA_6=new Ue(67,64,1),Ue.AZTEC_PARAM=new Ue(19,16,1),Ue.QR_CODE_FIELD_256=new Ue(285,256,0),Ue.DATA_MATRIX_FIELD_256=new Ue(301,256,1),Ue.AZTEC_DATA_8=Ue.DATA_MATRIX_FIELD_256,Ue.MAXICODE_FIELD_64=Ue.AZTEC_DATA_6;class pn extends g{}pn.kind="ReedSolomonException";class Vt extends g{}Vt.kind="IllegalStateException";class bn{constructor(e){this.field=e}decode(e,n){const i=this.field,s=new Xe(i,e),a=new Int32Array(n);let l=!0;for(let R=0;R<n;R++){const F=s.evaluateAt(i.exp(R+i.getGeneratorBase()));a[a.length-1-R]=F,F!==0&&(l=!1)}if(l)return;const d=new Xe(i,a),h=this.runEuclideanAlgorithm(i.buildMonomial(n,1),d,n),p=h[0],y=h[1],E=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,E);for(let R=0;R<E.length;R++){const F=e.length-1-i.log(E[R]);if(F<0)throw new pn("Bad error location");e[F]=Ue.addOrSubtract(e[F],I[R])}}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){const R=e;e=n,n=R}const s=this.field;let a=e,l=n,d=s.getZero(),h=s.getOne();for(;l.getDegree()>=(i/2|0);){let R=a,F=d;if(a=l,d=h,a.isZero())throw new pn("r_{i-1} was zero");l=R;let U=s.getZero();const Y=a.getCoefficient(a.getDegree()),re=s.inverse(Y);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const me=l.getDegree()-a.getDegree(),xe=s.multiply(l.getCoefficient(l.getDegree()),re);U=U.addOrSubtract(s.buildMonomial(me,xe)),l=l.addOrSubtract(a.multiplyByMonomial(me,xe))}if(h=U.multiply(d).addOrSubtract(F),l.getDegree()>=a.getDegree())throw new Vt("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new pn("sigmaTilde(0) was zero");const y=s.inverse(p),E=h.multiplyScalar(y),I=l.multiplyScalar(y);return[E,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const i=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(i[s]=a.inverse(l),s++);if(s!==n)throw new pn("Error locator degree does not match number of roots");return i}findErrorMagnitudes(e,n){const i=n.length,s=new Int32Array(i),a=this.field;for(let l=0;l<i;l++){const d=a.inverse(n[l]);let h=1;for(let p=0;p<i;p++)if(l!==p){const y=a.multiply(n[p],d),E=(y&1)===0?y|1:y&-2;h=a.multiply(h,E)}s[l]=a.multiply(e.evaluateAt(d),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],d))}return s}}var wt;(function(b){b[b.UPPER=0]="UPPER",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.DIGIT=3]="DIGIT",b[b.PUNCT=4]="PUNCT",b[b.BINARY=5]="BINARY"})(wt||(wt={}));class Je{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=Je.convertBoolArrayToByteArray(s),l=Je.getEncodedData(s),d=new Ne(a,l,null,null);return d.setNumBits(s.length),d}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,i=wt.UPPER,s=wt.UPPER,a="",l=0;for(;l<n;)if(s===wt.BINARY){if(n-l<5)break;let d=Je.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=Je.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const p=Je.readCode(e,l,8);a+=fe.castAsNonUtf8Char(p),l+=8}s=i}else{let d=s===wt.DIGIT?4:5;if(n-l<d)break;let h=Je.readCode(e,l,d);l+=d;let p=Je.getCharacter(s,h);p.startsWith("CTRL_")?(i=s,s=Je.getTable(p.charAt(5)),p.charAt(6)==="L"&&(i=s)):(a+=p,s=i)}return a}static getTable(e){switch(e){case"L":return wt.LOWER;case"P":return wt.PUNCT;case"M":return wt.MIXED;case"D":return wt.DIGIT;case"B":return wt.BINARY;case"U":default:return wt.UPPER}}static getCharacter(e,n){switch(e){case wt.UPPER:return Je.UPPER_TABLE[n];case wt.LOWER:return Je.LOWER_TABLE[n];case wt.MIXED:return Je.MIXED_TABLE[n];case wt.PUNCT:return Je.PUNCT_TABLE[n];case wt.DIGIT:return Je.DIGIT_TABLE[n];default:throw new Vt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=Ue.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=Ue.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=Ue.AZTEC_DATA_10):(i=12,n=Ue.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new V;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=Je.readCode(e,l,i);try{new bn(n).decode(d,a-s)}catch(I){throw new V(I)}let h=(1<<i)-1,p=0;for(let I=0;I<s;I++){let R=d[I];if(R===0||R===h)throw new V;(R===1||R===h-1)&&p++}let y=new Array(s*i-p),E=0;for(let I=0;I<s;I++){let R=d[I];if(R===1||R===h-1)y.fill(R>1,E,E+i-1),E+=i-1;else for(let F=i-1;F>=0;--F)y[E++]=(R&1<<F)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),i=this.ddata.getNbLayers(),s=(n?11:14)+i*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(i,n));if(n)for(let d=0;d<a.length;d++)a[d]=d;else{let d=s+1+2*$.truncDivision($.truncDivision(s,2)-1,15),h=s/2,p=$.truncDivision(d,2);for(let y=0;y<h;y++){let E=y+$.truncDivision(y,15);a[h-y-1]=p-E-1,a[h+y]=p+E+1}}for(let d=0,h=0;d<i;d++){let p=(i-d)*4+(n?9:12),y=d*2,E=s-1-y;for(let I=0;I<p;I++){let R=I*2;for(let F=0;F<2;F++)l[h+R+F]=e.get(a[y+F],a[y+I]),l[h+2*p+R+F]=e.get(a[y+I],a[E-F]),l[h+4*p+R+F]=e.get(a[E-F],a[E-I]),l[h+6*p+R+F]=e.get(a[E-I],a[y+F])}h+=p*8}return l}static readCode(e,n,i){let s=0;for(let a=n;a<n+i;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let i=e.length-n;return i>=8?Je.readCode(e,n,8):Je.readCode(e,n,i)<<8-i}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let i=0;i<n.length;i++)n[i]=Je.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Je.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],Je.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],Je.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
|
|
63
63
|
`,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],Je.PUNCT_TABLE=["","\r",`\r
|
|
64
|
-
`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],Je.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class je{constructor(){}static round(e){return e===NaN?0:e<=Number.MIN_SAFE_INTEGER?Number.MIN_SAFE_INTEGER:e>=Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+(e<0?-.5:.5)|0}static distance(e,n,i,s){const a=e-i,l=n-s;return Math.sqrt(a*a+l*l)}static sum(e){let n=0;for(let i=0,s=e.length;i!==s;i++){const a=e[i];n+=a}return n}}class En{static floatToIntBits(e){return e}}En.MAX_VALUE=Number.MAX_SAFE_INTEGER;class T{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof T){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*En.floatToIntBits(this.x)+En.floatToIntBits(this.y)}toString(){return"("+this.x+","+this.y+")"}static orderBestPatterns(e){const n=this.distance(e[0],e[1]),i=this.distance(e[1],e[2]),s=this.distance(e[0],e[2]);let a,l,d;if(i>=n&&i>=s?(l=e[0],a=e[1],d=e[2]):s>=i&&s>=n?(l=e[1],a=e[0],d=e[2]):(l=e[2],a=e[0],d=e[1]),this.crossProductZ(a,l,d)<0){const h=a;a=d,d=h}e[0]=a,e[1]=l,e[2]=d}static distance(e,n){return je.distance(e.x,e.y,n.x,n.y)}static crossProductZ(e,n,i){const s=n.x,a=n.y;return(i.x-s)*(e.y-a)-(i.y-a)*(e.x-s)}}class pe{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class _t extends pe{constructor(e,n,i,s,a){super(e,n),this.compact=i,this.nbDatablocks=s,this.nbLayers=a}getNbLayers(){return this.nbLayers}getNbDatablocks(){return this.nbDatablocks}isCompact(){return this.compact}}class vt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=vt.INIT_SIZE),i==null&&(i=e.getWidth()/2|0),s==null&&(s=e.getHeight()/2|0);const a=n/2|0;if(this.leftInit=i-a,this.rightInit=i+a,this.upInit=s-a,this.downInit=s+a,this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width)throw new D}detect(){let e=this.leftInit,n=this.rightInit,i=this.upInit,s=this.downInit,a=!1,l=!0,d=!1,h=!1,m=!1,y=!1,E=!1;const I=this.width,R=this.height;for(;l;){l=!1;let F=!0;for(;(F||!h)&&n<I;)F=this.containsBlackPoint(i,s,n,!1),F?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let U=!0;for(;(U||!m)&&s<R;)U=this.containsBlackPoint(e,n,s,!0),U?(s++,l=!0,m=!0):m||s++;if(s>=R){a=!0;break}let q=!0;for(;(q||!y)&&e>=0;)q=this.containsBlackPoint(i,s,e,!1),q?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let ne=!0;for(;(ne||!E)&&i>=0;)ne=this.containsBlackPoint(e,n,i,!0),ne?(i--,l=!0,E=!0):E||i--;if(i<0){a=!0;break}l&&(d=!0)}if(!a&&d){const F=n-e;let U=null;for(let xe=1;U===null&&xe<F;xe++)U=this.getBlackPointOnSegment(e,s-xe,e+xe,s);if(U==null)throw new D;let q=null;for(let xe=1;q===null&&xe<F;xe++)q=this.getBlackPointOnSegment(e,i+xe,e+xe,i);if(q==null)throw new D;let ne=null;for(let xe=1;ne===null&&xe<F;xe++)ne=this.getBlackPointOnSegment(n,i+xe,n-xe,i);if(ne==null)throw new D;let me=null;for(let xe=1;me===null&&xe<F;xe++)me=this.getBlackPointOnSegment(n,s-xe,n-xe,s);if(me==null)throw new D;return this.centerEdges(me,U,ne,q)}else throw new D}getBlackPointOnSegment(e,n,i,s){const a=je.round(je.distance(e,n,i,s)),l=(i-e)/a,d=(s-n)/a,h=this.image;for(let m=0;m<a;m++){const y=je.round(e+m*l),E=je.round(n+m*d);if(h.get(y,E))return new T(y,E)}return null}centerEdges(e,n,i,s){const a=e.getX(),l=e.getY(),d=n.getX(),h=n.getY(),m=i.getX(),y=i.getY(),E=s.getX(),I=s.getY(),R=vt.CORR;return a<this.width/2?[new T(E-R,I+R),new T(d+R,h+R),new T(m-R,y-R),new T(a+R,l-R)]:[new T(E+R,I+R),new T(d+R,h-R),new T(m-R,y+R),new T(a-R,l-R)]}containsBlackPoint(e,n,i,s){const a=this.image;if(s){for(let l=e;l<=n;l++)if(a.get(l,i))return!0}else for(let l=e;l<=n;l++)if(a.get(i,l))return!0;return!1}}vt.INIT_SIZE=10,vt.CORR=1;class Un{static checkAndNudgePoints(e,n){const i=e.getWidth(),s=e.getHeight();let a=!0;for(let l=0;l<n.length&&a;l+=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new D;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}a=!0;for(let l=n.length-2;l>=0&&a;l-=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new D;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}}}class nn{constructor(e,n,i,s,a,l,d,h,m){this.a11=e,this.a21=n,this.a31=i,this.a12=s,this.a22=a,this.a32=l,this.a13=d,this.a23=h,this.a33=m}static quadrilateralToQuadrilateral(e,n,i,s,a,l,d,h,m,y,E,I,R,F,U,q){const ne=nn.quadrilateralToSquare(e,n,i,s,a,l,d,h);return nn.squareToQuadrilateral(m,y,E,I,R,F,U,q).times(ne)}transformPoints(e){const n=e.length,i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,m=this.a31,y=this.a32,E=this.a33;for(let I=0;I<n;I+=2){const R=e[I],F=e[I+1],U=a*R+h*F+E;e[I]=(i*R+l*F+m)/U,e[I+1]=(s*R+d*F+y)/U}}transformPointsWithValues(e,n){const i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,m=this.a31,y=this.a32,E=this.a33,I=e.length;for(let R=0;R<I;R++){const F=e[R],U=n[R],q=a*F+h*U+E;e[R]=(i*F+l*U+m)/q,n[R]=(s*F+d*U+y)/q}}static squareToQuadrilateral(e,n,i,s,a,l,d,h){const m=e-i+a-d,y=n-s+l-h;if(m===0&&y===0)return new nn(i-e,a-i,e,s-n,l-s,n,0,0,1);{const E=i-a,I=d-a,R=s-l,F=h-l,U=E*F-I*R,q=(m*F-I*y)/U,ne=(E*y-m*R)/U;return new nn(i-e+q*i,d-e+ne*d,e,s-n+q*s,h-n+ne*h,n,q,ne,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return nn.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new nn(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21)}times(e){return new nn(this.a11*e.a11+this.a21*e.a12+this.a31*e.a13,this.a11*e.a21+this.a21*e.a22+this.a31*e.a23,this.a11*e.a31+this.a21*e.a32+this.a31*e.a33,this.a12*e.a11+this.a22*e.a12+this.a32*e.a13,this.a12*e.a21+this.a22*e.a22+this.a32*e.a23,this.a12*e.a31+this.a22*e.a32+this.a32*e.a33,this.a13*e.a11+this.a23*e.a12+this.a33*e.a13,this.a13*e.a21+this.a23*e.a22+this.a33*e.a23,this.a13*e.a31+this.a23*e.a32+this.a33*e.a33)}}class ai extends Un{sampleGrid(e,n,i,s,a,l,d,h,m,y,E,I,R,F,U,q,ne,me,xe){const ue=nn.quadrilateralToQuadrilateral(s,a,l,d,h,m,y,E,I,R,F,U,q,ne,me,xe);return this.sampleGridWithTransform(e,n,i,ue)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new D;const a=new X(n,i),l=new Float32Array(2*n);for(let d=0;d<i;d++){const h=l.length,m=d+.5;for(let y=0;y<h;y+=2)l[y]=y/2+.5,l[y+1]=m;s.transformPoints(l),Un.checkAndNudgePoints(e,l);try{for(let y=0;y<h;y+=2)e.get(Math.floor(l[y]),Math.floor(l[y+1]))&&a.set(y/2,d)}catch{throw new D}}return a}}class An{static setGridSampler(e){An.gridSampler=e}static getInstance(){return An.gridSampler}}An.gridSampler=new ai;class Lt{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new T(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class li{constructor(e){this.EXPECTED_CORNER_BITS=new Int32Array([3808,476,2107,1799]),this.image=e}detect(){return this.detectMirror(!1)}detectMirror(e){let n=this.getMatrixCenter(),i=this.getBullsEyeCorners(n);if(e){let l=i[0];i[0]=i[2],i[2]=l}this.extractParameters(i);let s=this.sampleGrid(this.image,i[this.shift%4],i[(this.shift+1)%4],i[(this.shift+2)%4],i[(this.shift+3)%4]),a=this.getMatrixCornerPoints(i);return new _t(s,a,this.compact,this.nbDataBlocks,this.nbLayers)}extractParameters(e){if(!this.isValidPoint(e[0])||!this.isValidPoint(e[1])||!this.isValidPoint(e[2])||!this.isValidPoint(e[3]))throw new D;let n=2*this.nbCenterLayers,i=new Int32Array([this.sampleLine(e[0],e[1],n),this.sampleLine(e[1],e[2],n),this.sampleLine(e[2],e[3],n),this.sampleLine(e[3],e[0],n)]);this.shift=this.getRotation(i,n);let s=0;for(let l=0;l<4;l++){let d=i[(this.shift+l)%4];this.compact?(s<<=7,s+=d>>1&127):(s<<=10,s+=(d>>2&992)+(d>>1&31))}let a=this.getCorrectedParameterData(s,this.compact);this.compact?(this.nbLayers=(a>>6)+1,this.nbDataBlocks=(a&63)+1):(this.nbLayers=(a>>11)+1,this.nbDataBlocks=(a&2047)+1)}getRotation(e,n){let i=0;e.forEach((s,a,l)=>{let d=(s>>n-2<<1)+(s&1);i=(i<<3)+d}),i=((i&1)<<11)+(i>>1);for(let s=0;s<4;s++)if($.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new D}getCorrectedParameterData(e,n){let i,s;n?(i=7,s=2):(i=10,s=4);let a=i-s,l=new Int32Array(i);for(let h=i-1;h>=0;--h)l[h]=e&15,e>>=4;try{new bn(Ue.AZTEC_PARAM).decode(l,a)}catch{throw new D}let d=0;for(let h=0;h<s;h++)d=(d<<4)+l[h];return d}getBullsEyeCorners(e){let n=e,i=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let E=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(i,l,1,1),R=this.getFirstDifferent(s,l,-1,1),F=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let U=this.distancePoint(F,E)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(U<.75||U>1.25||!this.isWhiteOrBlackRectangle(E,I,R,F))break}n=E,i=I,s=R,a=F,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new D;this.compact=this.nbCenterLayers===5;let d=new T(n.getX()+.5,n.getY()-.5),h=new T(i.getX()+.5,i.getY()+.5),m=new T(s.getX()-.5,s.getY()+.5),y=new T(a.getX()-.5,a.getY()-.5);return this.expandSquare([d,h,m,y],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,i,s;try{let d=new vt(this.image).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{let h=this.image.getWidth()/2,m=this.image.getHeight()/2;e=this.getFirstDifferent(new Lt(h+7,m-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(h+7,m+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(h-7,m+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(h-7,m-7),!1,-1,-1).toResultPoint()}let a=je.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=je.round((e.getY()+s.getY()+n.getY()+i.getY())/4);try{let d=new vt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new Lt(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(a-7,l-7),!1,-1,-1).toResultPoint()}return a=je.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=je.round((e.getY()+s.getY()+n.getY()+i.getY())/4),new Lt(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=An.getInstance(),d=this.getDimension(),h=d/2-this.nbCenterLayers,m=d/2+this.nbCenterLayers;return l.sampleGrid(e,d,d,h,h,m,h,m,m,h,m,n.getX(),n.getY(),i.getX(),i.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,i){let s=0,a=this.distanceResultPoint(e,n),l=a/i,d=e.getX(),h=e.getY(),m=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let E=0;E<i;E++)this.image.get(je.round(d+E*m),je.round(h+E*y))&&(s|=1<<i-E-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new Lt(e.getX()-a,e.getY()+a),n=new Lt(n.getX()-a,n.getY()-a),i=new Lt(i.getX()+a,i.getY()-a),s=new Lt(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let d=this.getColor(e,n);return d!==l||(d=this.getColor(n,i),d!==l)?!1:(d=this.getColor(i,s),d===l)}getColor(e,n){let i=this.distancePoint(e,n),s=(n.getX()-e.getX())/i,a=(n.getY()-e.getY())/i,l=0,d=e.getX(),h=e.getY(),m=this.image.get(e.getX(),e.getY()),y=Math.ceil(i);for(let I=0;I<y;I++)d+=s,h+=a,this.image.get(je.round(d),je.round(h))!==m&&l++;let E=l/i;return E>.1&&E<.9?0:E<=.1===m?1:-1}getFirstDifferent(e,n,i,s){let a=e.getX()+i,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i,l+=s;for(a-=i,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i;for(a-=i;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new Lt(a,l)}expandSquare(e,n,i){let s=i/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),d=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,m=new T(d+s*a,h+s*l),y=new T(d-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),d=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let E=new T(d+s*a,h+s*l),I=new T(d-s*a,h-s*l);return[m,E,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=je.round(e.getX()),i=je.round(e.getY());return this.isValid(n,i)}distancePoint(e,n){return je.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return je.distance(e.getX(),e.getY(),n.getX(),n.getY())}getDimension(){return this.compact?4*this.nbLayers+11:this.nbLayers<=4?4*this.nbLayers+15:4*this.nbLayers+2*($.truncDivision(this.nbLayers-4,8)+1)+15}}class pr{decode(e,n=null){let i=null,s=new li(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Je().decode(y)}catch(y){i=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Je().decode(y)}catch(y){throw i??y}let d=new Me(l.getText(),l.getRawBytes(),l.getNumBits(),a,ie.AZTEC,P.currentTimeMillis()),h=l.getByteSegments();h!=null&&d.putMetadata(Ae.BYTE_SEGMENTS,h);let m=l.getECLevel();return m!=null&&d.putMetadata(Ae.ERROR_CORRECTION_LEVEL,m),d}reportFoundResultPoints(e,n){if(e!=null){let i=e.get(j.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class Wi extends Ve{constructor(e=500){super(new pr,e)}}class Ie{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(j.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),d=l.getResultMetadata();let h=270;d!==null&&d.get(Ae.ORIENTATION)===!0&&(h=h+d.get(Ae.ORIENTATION)%360),l.putMetadata(Ae.ORIENTATION,h);const m=l.getResultPoints();if(m!==null){const y=a.getHeight();for(let E=0;E<m.length;E++)m[E]=new T(y-m[E].getY()-1,m[E].getX())}return l}else throw new D}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new H(i);const l=n&&n.get(j.TRY_HARDER)===!0,d=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const m=Math.trunc(s/2);for(let y=0;y<h;y++){const E=Math.trunc((y+1)/2),I=(y&1)===0,R=m+d*(I?E:-E);if(R<0||R>=s)break;try{a=e.getBlackRow(R,a)}catch{continue}for(let F=0;F<2;F++){if(F===1&&(a.reverse(),n&&n.get(j.NEED_RESULT_POINT_CALLBACK)===!0)){const U=new Map;n.forEach((q,ne)=>U.set(ne,q)),U.delete(j.NEED_RESULT_POINT_CALLBACK),n=U}try{const U=this.decodeRow(R,a,n);if(F===1){U.putMetadata(Ae.ORIENTATION,180);const q=U.getResultPoints();q!==null&&(q[0]=new T(i-q[0].getX()-1,q[0].getY()),q[1]=new T(i-q[1].getX()-1,q[1].getY()))}return U}catch{}}}throw new D}static recordPattern(e,n,i){const s=i.length;for(let m=0;m<s;m++)i[m]=0;const a=e.getSize();if(n>=a)throw new D;let l=!e.get(n),d=0,h=n;for(;h<a;){if(e.get(h)!==l)i[d]++;else{if(++d===s)break;i[d]=1,l=!l}h++}if(!(d===s||d===s-1&&h===a))throw new D}static recordPatternInReverse(e,n,i){let s=i.length,a=e.get(n);for(;n>0&&s>=0;)e.get(--n)!==a&&(s--,a=!a);if(s>=0)throw new D;Ie.recordPattern(e,n+1,i)}static patternMatchVariance(e,n,i){const s=e.length;let a=0,l=0;for(let m=0;m<s;m++)a+=e[m],l+=n[m];if(a<l)return Number.POSITIVE_INFINITY;const d=a/l;i*=d;let h=0;for(let m=0;m<s;m++){const y=e[m],E=n[m]*d,I=y>E?y-E:E-y;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class oe extends Ie{static findStartPattern(e){const n=e.getSize(),i=e.getNextSet(0);let s=0,a=Int32Array.from([0,0,0,0,0,0]),l=i,d=!1;const h=6;for(let m=i;m<n;m++)if(e.get(m)!==d)a[s]++;else{if(s===h-1){let y=oe.MAX_AVG_VARIANCE,E=-1;for(let I=oe.CODE_START_A;I<=oe.CODE_START_C;I++){const R=Ie.patternMatchVariance(a,oe.CODE_PATTERNS[I],oe.MAX_INDIVIDUAL_VARIANCE);R<y&&(y=R,E=I)}if(E>=0&&e.isRange(Math.max(0,l-(m-l)/2),l,!1))return Int32Array.from([l,m,E]);l+=a[0]+a[1],a=a.slice(2,a.length-1),a[s-1]=0,a[s]=0,s--}else s++;a[s]=1,d=!d}throw new D}static decodeCode(e,n,i){Ie.recordPattern(e,i,n);let s=oe.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<oe.CODE_PATTERNS.length;l++){const d=oe.CODE_PATTERNS[l],h=this.patternMatchVariance(n,d,oe.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new D}decodeRow(e,n,i){const s=i&&i.get(j.ASSUME_GS1)===!0,a=oe.findStartPattern(n),l=a[2];let d=0;const h=new Uint8Array(20);h[d++]=l;let m;switch(l){case oe.CODE_START_A:m=oe.CODE_CODE_A;break;case oe.CODE_START_B:m=oe.CODE_CODE_B;break;case oe.CODE_START_C:m=oe.CODE_CODE_C;break;default:throw new V}let y=!1,E=!1,I="",R=a[0],F=a[1];const U=Int32Array.from([0,0,0,0,0,0]);let q=0,ne=0,me=l,xe=0,ue=!0,We=!1,Be=!1;for(;!y;){const br=E;switch(E=!1,q=ne,ne=oe.decodeCode(n,U,F),h[d++]=ne,ne!==oe.CODE_STOP&&(ue=!0),ne!==oe.CODE_STOP&&(xe++,me+=xe*ne),R=F,F+=U.reduce((Ad,Id)=>Ad+Id,0),ne){case oe.CODE_START_A:case oe.CODE_START_B:case oe.CODE_START_C:throw new V}switch(m){case oe.CODE_CODE_A:if(ne<64)Be===We?I+=String.fromCharCode(32+ne):I+=String.fromCharCode(32+ne+128),Be=!1;else if(ne<96)Be===We?I+=String.fromCharCode(ne-64):I+=String.fromCharCode(ne+64),Be=!1;else switch(ne!==oe.CODE_STOP&&(ue=!1),ne){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_FNC_2:case oe.CODE_FNC_3:break;case oe.CODE_FNC_4_A:!We&&Be?(We=!0,Be=!1):We&&Be?(We=!1,Be=!1):Be=!0;break;case oe.CODE_SHIFT:E=!0,m=oe.CODE_CODE_B;break;case oe.CODE_CODE_B:m=oe.CODE_CODE_B;break;case oe.CODE_CODE_C:m=oe.CODE_CODE_C;break;case oe.CODE_STOP:y=!0;break}break;case oe.CODE_CODE_B:if(ne<96)Be===We?I+=String.fromCharCode(32+ne):I+=String.fromCharCode(32+ne+128),Be=!1;else switch(ne!==oe.CODE_STOP&&(ue=!1),ne){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_FNC_2:case oe.CODE_FNC_3:break;case oe.CODE_FNC_4_B:!We&&Be?(We=!0,Be=!1):We&&Be?(We=!1,Be=!1):Be=!0;break;case oe.CODE_SHIFT:E=!0,m=oe.CODE_CODE_A;break;case oe.CODE_CODE_A:m=oe.CODE_CODE_A;break;case oe.CODE_CODE_C:m=oe.CODE_CODE_C;break;case oe.CODE_STOP:y=!0;break}break;case oe.CODE_CODE_C:if(ne<100)ne<10&&(I+="0"),I+=ne;else switch(ne!==oe.CODE_STOP&&(ue=!1),ne){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_CODE_A:m=oe.CODE_CODE_A;break;case oe.CODE_CODE_B:m=oe.CODE_CODE_B;break;case oe.CODE_STOP:y=!0;break}break}br&&(m=m===oe.CODE_CODE_A?oe.CODE_CODE_B:oe.CODE_CODE_A)}const Qt=F-R;if(F=n.getNextUnset(F),!n.isRange(F,Math.min(n.getSize(),F+(F-R)/2),!1))throw new D;if(me-=xe*q,me%103!==q)throw new O;const gn=I.length;if(gn===0)throw new D;gn>0&&ue&&(m===oe.CODE_CODE_C?I=I.substring(0,gn-2):I=I.substring(0,gn-1));const en=(a[1]+a[0])/2,at=R+Qt/2,zt=h.length,rn=new Uint8Array(zt);for(let br=0;br<zt;br++)rn[br]=h[br];const Cr=[new T(en,e),new T(at,e)];return new Me(I,rn,0,Cr,ie.CODE_128,new Date().getTime())}}oe.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])],oe.MAX_AVG_VARIANCE=.25,oe.MAX_INDIVIDUAL_VARIANCE=.7,oe.CODE_SHIFT=98,oe.CODE_CODE_C=99,oe.CODE_CODE_B=100,oe.CODE_CODE_A=101,oe.CODE_FNC_1=102,oe.CODE_FNC_2=97,oe.CODE_FNC_3=96,oe.CODE_FNC_4_A=101,oe.CODE_FNC_4_B=100,oe.CODE_START_A=103,oe.CODE_START_B=104,oe.CODE_START_C=105,oe.CODE_STOP=106;class Re extends Ie{constructor(e=!1,n=!1){super(),this.usingCheckDigit=e,this.extendedMode=n,this.decodeRowResult="",this.counters=new Int32Array(9)}decodeRow(e,n,i){let s=this.counters;s.fill(0),this.decodeRowResult="";let a=Re.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,m;do{Re.recordPattern(n,l,s);let U=Re.toNarrowWidePattern(s);if(U<0)throw new D;h=Re.patternToChar(U),this.decodeRowResult+=h,m=l;for(let q of s)l+=q;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let U of s)y+=U;let E=l-m-y;if(l!==d&&E*2<y)throw new D;if(this.usingCheckDigit){let U=this.decodeRowResult.length-1,q=0;for(let ne=0;ne<U;ne++)q+=Re.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(ne));if(this.decodeRowResult.charAt(U)!==Re.ALPHABET_STRING.charAt(q%43))throw new O;this.decodeRowResult=this.decodeRowResult.substring(0,U)}if(this.decodeRowResult.length===0)throw new D;let I;this.extendedMode?I=Re.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let R=(a[1]+a[0])/2,F=m+y/2;return new Me(I,null,0,[new T(R,e),new T(F,e)],ie.CODE_39,new Date().getTime())}static findAsteriskPattern(e,n){let i=e.getSize(),s=e.getNextSet(0),a=0,l=s,d=!1,h=n.length;for(let m=s;m<i;m++)if(e.get(m)!==d)n[a]++;else{if(a===h-1){if(this.toNarrowWidePattern(n)===Re.ASTERISK_ENCODING&&e.isRange(Math.max(0,l-Math.floor((m-l)/2)),l,!1))return[l,m];l+=n[0]+n[1],n.copyWithin(0,2,2+a-1),n[a-1]=0,n[a]=0,a--}else a++;n[a]=1,d=!d}throw new D}static toNarrowWidePattern(e){let n=e.length,i=0,s;do{let a=2147483647;for(let h of e)h<a&&h>i&&(a=h);i=a,s=0;let l=0,d=0;for(let h=0;h<n;h++){let m=e[h];m>i&&(d|=1<<n-1-h,s++,l+=m)}if(s===3){for(let h=0;h<n&&s>0;h++){let m=e[h];if(m>i&&(s--,m*2>=l))return-1}return d}}while(s>3);return-1}static patternToChar(e){for(let n=0;n<Re.CHARACTER_ENCODINGS.length;n++)if(Re.CHARACTER_ENCODINGS[n]===e)return Re.ALPHABET_STRING.charAt(n);if(e===Re.ASTERISK_ENCODING)return"*";throw new D}static decodeExtended(e){let n=e.length,i="";for(let s=0;s<n;s++){let a=e.charAt(s);if(a==="+"||a==="$"||a==="%"||a==="/"){let l=e.charAt(s+1),d="\0";switch(a){case"+":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)+32);else throw new V;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new V;break;case"%":if(l>="A"&&l<="E")d=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")d=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")d=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")d="\0";else if(l==="V")d="@";else if(l==="W")d="`";else if(l==="X"||l==="Y"||l==="Z")d="";else throw new V;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new V;break}i+=d,s++}else i+=a}return i}}Re.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",Re.CHARACTER_ENCODINGS=[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,168,162,138,42],Re.ASTERISK_ENCODING=148;class qe extends Ie{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new ae;qe.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(j.ALLOWED_LENGTHS)),h==null&&(h=qe.DEFAULT_ALLOWED_LENGTHS);let m=d.length,y=!1,E=0;for(let F of h){if(m===F){y=!0;break}F>E&&(E=F)}if(!y&&m>E&&(y=!0),!y)throw new V;const I=[new T(s[1],e),new T(a[0],e)];return new Me(d,null,0,I,ie.ITF,new Date().getTime())}static decodeMiddle(e,n,i,s){let a=new Int32Array(10),l=new Int32Array(5),d=new Int32Array(5);for(a.fill(0),l.fill(0),d.fill(0);n<i;){Ie.recordPattern(e,n,a);for(let m=0;m<5;m++){let y=2*m;l[m]=a[y],d[m]=a[y+1]}let h=qe.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(m){n+=m})}}decodeStart(e){let n=qe.skipWhiteSpace(e),i=qe.findGuardPattern(e,n,qe.START_PATTERN);return this.narrowLineWidth=(i[1]-i[0])/4,this.validateQuietZone(e,i[0]),i}validateQuietZone(e,n){let i=this.narrowLineWidth*10;i=i<n?i:n;for(let s=n-1;i>0&&s>=0&&!e.get(s);s--)i--;if(i!==0)throw new D}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new D;return i}decodeEnd(e){e.reverse();try{let n=qe.skipWhiteSpace(e),i;try{i=qe.findGuardPattern(e,n,qe.END_PATTERN_REVERSED[0])}catch(a){a instanceof D&&(i=qe.findGuardPattern(e,n,qe.END_PATTERN_REVERSED[1]))}this.validateQuietZone(e,i[0]);let s=i[0];return i[0]=e.getSize()-i[1],i[1]=e.getSize()-s,i}finally{e.reverse()}}static findGuardPattern(e,n,i){let s=i.length,a=new Int32Array(s),l=e.getSize(),d=!1,h=0,m=n;a.fill(0);for(let y=n;y<l;y++)if(e.get(y)!==d)a[h]++;else{if(h===s-1){if(Ie.patternMatchVariance(a,i,qe.MAX_INDIVIDUAL_VARIANCE)<qe.MAX_AVG_VARIANCE)return[m,y];m+=a[0]+a[1],P.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,d=!d}throw new D}static decodeDigit(e){let n=qe.MAX_AVG_VARIANCE,i=-1,s=qe.PATTERNS.length;for(let a=0;a<s;a++){let l=qe.PATTERNS[a],d=Ie.patternMatchVariance(e,l,qe.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new D}}qe.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])],qe.MAX_AVG_VARIANCE=.38,qe.MAX_INDIVIDUAL_VARIANCE=.5,qe.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],qe.START_PATTERN=Int32Array.from([1,1,1,1]),qe.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class pt extends Ie{constructor(){super(...arguments),this.decodeRowStringBuffer=""}static findStartGuardPattern(e){let n=!1,i,s=0,a=Int32Array.from([0,0,0]);for(;!n;){a=Int32Array.from([0,0,0]),i=pt.findGuardPattern(e,s,!1,this.START_END_PATTERN,a);let l=i[0];s=i[1];let d=l-(s-l);d>=0&&(n=e.isRange(d,l,!1))}return i}static checkChecksum(e){return pt.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return pt.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return pt.findGuardPattern(e,n,!1,pt.START_END_PATTERN,new Int32Array(pt.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,i,s){return this.findGuardPattern(e,n,i,s,new Int32Array(s.length))}static findGuardPattern(e,n,i,s,a){let l=e.getSize();n=i?e.getNextUnset(n):e.getNextSet(n);let d=0,h=n,m=s.length,y=i;for(let E=n;E<l;E++)if(e.get(E)!==y)a[d]++;else{if(d===m-1){if(Ie.patternMatchVariance(a,s,pt.MAX_INDIVIDUAL_VARIANCE)<pt.MAX_AVG_VARIANCE)return Int32Array.from([h,E]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let R=0;R<d-1;R++)a[R]=I[R];a[d-1]=0,a[d]=0,d--}else d++;a[d]=1,y=!y}throw new D}static decodeDigit(e,n,i,s){this.recordPattern(e,i,n);let a=this.MAX_AVG_VARIANCE,l=-1,d=s.length;for(let h=0;h<d;h++){let m=s[h],y=Ie.patternMatchVariance(n,m,pt.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new D}}pt.MAX_AVG_VARIANCE=.48,pt.MAX_INDIVIDUAL_VARIANCE=.7,pt.START_END_PATTERN=Int32Array.from([1,1,1]),pt.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),pt.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),pt.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])];class Or{constructor(){this.CHECK_DIGIT_ENCODINGS=[24,20,18,17,12,6,3,10,9,5],this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=Or.parseExtensionString(l),h=[new T((i[0]+i[1])/2,e),new T(a,e)],m=new Me(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&m.putAllMetadata(d),m}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let m=0;m<5&&l<a;m++){let y=pt.decodeDigit(e,s,l,pt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<4-m),m!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new D;let h=this.determineCheckDigit(d);if(Or.extensionChecksum(i.toString())!==h)throw new D;return l}static extensionChecksum(e){let n=e.length,i=0;for(let s=n-2;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;i*=3;for(let s=n-1;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;return i*=3,i%10}determineCheckDigit(e){for(let n=0;n<10;n++)if(e===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new D}static parseExtensionString(e){if(e.length!==5)return null;let n=Or.parseExtension5String(e);return n==null?null:new Map([[Ae.SUGGESTED_PRICE,n]])}static parseExtension5String(e){let n;switch(e.charAt(0)){case"0":n="£";break;case"5":n="$";break;case"9":switch(e){case"90000":return null;case"99991":return"0.00";case"99990":return"Used"}n="";break;default:n="";break}let i=parseInt(e.substring(1)),s=(i/100).toString(),a=i%100,l=a<10?"0"+a:a.toString();return n+s+"."+l}}class Hi{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=Hi.parseExtensionString(l),h=[new T((i[0]+i[1])/2,e),new T(a,e)],m=new Me(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&m.putAllMetadata(d),m}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let h=0;h<2&&l<a;h++){let m=pt.decodeDigit(e,s,l,pt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+m%10);for(let y of s)l+=y;m>=10&&(d|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==2)throw new D;if(parseInt(i.toString())%4!==d)throw new D;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ae.ISSUE_NUMBER,parseInt(e)]])}}class cs{static decodeRow(e,n,i){let s=pt.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new Or().decodeRow(e,n,s)}catch{return new Hi().decodeRow(e,n,s)}}}cs.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ke extends pt{constructor(){super(),this.decodeRowStringBuffer="",Ke.L_AND_G_PATTERNS=Ke.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=Ke.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];Ke.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=Ke.findStartGuardPattern(n),a=i==null?null:i.get(j.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ue=new T((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ue)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),d=l.rowOffset,h=l.resultString;if(a!=null){const ue=new T(d,e);a.foundPossibleResultPoint(ue)}let m=this.decodeEnd(n,d);if(a!=null){const ue=new T((m[0]+m[1])/2,e);a.foundPossibleResultPoint(ue)}let y=m[1],E=y+(y-m[0]);if(E>=n.getSize()||!n.isRange(y,E,!1))throw new D;let I=h.toString();if(I.length<8)throw new V;if(!Ke.checkChecksum(I))throw new O;let R=(s[1]+s[0])/2,F=(m[1]+m[0])/2,U=this.getBarcodeFormat(),q=[new T(R,e),new T(F,e)],ne=new Me(I,null,0,q,U,new Date().getTime()),me=0;try{let ue=cs.decodeRow(e,n,m[1]);ne.putMetadata(Ae.UPC_EAN_EXTENSION,ue.getText()),ne.putAllMetadata(ue.getResultMetadata()),ne.addResultPoints(ue.getResultPoints()),me=ue.getText().length}catch{}let xe=i==null?null:i.get(j.ALLOWED_EAN_EXTENSIONS);if(xe!=null){let ue=!1;for(let We in xe)if(me.toString()===We){ue=!0;break}if(!ue)throw new D}return ne}decodeEnd(e,n){return Ke.findGuardPattern(e,n,!1,Ke.START_END_PATTERN,new Int32Array(Ke.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return Ke.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return Ke.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}return(1e3-i)%10}}class Qn extends Ke{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let m=0;m<6&&l<a;m++){let y=Ke.decodeDigit(e,s,l,Ke.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-m)}i=Qn.determineFirstDigit(i,d),l=Ke.findGuardPattern(e,l,!0,Ke.MIDDLE_PATTERN,new Int32Array(Ke.MIDDLE_PATTERN.length).fill(0))[1];for(let m=0;m<6&&l<a;m++){let y=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+y);for(let E of s)l+=E}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return ie.EAN_13}static determineFirstDigit(e,n){for(let i=0;i<10;i++)if(n===this.FIRST_DIGIT_ENCODINGS[i])return e=String.fromCharCode(48+i)+e,e;throw new D}}Qn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class us extends Ke{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1];for(let h=0;h<4&&l<a;h++){let m=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+m);for(let y of s)l+=y}l=Ke.findGuardPattern(e,l,!0,Ke.MIDDLE_PATTERN,new Int32Array(Ke.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let m=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+m);for(let y of s)l+=y}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return ie.EAN_8}}class ds extends Ke{constructor(){super(...arguments),this.ean13Reader=new Qn}getBarcodeFormat(){return ie.UPC_A}decode(e,n){return this.maybeReturnResult(this.ean13Reader.decode(e))}decodeRow(e,n,i){return this.maybeReturnResult(this.ean13Reader.decodeRow(e,n,i))}decodeMiddle(e,n,i){return this.ean13Reader.decodeMiddle(e,n,i)}maybeReturnResult(e){let n=e.getText();if(n.charAt(0)==="0"){let i=new Me(n.substring(1),null,null,e.getResultPoints(),ie.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new D}reset(){this.ean13Reader.reset()}}class mn extends Ke{constructor(){super(),this.decodeMiddleCounters=new Int32Array(4)}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters.map(m=>m);s[0]=0,s[1]=0,s[2]=0,s[3]=0;const a=e.getSize();let l=n[1],d=0;for(let m=0;m<6&&l<a;m++){const y=mn.decodeDigit(e,s,l,mn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-m)}let h=mn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return mn.findGuardPatternWithoutCounters(e,n,!0,mn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ke.checkChecksum(mn.convertUPCEtoUPCA(e))}static determineNumSysAndCheckDigit(e,n){for(let i=0;i<=1;i++)for(let s=0;s<10;s++)if(n===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[i][s]){let a=String.fromCharCode(48+i),l=String.fromCharCode(48+s);return a+e+l}throw D.getNotFoundInstance()}getBarcodeFormat(){return ie.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new ae;i.append(e.charAt(0));let s=n[5];switch(s){case 0:case 1:case 2:i.appendChars(n,0,2),i.append(s),i.append("0000"),i.appendChars(n,2,3);break;case 3:i.appendChars(n,0,3),i.append("00000"),i.appendChars(n,3,2);break;case 4:i.appendChars(n,0,4),i.append("00000"),i.append(n[4]);break;default:i.appendChars(n,0,5),i.append("0000"),i.append(s);break}return e.length>=8&&i.append(e.charAt(7)),i.toString()}}mn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),mn.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([56,52,50,49,44,38,35,42,41,37]),Int32Array.from([7,11,13,14,19,25,28,21,22,26])];class Gi extends Ie{constructor(e){super();let n=e==null?null:e.get(j.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new Qn),i.push(new ds),i.push(new us),i.push(new mn)):(n.indexOf(ie.EAN_13)>-1&&i.push(new Qn),n.indexOf(ie.UPC_A)>-1&&i.push(new ds),n.indexOf(ie.EAN_8)>-1&&i.push(new us),n.indexOf(ie.UPC_E)>-1&&i.push(new mn)),this.readers=i}decodeRow(e,n,i){for(let s of this.readers)try{const a=s.decodeRow(e,n,i),l=a.getBarcodeFormat()===ie.EAN_13&&a.getText().charAt(0)==="0",d=i==null?null:i.get(j.POSSIBLE_FORMATS),h=d==null||d.includes(ie.UPC_A);if(l&&h){const m=a.getRawBytes(),y=new Me(a.getText().substring(1),m,m?m.length:null,a.getResultPoints(),ie.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new D}reset(){for(let e of this.readers)e.reset()}}class Zt extends Ie{constructor(){super(),this.decodeFinderCounters=new Int32Array(4),this.dataCharacterCounters=new Int32Array(8),this.oddRoundingErrors=new Array(4),this.evenRoundingErrors=new Array(4),this.oddCounts=new Array(this.dataCharacterCounters.length/2),this.evenCounts=new Array(this.dataCharacterCounters.length/2)}getDecodeFinderCounters(){return this.decodeFinderCounters}getDataCharacterCounters(){return this.dataCharacterCounters}getOddRoundingErrors(){return this.oddRoundingErrors}getEvenRoundingErrors(){return this.evenRoundingErrors}getOddCounts(){return this.oddCounts}getEvenCounts(){return this.evenCounts}parseFinderValue(e,n){for(let i=0;i<n.length;i++)if(Ie.patternMatchVariance(e,n[i],Zt.MAX_INDIVIDUAL_VARIANCE)<Zt.MAX_AVG_VARIANCE)return i;throw new D}static count(e){return je.sum(new Int32Array(e))}static increment(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],i=a);e[i]++}static decrement(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],i=a);e[i]--}static isFinderPattern(e){let n=e[0]+e[1],i=n+e[2]+e[3],s=n/i;if(s>=Zt.MIN_FINDER_PATTERN_RATIO&&s<=Zt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let d of e)d>l&&(l=d),d<a&&(a=d);return l<10*a}return!1}}Zt.MAX_AVG_VARIANCE=.2,Zt.MAX_INDIVIDUAL_VARIANCE=.45,Zt.MIN_FINDER_PATTERN_RATIO=9.5/12,Zt.MAX_FINDER_PATTERN_RATIO=12.5/14;class mr{constructor(e,n){this.value=e,this.checksumPortion=n}getValue(){return this.value}getChecksumPortion(){return this.checksumPortion}toString(){return this.value+"("+this.checksumPortion+")"}equals(e){if(!(e instanceof mr))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class ci{constructor(e,n,i,s,a){this.value=e,this.startEnd=n,this.value=e,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new T(i,a)),this.resultPoints.push(new T(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof ci))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class In{constructor(){}static getRSSvalue(e,n,i){let s=0;for(let h of e)s+=h;let a=0,l=0,d=e.length;for(let h=0;h<d-1;h++){let m;for(m=1,l|=1<<h;m<e[h];m++,l&=~(1<<h)){let y=In.combins(s-m-1,d-h-2);if(i&&l===0&&s-m-(d-h-1)>=d-h-1&&(y-=In.combins(s-m-(d-h),d-h-2)),d-h-1>1){let E=0;for(let I=s-m-(d-h-2);I>n;I--)E+=In.combins(s-m-I-1,d-h-3);y-=E*(d-1-h)}else s-m>n&&y--;a+=y}s-=m}return a}static combins(e,n){let i,s;e-n>n?(s=n,i=e-n):(s=e-n,i=n);let a=1,l=1;for(let d=e;d>i;d--)a*=d,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Ju{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new H(i),a=0,d=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(d&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let m=e[h],y=m.getLeftChar().getValue();for(let E=11;E>=0;--E)(y&1<<E)!=0&&s.set(a),a++;if(m.getRightChar()!=null){let E=m.getRightChar().getValue();for(let I=11;I>=0;--I)(E&1<<I)!=0&&s.set(a),a++}}return s}}class er{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class Xi{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class Yt extends Xi{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Yt.FNC1}}Yt.FNC1="$";class tr extends Xi{constructor(e,n,i){super(e),i?(this.remaining=!0,this.remainingValue=this.remainingValue):(this.remaining=!1,this.remainingValue=0),this.newString=n}getNewString(){return this.newString}isRemaining(){return this.remaining}getRemainingValue(){return this.remainingValue}}class un extends Xi{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new V;this.firstDigit=n,this.secondDigit=i}getFirstDigit(){return this.firstDigit}getSecondDigit(){return this.secondDigit}getValue(){return this.firstDigit*10+this.secondDigit}isFirstDigitFNC1(){return this.firstDigit===un.FNC1}isSecondDigitFNC1(){return this.secondDigit===un.FNC1}isAnyFNC1(){return this.firstDigit===un.FNC1||this.secondDigit===un.FNC1}}un.FNC1=10;class _e{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new D;let n=e.substring(0,2);for(let a of _e.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(2,a[2],e):_e.processFixedAI(2,a[1],e);if(e.length<3)throw new D;let i=e.substring(0,3);for(let a of _e.THREE_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(3,a[2],e):_e.processFixedAI(3,a[1],e);for(let a of _e.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(4,a[2],e):_e.processFixedAI(4,a[1],e);if(e.length<4)throw new D;let s=e.substring(0,4);for(let a of _e.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(4,a[2],e):_e.processFixedAI(4,a[1],e);throw new D}static processFixedAI(e,n,i){if(i.length<e)throw new D;let s=i.substring(0,e);if(i.length<e+n)throw new D;let a=i.substring(e,e+n),l=i.substring(e+n),d="("+s+")"+a,h=_e.parseFieldsInGeneralPurpose(l);return h==null?d:d+h}static processVariableAI(e,n,i){let s=i.substring(0,e),a;i.length<e+n?a=i.length:a=e+n;let l=i.substring(e,a),d=i.substring(a),h="("+s+")"+l,m=_e.parseFieldsInGeneralPurpose(d);return m==null?h:h+m}}_e.VARIABLE_LENGTH=[],_e.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",_e.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",_e.VARIABLE_LENGTH,20],["22",_e.VARIABLE_LENGTH,29],["30",_e.VARIABLE_LENGTH,8],["37",_e.VARIABLE_LENGTH,8],["90",_e.VARIABLE_LENGTH,30],["91",_e.VARIABLE_LENGTH,30],["92",_e.VARIABLE_LENGTH,30],["93",_e.VARIABLE_LENGTH,30],["94",_e.VARIABLE_LENGTH,30],["95",_e.VARIABLE_LENGTH,30],["96",_e.VARIABLE_LENGTH,30],["97",_e.VARIABLE_LENGTH,3],["98",_e.VARIABLE_LENGTH,30],["99",_e.VARIABLE_LENGTH,30]],_e.THREE_DIGIT_DATA_LENGTH=[["240",_e.VARIABLE_LENGTH,30],["241",_e.VARIABLE_LENGTH,30],["242",_e.VARIABLE_LENGTH,6],["250",_e.VARIABLE_LENGTH,30],["251",_e.VARIABLE_LENGTH,30],["253",_e.VARIABLE_LENGTH,17],["254",_e.VARIABLE_LENGTH,20],["400",_e.VARIABLE_LENGTH,30],["401",_e.VARIABLE_LENGTH,30],["402",17],["403",_e.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",_e.VARIABLE_LENGTH,20],["421",_e.VARIABLE_LENGTH,15],["422",3],["423",_e.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],_e.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=[["310",6],["311",6],["312",6],["313",6],["314",6],["315",6],["316",6],["320",6],["321",6],["322",6],["323",6],["324",6],["325",6],["326",6],["327",6],["328",6],["329",6],["330",6],["331",6],["332",6],["333",6],["334",6],["335",6],["336",6],["340",6],["341",6],["342",6],["343",6],["344",6],["345",6],["346",6],["347",6],["348",6],["349",6],["350",6],["351",6],["352",6],["353",6],["354",6],["355",6],["356",6],["357",6],["360",6],["361",6],["362",6],["363",6],["364",6],["365",6],["366",6],["367",6],["368",6],["369",6],["390",_e.VARIABLE_LENGTH,15],["391",_e.VARIABLE_LENGTH,18],["392",_e.VARIABLE_LENGTH,15],["393",_e.VARIABLE_LENGTH,18],["703",_e.VARIABLE_LENGTH,30]],_e.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",_e.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",_e.VARIABLE_LENGTH,20],["8003",_e.VARIABLE_LENGTH,30],["8004",_e.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",_e.VARIABLE_LENGTH,30],["8008",_e.VARIABLE_LENGTH,12],["8018",18],["8020",_e.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",_e.VARIABLE_LENGTH,70],["8200",_e.VARIABLE_LENGTH,70]];class gr{constructor(e){this.buffer=new ae,this.information=e}decodeAllCodes(e,n){let i=n,s=null;do{let a=this.decodeGeneralPurposeField(i,s),l=_e.parseFieldsInGeneralPurpose(a.getNewString());if(l!=null&&e.append(l),a.isRemaining()?s=""+a.getRemainingValue():s=null,i===a.getNewPosition())break;i=a.getNewPosition()}while(!0);return e.toString()}isStillNumeric(e){if(e+7>this.information.getSize())return e+4<=this.information.getSize();for(let n=e;n<e+3;++n)if(this.information.get(n))return!0;return this.information.get(e+3)}decodeNumeric(e){if(e+7>this.information.getSize()){let a=this.extractNumericValueFromBitArray(e,4);return a===0?new un(this.information.getSize(),un.FNC1,un.FNC1):new un(this.information.getSize(),a-1,un.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new un(e+7,i,s)}extractNumericValueFromBitArray(e,n){return gr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,i){let s=0;for(let a=0;a<i;++a)e.get(n+a)&&(s|=1<<i-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let i=this.parseBlocks();return i!=null&&i.isRemaining()?new tr(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new tr(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let i=this.current.getPosition();if(this.current.isAlpha()?(n=this.parseAlphaBlock(),e=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),e=n.isFinished()):(n=this.parseNumericBlock(),e=n.isFinished()),!(i!==this.current.getPosition())&&!e)break}while(!e);return n.getDecodedInformation()}parseNumericBlock(){for(;this.isStillNumeric(this.current.getPosition());){let e=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFirstDigitFNC1()){let n;return e.isSecondDigitFNC1()?n=new tr(this.current.getPosition(),this.buffer.toString()):n=new tr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new er(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new er(!1)}parseIsoIec646Block(){for(;this.isStillIsoIec646(this.current.getPosition());){let e=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new er(!1)}parseAlphaBlock(){for(;this.isStillAlpha(this.current.getPosition());){let e=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new er(!1)}isStillIsoIec646(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+7>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<116)return!0;if(e+8>this.information.getSize())return!1;let s=this.extractNumericValueFromBitArray(e,8);return s>=232&&s<253}decodeIsoIec646(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Yt(e+5,Yt.FNC1);if(n>=5&&n<15)return new Yt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new Yt(e+7,""+(i+1));if(i>=90&&i<116)return new Yt(e+7,""+(i+7));let s=this.extractNumericValueFromBitArray(e,8),a;switch(s){case 232:a="!";break;case 233:a='"';break;case 234:a="%";break;case 235:a="&";break;case 236:a="'";break;case 237:a="(";break;case 238:a=")";break;case 239:a="*";break;case 240:a="+";break;case 241:a=",";break;case 242:a="-";break;case 243:a=".";break;case 244:a="/";break;case 245:a=":";break;case 246:a=";";break;case 247:a="<";break;case 248:a="=";break;case 249:a=">";break;case 250:a="?";break;case 251:a="_";break;case 252:a=" ";break;default:throw new V}return new Yt(e+8,a)}isStillAlpha(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+6>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,6);return i>=16&&i<63}decodeAlphanumeric(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Yt(e+5,Yt.FNC1);if(n>=5&&n<15)return new Yt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new Yt(e+6,""+(i+33));let s;switch(i){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new Vt("Decoding invalid alphanumeric value: "+i)}return new Yt(e+6,s)}isAlphaTo646ToAlphaLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<5&&n+e<this.information.getSize();++n)if(n===2){if(!this.information.get(e+2))return!1}else if(this.information.get(e+n))return!1;return!0}isAlphaOr646ToNumericLatch(e){if(e+3>this.information.getSize())return!1;for(let n=e;n<e+3;++n)if(this.information.get(n))return!1;return!0}isNumericToAlphaNumericLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<4&&n+e<this.information.getSize();++n)if(this.information.get(e+n))return!1;return!0}}class qi{constructor(e){this.information=e,this.generalDecoder=new gr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class Jt extends qi{constructor(e){super(e)}encodeCompressedGtin(e,n){e.append("(01)");let i=e.length();e.append("9"),this.encodeCompressedGtinWithoutAI(e,n,i)}encodeCompressedGtinWithoutAI(e,n,i){for(let s=0;s<4;++s){let a=this.getGeneralDecoder().extractNumericValueFromBitArray(n+10*s,10);a/100===0&&e.append("0"),a/10===0&&e.append("0"),e.append(a)}Jt.appendCheckDigit(e,i)}static appendCheckDigit(e,n){let i=0;for(let s=0;s<13;s++){let a=e.charAt(s+n).charCodeAt(0)-48;i+=(s&1)===0?3*a:a}i=10-i%10,i===10&&(i=0),e.append(i)}}Jt.GTIN_SIZE=40;class xr extends Jt{constructor(e){super(e)}parseInformation(){let e=new ae;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(xr.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,xr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,xr.HEADER_SIZE+44)}}xr.HEADER_SIZE=4;class ui extends qi{constructor(e){super(e)}parseInformation(){let e=new ae;return this.getGeneralDecoder().decodeAllCodes(e,ui.HEADER_SIZE)}}ui.HEADER_SIZE=5;class di extends Jt{constructor(e){super(e)}encodeCompressedWeight(e,n,i){let s=this.getGeneralDecoder().extractNumericValueFromBitArray(n,i);this.addWeightCode(e,s);let a=this.checkWeight(s),l=1e5;for(let d=0;d<5;++d)a/l===0&&e.append("0"),l/=10;e.append(a)}}class Sn extends di{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Sn.HEADER_SIZE+di.GTIN_SIZE+Sn.WEIGHT_SIZE)throw new D;let e=new ae;return this.encodeCompressedGtin(e,Sn.HEADER_SIZE),this.encodeCompressedWeight(e,Sn.HEADER_SIZE+di.GTIN_SIZE,Sn.WEIGHT_SIZE),e.toString()}}Sn.HEADER_SIZE=5,Sn.WEIGHT_SIZE=15;class Ku extends Sn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Qu extends Sn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class Tn extends Jt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Tn.HEADER_SIZE+Jt.GTIN_SIZE)throw new D;let e=new ae;this.encodeCompressedGtin(e,Tn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Tn.HEADER_SIZE+Jt.GTIN_SIZE,Tn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(Tn.HEADER_SIZE+Jt.GTIN_SIZE+Tn.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}Tn.HEADER_SIZE=8,Tn.LAST_DIGIT_SIZE=2;class Gt extends Jt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Gt.HEADER_SIZE+Jt.GTIN_SIZE)throw new D;let e=new ae;this.encodeCompressedGtin(e,Gt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Gt.HEADER_SIZE+Jt.GTIN_SIZE,Gt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(Gt.HEADER_SIZE+Jt.GTIN_SIZE+Gt.LAST_DIGIT_SIZE,Gt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Gt.HEADER_SIZE+Jt.GTIN_SIZE+Gt.LAST_DIGIT_SIZE+Gt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Gt.HEADER_SIZE=8,Gt.LAST_DIGIT_SIZE=2,Gt.FIRST_THREE_DIGITS_SIZE=10;class mt extends di{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=mt.HEADER_SIZE+mt.GTIN_SIZE+mt.WEIGHT_SIZE+mt.DATE_SIZE)throw new D;let e=new ae;return this.encodeCompressedGtin(e,mt.HEADER_SIZE),this.encodeCompressedWeight(e,mt.HEADER_SIZE+mt.GTIN_SIZE,mt.WEIGHT_SIZE),this.encodeCompressedDate(e,mt.HEADER_SIZE+mt.GTIN_SIZE+mt.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,mt.DATE_SIZE);if(i==38400)return;e.append("("),e.append(this.dateCode),e.append(")");let s=i%32;i/=32;let a=i%12+1;i/=12;let l=i;l/10==0&&e.append("0"),e.append(l),a/10==0&&e.append("0"),e.append(a),s/10==0&&e.append("0"),e.append(s)}addWeightCode(e,n){e.append("("),e.append(this.firstAIdigits),e.append(n/1e5),e.append(")")}checkWeight(e){return e%1e5}}mt.HEADER_SIZE=8,mt.WEIGHT_SIZE=20,mt.DATE_SIZE=16;function fs(b){try{if(b.get(1))return new xr(b);if(!b.get(2))return new ui(b);switch(gr.extractNumericValueFromBitArray(b,1,4)){case 4:return new Ku(b);case 5:return new Qu(b)}switch(gr.extractNumericValueFromBitArray(b,1,5)){case 12:return new Tn(b);case 13:return new Gt(b)}switch(gr.extractNumericValueFromBitArray(b,1,7)){case 56:return new mt(b,"310","11");case 57:return new mt(b,"320","11");case 58:return new mt(b,"310","13");case 59:return new mt(b,"320","13");case 60:return new mt(b,"310","15");case 61:return new mt(b,"320","15");case 62:return new mt(b,"310","17");case 63:return new mt(b,"320","17")}}catch(e){throw console.log(e),new Vt("unknown decoder: "+b)}}class zn{constructor(e,n,i,s){this.leftchar=e,this.rightchar=n,this.finderpattern=i,this.maybeLast=s}mayBeLast(){return this.maybeLast}getLeftChar(){return this.leftchar}getRightChar(){return this.rightchar}getFinderPattern(){return this.finderpattern}mustBeLast(){return this.rightchar==null}toString(){return"[ "+this.leftchar+", "+this.rightchar+" : "+(this.finderpattern==null?"null":this.finderpattern.getValue())+" ]"}static equals(e,n){return e instanceof zn?zn.equalsOrNull(e.leftchar,n.leftchar)&&zn.equalsOrNull(e.rightchar,n.rightchar)&&zn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:zn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Yi{constructor(e,n,i){this.pairs=e,this.rowNumber=n,this.wasReversed=i}getPairs(){return this.pairs}getRowNumber(){return this.rowNumber}isReversed(){return this.wasReversed}isEquivalent(e){return this.checkEqualitity(this,e)}toString(){return"{ "+this.pairs+" }"}equals(e,n){return e instanceof Yi?this.checkEqualitity(e,n)&&e.wasReversed===n.wasReversed:!1}checkEqualitity(e,n){if(!e||!n)return;let i;return e.forEach((s,a)=>{n.forEach(l=>{s.getLeftChar().getValue()===l.getLeftChar().getValue()&&s.getRightChar().getValue()===l.getRightChar().getValue()&&s.getFinderPatter().getValue()===l.getFinderPatter().getValue()&&(i=!0)})}),i}}class ce extends Zt{constructor(e){super(...arguments),this.pairs=new Array(ce.MAX_PAIRS),this.rows=new Array,this.startEnd=[2],this.verbose=e===!0}decodeRow(e,n,i){this.pairs.length=0,this.startFromEven=!1;try{return ce.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,ce.constructResult(this.decodeRow2pairs(e,n))}reset(){this.pairs.length=0,this.rows.length=0}decodeRow2pairs(e,n){let i=!1;for(;!i;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof D){if(!this.pairs.length)throw new D;i=!0}}if(this.checkChecksum())return this.pairs;let s;if(this.rows.length?s=!0:s=!1,this.storeRow(e,!1),s){let a=this.checkRowsBoolean(!1);if(a!=null||(a=this.checkRowsBoolean(!0),a!=null))return a}throw new D}checkRowsBoolean(e){if(this.rows.length>25)return this.rows.length=0,null;this.pairs.length=0,e&&(this.rows=this.rows.reverse());let n=null;try{n=this.checkRows(new Array,0)}catch(i){this.verbose&&console.log(i)}return e&&(this.rows=this.rows.reverse()),n}checkRows(e,n){for(let i=n;i<this.rows.length;i++){let s=this.rows[i];this.pairs.length=0;for(let l of e)this.pairs.push(l.getPairs());if(this.pairs.push(s.getPairs()),!ce.isValidSequence(this.pairs))continue;if(this.checkChecksum())return this.pairs;let a=new Array(e);a.push(s);try{return this.checkRows(a,i+1)}catch(l){this.verbose&&console.log(l)}}throw new D}static isValidSequence(e){for(let n of ce.FINDER_PATTERN_SEQUENCES){if(e.length>n.length)continue;let i=!0;for(let s=0;s<e.length;s++)if(e[s].getFinderPattern().getValue()!=n[s]){i=!1;break}if(i)return!0}return!1}storeRow(e,n){let i=0,s=!1,a=!1;for(;i<this.rows.length;){let l=this.rows[i];if(l.getRowNumber()>e){a=l.isEquivalent(this.pairs);break}s=l.isEquivalent(this.pairs),i++}a||s||ce.isPartialRow(this.pairs,this.rows)||(this.rows.push(i,new Yi(this.pairs,e,n)),this.removePartialRows(this.pairs,this.rows))}removePartialRows(e,n){for(let i of n)if(i.getPairs().length!==e.length){for(let s of i.getPairs())for(let a of e)if(zn.equals(s,a))break}}static isPartialRow(e,n){for(let i of n){let s=!0;for(let a of e){let l=!1;for(let d of i.getPairs())if(a.equals(d)){l=!0;break}if(!l){s=!1;break}}if(s)return!0}return!1}getRows(){return this.rows}static constructResult(e){let n=Ju.buildBitArray(e),s=fs(n).parseInformation(),a=e[0].getFinderPattern().getResultPoints(),l=e[e.length-1].getFinderPattern().getResultPoints(),d=[a[0],a[1],l[0],l[1]];return new Me(s,null,null,d,ie.RSS_EXPANDED,null)}checkChecksum(){let e=this.pairs.get(0),n=e.getLeftChar(),i=e.getRightChar();if(i==null)return!1;let s=i.getChecksumPortion(),a=2;for(let d=1;d<this.pairs.size();++d){let h=this.pairs.get(d);s+=h.getLeftChar().getChecksumPortion(),a++;let m=h.getRightChar();m!=null&&(s+=m.getChecksumPortion(),a++)}return s%=211,211*(a-4)+s==n.getValue()}static getNextSecondBar(e,n){let i;return e.get(n)?(i=e.getNextUnset(n),i=e.getNextSet(i)):(i=e.getNextSet(n),i=e.getNextUnset(i)),i}retrieveNextPair(e,n,i){let s=n.length%2==0;this.startFromEven&&(s=!s);let a,l=!0,d=-1;do this.findNextPair(e,n,d),a=this.parseFoundFinderPattern(e,i,s),a==null?d=ce.getNextSecondBar(e,this.startEnd[0]):l=!1;while(l);let h=this.decodeDataCharacter(e,a,s,!0);if(!this.isEmptyPair(n)&&n[n.length-1].mustBeLast())throw new D;let m;try{m=this.decodeDataCharacter(e,a,s,!1)}catch(y){m=null,this.verbose&&console.log(y)}return new zn(h,m,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,i){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;i>=0?l=i:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let d=n.length%2!=0;this.startFromEven&&(d=!d);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let m=0,y=l;for(let E=l;E<a;E++)if(e.get(E)!=h)s[m]++;else{if(m==3){if(d&&ce.reverseCounters(s),ce.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=E;return}d&&ce.reverseCounters(s),y+=s[0]+s[1],s[0]=s[2],s[1]=s[3],s[2]=0,s[3]=0,m--}else m++;s[m]=1,h=!h}throw new D}static reverseCounters(e){let n=e.length;for(let i=0;i<n/2;++i){let s=e[i];e[i]=e[n-i-1],e[n-i-1]=s}}parseFoundFinderPattern(e,n,i){let s,a,l;if(i){let m=this.startEnd[0]-1;for(;m>=0&&!e.get(m);)m--;m++,s=this.startEnd[0]-m,a=m,l=this.startEnd[1]}else a=this.startEnd[0],l=e.getNextUnset(this.startEnd[1]+1),s=l-this.startEnd[1];let d=this.getDecodeFinderCounters();P.arraycopy(d,0,d,1,d.length-1),d[0]=s;let h;try{h=this.parseFinderValue(d,ce.FINDER_PATTERNS)}catch{return null}return new ci(h,[a,l],a,l,n)}decodeDataCharacter(e,n,i,s){let a=this.getDataCharacterCounters();for(let at=0;at<a.length;at++)a[at]=0;if(s)ce.recordPatternInReverse(e,n.getStartEnd()[0],a);else{ce.recordPattern(e,n.getStartEnd()[1],a);for(let at=0,zt=a.length-1;at<zt;at++,zt--){let rn=a[at];a[at]=a[zt],a[zt]=rn}}let l=17,d=je.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(d-h)/h>.3)throw new D;let m=this.getOddCounts(),y=this.getEvenCounts(),E=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let at=0;at<a.length;at++){let zt=1*a[at]/d,rn=zt+.5;if(rn<1){if(zt<.3)throw new D;rn=1}else if(rn>8){if(zt>8.7)throw new D;rn=8}let Cr=at/2;(at&1)==0?(m[Cr]=rn,E[Cr]=zt-rn):(y[Cr]=rn,I[Cr]=zt-rn)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(i?0:2)+(s?0:1)-1,F=0,U=0;for(let at=m.length-1;at>=0;at--){if(ce.isNotA1left(n,i,s)){let zt=ce.WEIGHTS[R][2*at];U+=m[at]*zt}F+=m[at]}let q=0;for(let at=y.length-1;at>=0;at--)if(ce.isNotA1left(n,i,s)){let zt=ce.WEIGHTS[R][2*at+1];q+=y[at]*zt}let ne=U+q;if((F&1)!=0||F>13||F<4)throw new D;let me=(13-F)/2,xe=ce.SYMBOL_WIDEST[me],ue=9-xe,We=In.getRSSvalue(m,xe,!0),Be=In.getRSSvalue(y,ue,!1),Qt=ce.EVEN_TOTAL_SUBSET[me],gn=ce.GSUM[me],en=We*Qt+Be+gn;return new mr(en,ne)}static isNotA1left(e,n,i){return!(e.getValue()==0&&n&&i)}adjustOddEvenCounts(e){let n=je.sum(new Int32Array(this.getOddCounts())),i=je.sum(new Int32Array(this.getEvenCounts())),s=!1,a=!1;n>13?a=!0:n<4&&(s=!0);let l=!1,d=!1;i>13?d=!0:i<4&&(l=!0);let h=n+i-e,m=(n&1)==1,y=(i&1)==0;if(h==1)if(m){if(y)throw new D;a=!0}else{if(!y)throw new D;d=!0}else if(h==-1)if(m){if(y)throw new D;s=!0}else{if(!y)throw new D;l=!0}else if(h==0){if(m){if(!y)throw new D;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(y)throw new D}else throw new D;if(s){if(a)throw new D;ce.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&ce.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new D;ce.increment(this.getEvenCounts(),this.getOddRoundingErrors())}d&&ce.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}ce.SYMBOL_WIDEST=[7,5,4,3,1],ce.EVEN_TOTAL_SUBSET=[4,20,52,104,204],ce.GSUM=[0,348,1388,2948,3988],ce.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])],ce.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]],ce.FINDER_PAT_A=0,ce.FINDER_PAT_B=1,ce.FINDER_PAT_C=2,ce.FINDER_PAT_D=3,ce.FINDER_PAT_E=4,ce.FINDER_PAT_F=5,ce.FINDER_PATTERN_SEQUENCES=[[ce.FINDER_PAT_A,ce.FINDER_PAT_A],[ce.FINDER_PAT_A,ce.FINDER_PAT_B,ce.FINDER_PAT_B],[ce.FINDER_PAT_A,ce.FINDER_PAT_C,ce.FINDER_PAT_B,ce.FINDER_PAT_D],[ce.FINDER_PAT_A,ce.FINDER_PAT_E,ce.FINDER_PAT_B,ce.FINDER_PAT_D,ce.FINDER_PAT_C],[ce.FINDER_PAT_A,ce.FINDER_PAT_E,ce.FINDER_PAT_B,ce.FINDER_PAT_D,ce.FINDER_PAT_D,ce.FINDER_PAT_F],[ce.FINDER_PAT_A,ce.FINDER_PAT_E,ce.FINDER_PAT_B,ce.FINDER_PAT_D,ce.FINDER_PAT_E,ce.FINDER_PAT_F,ce.FINDER_PAT_F],[ce.FINDER_PAT_A,ce.FINDER_PAT_A,ce.FINDER_PAT_B,ce.FINDER_PAT_B,ce.FINDER_PAT_C,ce.FINDER_PAT_C,ce.FINDER_PAT_D,ce.FINDER_PAT_D],[ce.FINDER_PAT_A,ce.FINDER_PAT_A,ce.FINDER_PAT_B,ce.FINDER_PAT_B,ce.FINDER_PAT_C,ce.FINDER_PAT_C,ce.FINDER_PAT_D,ce.FINDER_PAT_E,ce.FINDER_PAT_E],[ce.FINDER_PAT_A,ce.FINDER_PAT_A,ce.FINDER_PAT_B,ce.FINDER_PAT_B,ce.FINDER_PAT_C,ce.FINDER_PAT_C,ce.FINDER_PAT_D,ce.FINDER_PAT_E,ce.FINDER_PAT_F,ce.FINDER_PAT_F],[ce.FINDER_PAT_A,ce.FINDER_PAT_A,ce.FINDER_PAT_B,ce.FINDER_PAT_B,ce.FINDER_PAT_C,ce.FINDER_PAT_D,ce.FINDER_PAT_D,ce.FINDER_PAT_E,ce.FINDER_PAT_E,ce.FINDER_PAT_F,ce.FINDER_PAT_F]],ce.MAX_PAIRS=11;class ed extends mr{constructor(e,n,i){super(e,n),this.count=0,this.finderPattern=i}getFinderPattern(){return this.finderPattern}getCount(){return this.count}incrementCount(){this.count++}}class At extends Zt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);At.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);At.addOrTally(this.possibleRightPairs,a),n.reverse();for(let l of this.possibleLeftPairs)if(l.getCount()>1){for(let d of this.possibleRightPairs)if(d.getCount()>1&&At.checkChecksum(l,d))return At.constructResult(l,d)}throw new D}static addOrTally(e,n){if(n==null)return;let i=!1;for(let s of e)if(s.getValue()===n.getValue()){s.incrementCount(),i=!0;break}i||e.push(n)}reset(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0}static constructResult(e,n){let i=4537077*e.getValue()+n.getValue(),s=new String(i).toString(),a=new ae;for(let m=13-s.length;m>0;m--)a.append("0");a.append(s);let l=0;for(let m=0;m<13;m++){let y=a.charAt(m).charCodeAt(0)-48;l+=(m&1)===0?3*y:y}l=10-l%10,l===10&&(l=0),a.append(l.toString());let d=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new Me(a.toString(),null,0,[d[0],d[1],h[0],h[1]],ie.RSS_14,new Date().getTime())}static checkChecksum(e,n){let i=(e.getChecksumPortion()+16*n.getChecksumPortion())%79,s=9*e.getFinderPattern().getValue()+n.getFinderPattern().getValue();return s>72&&s--,s>8&&s--,i===s}decodePair(e,n,i,s){try{let a=this.findFinderPattern(e,n),l=this.parseFoundFinderPattern(e,i,n,a),d=s==null?null:s.get(j.NEED_RESULT_POINT_CALLBACK);if(d!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),d.foundPossibleResultPoint(new T(y,i))}let h=this.decodeDataCharacter(e,l,!0),m=this.decodeDataCharacter(e,l,!1);return new ed(1597*h.getValue()+m.getValue(),h.getChecksumPortion()+4*m.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let q=0;q<s.length;q++)s[q]=0;if(i)Ie.recordPatternInReverse(e,n.getStartEnd()[0],s);else{Ie.recordPattern(e,n.getStartEnd()[1]+1,s);for(let q=0,ne=s.length-1;q<ne;q++,ne--){let me=s[q];s[q]=s[ne],s[ne]=me}}let a=i?16:15,l=je.sum(new Int32Array(s))/a,d=this.getOddCounts(),h=this.getEvenCounts(),m=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let q=0;q<s.length;q++){let ne=s[q]/l,me=Math.floor(ne+.5);me<1?me=1:me>8&&(me=8);let xe=Math.floor(q/2);(q&1)===0?(d[xe]=me,m[xe]=ne-me):(h[xe]=me,y[xe]=ne-me)}this.adjustOddEvenCounts(i,a);let E=0,I=0;for(let q=d.length-1;q>=0;q--)I*=9,I+=d[q],E+=d[q];let R=0,F=0;for(let q=h.length-1;q>=0;q--)R*=9,R+=h[q],F+=h[q];let U=I+3*R;if(i){if((E&1)!==0||E>12||E<4)throw new D;let q=(12-E)/2,ne=At.OUTSIDE_ODD_WIDEST[q],me=9-ne,xe=In.getRSSvalue(d,ne,!1),ue=In.getRSSvalue(h,me,!0),We=At.OUTSIDE_EVEN_TOTAL_SUBSET[q],Be=At.OUTSIDE_GSUM[q];return new mr(xe*We+ue+Be,U)}else{if((F&1)!==0||F>10||F<4)throw new D;let q=(10-F)/2,ne=At.INSIDE_ODD_WIDEST[q],me=9-ne,xe=In.getRSSvalue(d,ne,!0),ue=In.getRSSvalue(h,me,!1),We=At.INSIDE_ODD_TOTAL_SUBSET[q],Be=At.INSIDE_GSUM[q];return new mr(ue*We+xe+Be,U)}}findFinderPattern(e,n){let i=this.getDecodeFinderCounters();i[0]=0,i[1]=0,i[2]=0,i[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let d=0,h=l;for(let m=l;m<s;m++)if(e.get(m)!==a)i[d]++;else{if(d===3){if(Zt.isFinderPattern(i))return[h,m];h+=i[0]+i[1],i[0]=i[2],i[1]=i[3],i[2]=0,i[3]=0,d--}else d++;i[d]=1,a=!a}throw new D}parseFoundFinderPattern(e,n,i,s){let a=e.get(s[0]),l=s[0]-1;for(;l>=0&&a!==e.get(l);)l--;l++;const d=s[0]-l,h=this.getDecodeFinderCounters(),m=new Int32Array(h.length);P.arraycopy(h,0,m,1,h.length-1),m[0]=d;const y=this.parseFinderValue(m,At.FINDER_PATTERNS);let E=l,I=s[1];return i&&(E=e.getSize()-1-E,I=e.getSize()-1-I),new ci(y,[l,s[1]],E,I,n)}adjustOddEvenCounts(e,n){let i=je.sum(new Int32Array(this.getOddCounts())),s=je.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,d=!1,h=!1;e?(i>12?l=!0:i<4&&(a=!0),s>12?h=!0:s<4&&(d=!0)):(i>11?l=!0:i<5&&(a=!0),s>10?h=!0:s<4&&(d=!0));let m=i+s-n,y=(i&1)===(e?1:0),E=(s&1)===1;if(m===1)if(y){if(E)throw new D;l=!0}else{if(!E)throw new D;h=!0}else if(m===-1)if(y){if(E)throw new D;a=!0}else{if(!E)throw new D;d=!0}else if(m===0){if(y){if(!E)throw new D;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(E)throw new D}else throw new D;if(a){if(l)throw new D;Zt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Zt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new D;Zt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Zt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}At.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],At.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],At.OUTSIDE_GSUM=[0,161,961,2015,2715],At.INSIDE_GSUM=[0,336,1036,1516],At.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],At.INSIDE_ODD_WIDEST=[2,4,6,8],At.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])];class yr extends Ie{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(j.POSSIBLE_FORMATS):null,s=e&&e.get(j.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(ie.EAN_13)||i.includes(ie.UPC_A)||i.includes(ie.EAN_8)||i.includes(ie.UPC_E))&&this.readers.push(new Gi(e)),i.includes(ie.CODE_39)&&this.readers.push(new Re(s)),i.includes(ie.CODE_128)&&this.readers.push(new oe),i.includes(ie.ITF)&&this.readers.push(new qe),i.includes(ie.RSS_14)&&this.readers.push(new At),i.includes(ie.RSS_EXPANDED)&&this.readers.push(new ce(this.verbose))):(this.readers.push(new Gi(e)),this.readers.push(new Re),this.readers.push(new Gi(e)),this.readers.push(new oe),this.readers.push(new qe),this.readers.push(new At),this.readers.push(new ce(this.verbose)))}decodeRow(e,n,i){for(let s=0;s<this.readers.length;s++)try{return this.readers[s].decodeRow(e,n,i)}catch{}throw new D}reset(){this.readers.forEach(e=>e.reset())}}class td extends Ve{constructor(e=500,n){super(new yr(n),e,n)}}class tt{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class Qe{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class He{constructor(e,n,i,s,a,l){this.versionNumber=e,this.symbolSizeRows=n,this.symbolSizeColumns=i,this.dataRegionSizeRows=s,this.dataRegionSizeColumns=a,this.ecBlocks=l;let d=0;const h=l.getECCodewords(),m=l.getECBlocks();for(let y of m)d+=y.getCount()*(y.getDataCodewords()+h);this.totalCodewords=d}getVersionNumber(){return this.versionNumber}getSymbolSizeRows(){return this.symbolSizeRows}getSymbolSizeColumns(){return this.symbolSizeColumns}getDataRegionSizeRows(){return this.dataRegionSizeRows}getDataRegionSizeColumns(){return this.dataRegionSizeColumns}getTotalCodewords(){return this.totalCodewords}getECBlocks(){return this.ecBlocks}static getVersionForDimensions(e,n){if((e&1)!==0||(n&1)!==0)throw new V;for(let i of He.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new V}toString(){return""+this.versionNumber}static buildVersions(){return[new He(1,10,10,8,8,new tt(5,new Qe(1,3))),new He(2,12,12,10,10,new tt(7,new Qe(1,5))),new He(3,14,14,12,12,new tt(10,new Qe(1,8))),new He(4,16,16,14,14,new tt(12,new Qe(1,12))),new He(5,18,18,16,16,new tt(14,new Qe(1,18))),new He(6,20,20,18,18,new tt(18,new Qe(1,22))),new He(7,22,22,20,20,new tt(20,new Qe(1,30))),new He(8,24,24,22,22,new tt(24,new Qe(1,36))),new He(9,26,26,24,24,new tt(28,new Qe(1,44))),new He(10,32,32,14,14,new tt(36,new Qe(1,62))),new He(11,36,36,16,16,new tt(42,new Qe(1,86))),new He(12,40,40,18,18,new tt(48,new Qe(1,114))),new He(13,44,44,20,20,new tt(56,new Qe(1,144))),new He(14,48,48,22,22,new tt(68,new Qe(1,174))),new He(15,52,52,24,24,new tt(42,new Qe(2,102))),new He(16,64,64,14,14,new tt(56,new Qe(2,140))),new He(17,72,72,16,16,new tt(36,new Qe(4,92))),new He(18,80,80,18,18,new tt(48,new Qe(4,114))),new He(19,88,88,20,20,new tt(56,new Qe(4,144))),new He(20,96,96,22,22,new tt(68,new Qe(4,174))),new He(21,104,104,24,24,new tt(56,new Qe(6,136))),new He(22,120,120,18,18,new tt(68,new Qe(6,175))),new He(23,132,132,20,20,new tt(62,new Qe(8,163))),new He(24,144,144,22,22,new tt(62,new Qe(8,156),new Qe(2,155))),new He(25,8,18,6,16,new tt(7,new Qe(1,5))),new He(26,8,32,6,14,new tt(11,new Qe(1,10))),new He(27,12,26,10,24,new tt(14,new Qe(1,16))),new He(28,12,36,10,16,new tt(18,new Qe(1,22))),new He(29,16,36,14,16,new tt(24,new Qe(1,32))),new He(30,16,48,14,22,new tt(28,new Qe(1,49)))]}}He.VERSIONS=He.buildVersions();class Ji{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new V;this.version=Ji.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new X(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return He.getVersionForDimensions(n,i)}readCodewords(){const e=new Int8Array(this.version.getTotalCodewords());let n=0,i=4,s=0;const a=this.mappingBitMatrix.getHeight(),l=this.mappingBitMatrix.getWidth();let d=!1,h=!1,m=!1,y=!1;do if(i===a&&s===0&&!d)e[n++]=this.readCorner1(a,l)&255,i-=2,s+=2,d=!0;else if(i===a-2&&s===0&&(l&3)!==0&&!h)e[n++]=this.readCorner2(a,l)&255,i-=2,s+=2,h=!0;else if(i===a+4&&s===2&&(l&7)===0&&!m)e[n++]=this.readCorner3(a,l)&255,i-=2,s+=2,m=!0;else if(i===a-2&&s===0&&(l&7)===4&&!y)e[n++]=this.readCorner4(a,l)&255,i-=2,s+=2,y=!0;else{do i<a&&s>=0&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i-=2,s+=2;while(i>=0&&s<l);i+=1,s+=3;do i>=0&&s<l&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i+=2,s-=2;while(i<a&&s>=0);i+=3,s+=1}while(i<a||s<l);if(n!==this.version.getTotalCodewords())throw new V;return e}readModule(e,n,i,s){return e<0&&(e+=i,n+=4-(i+4&7)),n<0&&(n+=s,e+=4-(s+4&7)),this.readMappingMatrix.set(n,e),this.mappingBitMatrix.get(n,e)}readUtah(e,n,i,s){let a=0;return this.readModule(e-2,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-2,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n,i,s)&&(a|=1),a<<=1,this.readModule(e,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e,n,i,s)&&(a|=1),a}readCorner1(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,1,e,n)&&(i|=1),i<<=1,this.readModule(e-1,2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}readCorner2(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-4,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner3(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-3,e,n)&&(i|=1),i<<=1,this.readModule(1,n-2,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner4(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}extractDataRegion(e){const n=this.version.getSymbolSizeRows(),i=this.version.getSymbolSizeColumns();if(e.getHeight()!==n)throw new A("Dimension of bitMatrix must match the version size");const s=this.version.getDataRegionSizeRows(),a=this.version.getDataRegionSizeColumns(),l=n/s|0,d=i/a|0,h=l*s,m=d*a,y=new X(m,h);for(let E=0;E<l;++E){const I=E*s;for(let R=0;R<d;++R){const F=R*a;for(let U=0;U<s;++U){const q=E*(s+2)+1+U,ne=I+U;for(let me=0;me<a;++me){const xe=R*(a+2)+1+me;if(e.get(xe,q)){const ue=F+me;y.set(ue,ne)}}}}}return y}}class Ki{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n){const i=n.getECBlocks();let s=0;const a=i.getECBlocks();for(let U of a)s+=U.getCount();const l=new Array(s);let d=0;for(let U of a)for(let q=0;q<U.getCount();q++){const ne=U.getDataCodewords(),me=i.getECCodewords()+ne;l[d++]=new Ki(ne,new Uint8Array(me))}const m=l[0].codewords.length-i.getECCodewords(),y=m-1;let E=0;for(let U=0;U<y;U++)for(let q=0;q<d;q++)l[q].codewords[U]=e[E++];const I=n.getVersionNumber()===24,R=I?8:d;for(let U=0;U<R;U++)l[U].codewords[m-1]=e[E++];const F=l[0].codewords.length;for(let U=m;U<F;U++)for(let q=0;q<d;q++){const ne=I?(q+8)%d:q,me=I&&ne>7?U-1:U;l[ne].codewords[me]=e[E++]}if(E!==e.length)throw new A;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Qi{constructor(e){this.bytes=e,this.byteOffset=0,this.bitOffset=0}getBitOffset(){return this.bitOffset}getByteOffset(){return this.byteOffset}readBits(e){if(e<1||e>32||e>this.available())throw new A(""+e);let n=0,i=this.bitOffset,s=this.byteOffset;const a=this.bytes;if(i>0){const l=8-i,d=e<l?e:l,h=l-d,m=255>>8-d<<h;n=(a[s]&m)>>h,e-=d,i+=d,i===8&&(i=0,s++)}if(e>0){for(;e>=8;)n=n<<8|a[s]&255,s++,e-=8;if(e>0){const l=8-e,d=255>>l<<l;n=n<<e|(a[s]&d)>>l,i+=e}}return this.bitOffset=i,this.byteOffset=s,n}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var Ot;(function(b){b[b.PAD_ENCODE=0]="PAD_ENCODE",b[b.ASCII_ENCODE=1]="ASCII_ENCODE",b[b.C40_ENCODE=2]="C40_ENCODE",b[b.TEXT_ENCODE=3]="TEXT_ENCODE",b[b.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",b[b.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",b[b.BASE256_ENCODE=6]="BASE256_ENCODE"})(Ot||(Ot={}));class $n{static decode(e){const n=new Qi(e),i=new ae,s=new ae,a=new Array;let l=Ot.ASCII_ENCODE;do if(l===Ot.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Ot.C40_ENCODE:this.decodeC40Segment(n,i);break;case Ot.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Ot.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Ot.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Ot.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new V}l=Ot.ASCII_ENCODE}while(l!==Ot.PAD_ENCODE&&n.available()>0);return s.length()>0&&i.append(s.toString()),new Ne(e,i.toString(),a.length===0?null:a,null)}static decodeAsciiSegment(e,n,i){let s=!1;do{let a=e.readBits(8);if(a===0)throw new V;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Ot.ASCII_ENCODE;if(a===129)return Ot.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Ot.C40_ENCODE;case 231:return Ot.BASE256_ENCODE;case 232:n.append("");break;case 233:case 234:break;case 235:s=!0;break;case 236:n.append("[)>05"),i.insert(0,"");break;case 237:n.append("[)>06"),i.insert(0,"");break;case 238:return Ot.ANSIX12_ENCODE;case 239:return Ot.TEXT_ENCODE;case 240:return Ot.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new V;break}}while(e.available()>0);return Ot.ASCII_ENCODE}static decodeC40Segment(e,n){let i=!1;const s=[];let a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.C40_BASIC_SET_CHARS.length){const m=this.C40_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(m.charCodeAt(0)+128)),i=!1):n.append(m)}else throw new V;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.C40_SHIFT2_SET_CHARS.length){const m=this.C40_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(m.charCodeAt(0)+128)),i=!1):n.append(m)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new V}a=0;break;case 3:i?(n.append(String.fromCharCode(h+224)),i=!1):n.append(String.fromCharCode(h+96)),a=0;break;default:throw new V}}}while(e.available()>0)}static decodeTextSegment(e,n){let i=!1,s=[],a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.TEXT_BASIC_SET_CHARS.length){const m=this.TEXT_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(m.charCodeAt(0)+128)),i=!1):n.append(m)}else throw new V;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.TEXT_SHIFT2_SET_CHARS.length){const m=this.TEXT_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(m.charCodeAt(0)+128)),i=!1):n.append(m)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new V}a=0;break;case 3:if(h<this.TEXT_SHIFT3_SET_CHARS.length){const m=this.TEXT_SHIFT3_SET_CHARS[h];i?(n.append(String.fromCharCode(m.charCodeAt(0)+128)),i=!1):n.append(m),a=0}else throw new V;break;default:throw new V}}}while(e.available()>0)}static decodeAnsiX12Segment(e,n){const i=[];do{if(e.available()===8)return;const s=e.readBits(8);if(s===254)return;this.parseTwoBytes(s,e.readBits(8),i);for(let a=0;a<3;a++){const l=i[a];switch(l){case 0:n.append("\r");break;case 1:n.append("*");break;case 2:n.append(">");break;case 3:n.append(" ");break;default:if(l<14)n.append(String.fromCharCode(l+44));else if(l<40)n.append(String.fromCharCode(l+51));else throw new V;break}}}while(e.available()>0)}static parseTwoBytes(e,n,i){let s=(e<<8)+n-1,a=Math.floor(s/1600);i[0]=a,s-=a*1600,a=Math.floor(s/40),i[1]=a,i[2]=s-a*40}static decodeEdifactSegment(e,n){do{if(e.available()<=16)return;for(let i=0;i<4;i++){let s=e.readBits(6);if(s===31){const a=8-e.getBitOffset();a!==8&&e.readBits(a);return}(s&32)===0&&(s|=64),n.append(String.fromCharCode(s))}}while(e.available()>0)}static decodeBase256Segment(e,n,i){let s=1+e.getByteOffset();const a=this.unrandomize255State(e.readBits(8),s++);let l;if(a===0?l=e.available()/8|0:a<250?l=a:l=250*(a-249)+this.unrandomize255State(e.readBits(8),s++),l<0)throw new V;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new V;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(le.decode(d,fe.ISO88591))}catch(h){throw new Vt("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const i=149*n%255+1,s=e-i;return s>=0?s:s+256}}$n.C40_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],$n.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],$n.TEXT_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],$n.TEXT_SHIFT2_SET_CHARS=$n.C40_SHIFT2_SET_CHARS,$n.TEXT_SHIFT3_SET_CHARS=["`","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","~",""];class nd{constructor(){this.rsDecoder=new bn(Ue.DATA_MATRIX_FIELD_256)}decode(e){const n=new Ji(e),i=n.getVersion(),s=n.readCodewords(),a=Ki.getDataBlocks(s,i);let l=0;for(let m of a)l+=m.getNumDataCodewords();const d=new Uint8Array(l),h=a.length;for(let m=0;m<h;m++){const y=a[m],E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let R=0;R<I;R++)d[R*h+m]=E[R]}return $n.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Nt{constructor(e){this.image=e,this.rectangleDetector=new vt(this.image)}detect(){const e=this.rectangleDetector.detect();let n=this.detectSolid1(e);if(n=this.detectSolid2(n),n[3]=this.correctTopRight(n),!n[3])throw new D;n=this.shiftToModuleCenter(n);const i=n[0],s=n[1],a=n[2],l=n[3];let d=this.transitionsBetween(i,l)+1,h=this.transitionsBetween(a,l)+1;(d&1)===1&&(d+=1),(h&1)===1&&(h+=1),4*d<7*h&&4*h<7*d&&(d=h=Math.max(d,h));let m=Nt.sampleGrid(this.image,i,s,a,l,d,h);return new pe(m,[i,s,a,l])}static shiftPoint(e,n,i){let s=(n.getX()-e.getX())/(i+1),a=(n.getY()-e.getY())/(i+1);return new T(e.getX()+s,e.getY()+a)}static moveAway(e,n,i){let s=e.getX(),a=e.getY();return s<n?s-=1:s+=1,a<i?a-=1:a+=1,new T(s,a)}detectSolid1(e){let n=e[0],i=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,i),d=this.transitionsBetween(i,s),h=this.transitionsBetween(s,a),m=this.transitionsBetween(a,n),y=l,E=[a,n,i,s];return y>d&&(y=d,E[0]=n,E[1]=i,E[2]=s,E[3]=a),y>h&&(y=h,E[0]=i,E[1]=s,E[2]=a,E[3]=n),y>m&&(E[0]=s,E[1]=a,E[2]=n,E[3]=i),E}detectSolid2(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=Nt.shiftPoint(i,s,(l+1)*4),h=Nt.shiftPoint(s,i,(l+1)*4),m=this.transitionsBetween(d,n),y=this.transitionsBetween(h,a);return m<y?(e[0]=n,e[1]=i,e[2]=s,e[3]=a):(e[0]=i,e[1]=s,e[2]=a,e[3]=n),e}correctTopRight(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=this.transitionsBetween(i,a),h=Nt.shiftPoint(n,i,(d+1)*4),m=Nt.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(m,a);let y=new T(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),E=new T(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(y))return this.isValid(E)?E:null;if(!this.isValid(E))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(m,y),R=this.transitionsBetween(h,E)+this.transitionsBetween(m,E);return I>R?y:E}shiftToModuleCenter(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,d=this.transitionsBetween(s,a)+1,h=Nt.shiftPoint(n,i,d*4),m=Nt.shiftPoint(s,i,l*4);l=this.transitionsBetween(h,a)+1,d=this.transitionsBetween(m,a)+1,(l&1)===1&&(l+=1),(d&1)===1&&(d+=1);let y=(n.getX()+i.getX()+s.getX()+a.getX())/4,E=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Nt.moveAway(n,y,E),i=Nt.moveAway(i,y,E),s=Nt.moveAway(s,y,E),a=Nt.moveAway(a,y,E);let I,R;return h=Nt.shiftPoint(n,i,d*4),h=Nt.shiftPoint(h,a,l*4),I=Nt.shiftPoint(i,n,d*4),I=Nt.shiftPoint(I,s,l*4),m=Nt.shiftPoint(s,a,d*4),m=Nt.shiftPoint(m,i,l*4),R=Nt.shiftPoint(a,s,d*4),R=Nt.shiftPoint(R,n,l*4),[h,I,m,R]}isValid(e){return e.getX()>=0&&e.getX()<this.image.getWidth()&&e.getY()>0&&e.getY()<this.image.getHeight()}static sampleGrid(e,n,i,s,a,l,d){return An.getInstance().sampleGrid(e,l,d,.5,.5,l-.5,.5,l-.5,d-.5,.5,d-.5,n.getX(),n.getY(),a.getX(),a.getY(),s.getX(),s.getY(),i.getX(),i.getY())}transitionsBetween(e,n){let i=Math.trunc(e.getX()),s=Math.trunc(e.getY()),a=Math.trunc(n.getX()),l=Math.trunc(n.getY()),d=Math.abs(l-s)>Math.abs(a-i);if(d){let U=i;i=s,s=U,U=a,a=l,l=U}let h=Math.abs(a-i),m=Math.abs(l-s),y=-h/2,E=s<l?1:-1,I=i<a?1:-1,R=0,F=this.image.get(d?s:i,d?i:s);for(let U=i,q=s;U!==a;U+=I){let ne=this.image.get(d?q:U,d?U:q);if(ne!==F&&(R++,F=ne),y+=m,y>0){if(q===l)break;q+=E,y-=h}}return R}}class Vn{constructor(){this.decoder=new nd}decode(e,n=null){let i,s;if(n!=null&&n.has(j.PURE_BARCODE)){const m=Vn.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(m),s=Vn.NO_POINTS}else{const m=new Nt(e.getBlackMatrix()).detect();i=this.decoder.decode(m.getBits()),s=m.getPoints()}const a=i.getRawBytes(),l=new Me(i.getText(),a,8*a.length,s,ie.DATA_MATRIX,P.currentTimeMillis()),d=i.getByteSegments();d!=null&&l.putMetadata(Ae.BYTE_SEGMENTS,d);const h=i.getECLevel();return h!=null&&l.putMetadata(Ae.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n==null||i==null)throw new D;const s=this.moduleSize(n,e);let a=n[1];const l=i[1];let d=n[0];const m=(i[0]-d+1)/s,y=(l-a+1)/s;if(m<=0||y<=0)throw new D;const E=s/2;a+=E,d+=E;const I=new X(m,y);for(let R=0;R<y;R++){const F=a+R*s;for(let U=0;U<m;U++)e.get(d+U*s,F)&&I.set(U,R)}return I}static moduleSize(e,n){const i=n.getWidth();let s=e[0];const a=e[1];for(;s<i&&n.get(s,a);)s++;if(s===i)throw new D;const l=s-e[0];if(l===0)throw new D;return l}}Vn.NO_POINTS=[];class rd extends Ve{constructor(e=500){super(new Vn,e)}}var wr;(function(b){b[b.L=0]="L",b[b.M=1]="M",b[b.Q=2]="Q",b[b.H=3]="H"})(wr||(wr={}));class ut{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,ut.FOR_BITS.set(i,this),ut.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return ut.L;case"M":return ut.M;case"Q":return ut.Q;case"H":return ut.H;default:throw new C(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof ut))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=ut.FOR_BITS.size)throw new A;return ut.FOR_BITS.get(e)}}ut.FOR_BITS=new Map,ut.FOR_VALUE=new Map,ut.L=new ut(wr.L,"L",1),ut.M=new ut(wr.M,"M",0),ut.Q=new ut(wr.Q,"Q",3),ut.H=new ut(wr.H,"H",2);class jt{constructor(e){this.errorCorrectionLevel=ut.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return $.bitCount(e^n)}static decodeFormatInformation(e,n){const i=jt.doDecodeFormatInformation(e,n);return i!==null?i:jt.doDecodeFormatInformation(e^jt.FORMAT_INFO_MASK_QR,n^jt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=Number.MAX_SAFE_INTEGER,s=0;for(const a of jt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new jt(a[1]);let d=jt.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=jt.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=3?new jt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof jt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}jt.FORMAT_INFO_MASK_QR=21522,jt.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([21522,0]),Int32Array.from([20773,1]),Int32Array.from([24188,2]),Int32Array.from([23371,3]),Int32Array.from([17913,4]),Int32Array.from([16590,5]),Int32Array.from([20375,6]),Int32Array.from([19104,7]),Int32Array.from([30660,8]),Int32Array.from([29427,9]),Int32Array.from([32170,10]),Int32Array.from([30877,11]),Int32Array.from([26159,12]),Int32Array.from([25368,13]),Int32Array.from([27713,14]),Int32Array.from([26998,15]),Int32Array.from([5769,16]),Int32Array.from([5054,17]),Int32Array.from([7399,18]),Int32Array.from([6608,19]),Int32Array.from([1890,20]),Int32Array.from([597,21]),Int32Array.from([3340,22]),Int32Array.from([2107,23]),Int32Array.from([13663,24]),Int32Array.from([12392,25]),Int32Array.from([16177,26]),Int32Array.from([14854,27]),Int32Array.from([9396,28]),Int32Array.from([8579,29]),Int32Array.from([11994,30]),Int32Array.from([11245,31])];class J{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const i of n)e+=i.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class N{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ee{constructor(e,n,...i){this.versionNumber=e,this.alignmentPatternCenters=n,this.ecBlocks=i;let s=0;const a=i[0].getECCodewordsPerBlock(),l=i[0].getECBlocks();for(const d of l)s+=d.getCount()*(d.getDataCodewords()+a);this.totalCodewords=s}getVersionNumber(){return this.versionNumber}getAlignmentPatternCenters(){return this.alignmentPatternCenters}getTotalCodewords(){return this.totalCodewords}getDimensionForVersion(){return 17+4*this.versionNumber}getECBlocksForLevel(e){return this.ecBlocks[e.getValue()]}static getProvisionalVersionForDimension(e){if(e%4!==1)throw new V;try{return this.getVersionForNumber((e-17)/4)}catch{throw new V}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return Ee.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<Ee.VERSION_DECODE_INFO.length;s++){const a=Ee.VERSION_DECODE_INFO[s];if(a===e)return Ee.getVersionForNumber(s+7);const l=jt.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?Ee.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new X(e);n.setRegion(0,0,9,9),n.setRegion(e-8,0,8,9),n.setRegion(0,e-8,9,8);const i=this.alignmentPatternCenters.length;for(let s=0;s<i;s++){const a=this.alignmentPatternCenters[s]-2;for(let l=0;l<i;l++)s===0&&(l===0||l===i-1)||s===i-1&&l===0||n.setRegion(this.alignmentPatternCenters[l]-2,a,5,5)}return n.setRegion(6,9,1,e-17),n.setRegion(9,6,e-17,1),this.versionNumber>6&&(n.setRegion(e-11,0,3,6),n.setRegion(0,e-11,6,3)),n}toString(){return""+this.versionNumber}}Ee.VERSION_DECODE_INFO=Int32Array.from([31892,34236,39577,42195,48118,51042,55367,58893,63784,68472,70749,76311,79154,84390,87683,92361,96236,102084,102881,110507,110734,117786,119615,126325,127568,133589,136944,141498,145311,150283,152622,158308,161089,167017]),Ee.VERSIONS=[new Ee(1,new Int32Array(0),new J(7,new N(1,19)),new J(10,new N(1,16)),new J(13,new N(1,13)),new J(17,new N(1,9))),new Ee(2,Int32Array.from([6,18]),new J(10,new N(1,34)),new J(16,new N(1,28)),new J(22,new N(1,22)),new J(28,new N(1,16))),new Ee(3,Int32Array.from([6,22]),new J(15,new N(1,55)),new J(26,new N(1,44)),new J(18,new N(2,17)),new J(22,new N(2,13))),new Ee(4,Int32Array.from([6,26]),new J(20,new N(1,80)),new J(18,new N(2,32)),new J(26,new N(2,24)),new J(16,new N(4,9))),new Ee(5,Int32Array.from([6,30]),new J(26,new N(1,108)),new J(24,new N(2,43)),new J(18,new N(2,15),new N(2,16)),new J(22,new N(2,11),new N(2,12))),new Ee(6,Int32Array.from([6,34]),new J(18,new N(2,68)),new J(16,new N(4,27)),new J(24,new N(4,19)),new J(28,new N(4,15))),new Ee(7,Int32Array.from([6,22,38]),new J(20,new N(2,78)),new J(18,new N(4,31)),new J(18,new N(2,14),new N(4,15)),new J(26,new N(4,13),new N(1,14))),new Ee(8,Int32Array.from([6,24,42]),new J(24,new N(2,97)),new J(22,new N(2,38),new N(2,39)),new J(22,new N(4,18),new N(2,19)),new J(26,new N(4,14),new N(2,15))),new Ee(9,Int32Array.from([6,26,46]),new J(30,new N(2,116)),new J(22,new N(3,36),new N(2,37)),new J(20,new N(4,16),new N(4,17)),new J(24,new N(4,12),new N(4,13))),new Ee(10,Int32Array.from([6,28,50]),new J(18,new N(2,68),new N(2,69)),new J(26,new N(4,43),new N(1,44)),new J(24,new N(6,19),new N(2,20)),new J(28,new N(6,15),new N(2,16))),new Ee(11,Int32Array.from([6,30,54]),new J(20,new N(4,81)),new J(30,new N(1,50),new N(4,51)),new J(28,new N(4,22),new N(4,23)),new J(24,new N(3,12),new N(8,13))),new Ee(12,Int32Array.from([6,32,58]),new J(24,new N(2,92),new N(2,93)),new J(22,new N(6,36),new N(2,37)),new J(26,new N(4,20),new N(6,21)),new J(28,new N(7,14),new N(4,15))),new Ee(13,Int32Array.from([6,34,62]),new J(26,new N(4,107)),new J(22,new N(8,37),new N(1,38)),new J(24,new N(8,20),new N(4,21)),new J(22,new N(12,11),new N(4,12))),new Ee(14,Int32Array.from([6,26,46,66]),new J(30,new N(3,115),new N(1,116)),new J(24,new N(4,40),new N(5,41)),new J(20,new N(11,16),new N(5,17)),new J(24,new N(11,12),new N(5,13))),new Ee(15,Int32Array.from([6,26,48,70]),new J(22,new N(5,87),new N(1,88)),new J(24,new N(5,41),new N(5,42)),new J(30,new N(5,24),new N(7,25)),new J(24,new N(11,12),new N(7,13))),new Ee(16,Int32Array.from([6,26,50,74]),new J(24,new N(5,98),new N(1,99)),new J(28,new N(7,45),new N(3,46)),new J(24,new N(15,19),new N(2,20)),new J(30,new N(3,15),new N(13,16))),new Ee(17,Int32Array.from([6,30,54,78]),new J(28,new N(1,107),new N(5,108)),new J(28,new N(10,46),new N(1,47)),new J(28,new N(1,22),new N(15,23)),new J(28,new N(2,14),new N(17,15))),new Ee(18,Int32Array.from([6,30,56,82]),new J(30,new N(5,120),new N(1,121)),new J(26,new N(9,43),new N(4,44)),new J(28,new N(17,22),new N(1,23)),new J(28,new N(2,14),new N(19,15))),new Ee(19,Int32Array.from([6,30,58,86]),new J(28,new N(3,113),new N(4,114)),new J(26,new N(3,44),new N(11,45)),new J(26,new N(17,21),new N(4,22)),new J(26,new N(9,13),new N(16,14))),new Ee(20,Int32Array.from([6,34,62,90]),new J(28,new N(3,107),new N(5,108)),new J(26,new N(3,41),new N(13,42)),new J(30,new N(15,24),new N(5,25)),new J(28,new N(15,15),new N(10,16))),new Ee(21,Int32Array.from([6,28,50,72,94]),new J(28,new N(4,116),new N(4,117)),new J(26,new N(17,42)),new J(28,new N(17,22),new N(6,23)),new J(30,new N(19,16),new N(6,17))),new Ee(22,Int32Array.from([6,26,50,74,98]),new J(28,new N(2,111),new N(7,112)),new J(28,new N(17,46)),new J(30,new N(7,24),new N(16,25)),new J(24,new N(34,13))),new Ee(23,Int32Array.from([6,30,54,78,102]),new J(30,new N(4,121),new N(5,122)),new J(28,new N(4,47),new N(14,48)),new J(30,new N(11,24),new N(14,25)),new J(30,new N(16,15),new N(14,16))),new Ee(24,Int32Array.from([6,28,54,80,106]),new J(30,new N(6,117),new N(4,118)),new J(28,new N(6,45),new N(14,46)),new J(30,new N(11,24),new N(16,25)),new J(30,new N(30,16),new N(2,17))),new Ee(25,Int32Array.from([6,32,58,84,110]),new J(26,new N(8,106),new N(4,107)),new J(28,new N(8,47),new N(13,48)),new J(30,new N(7,24),new N(22,25)),new J(30,new N(22,15),new N(13,16))),new Ee(26,Int32Array.from([6,30,58,86,114]),new J(28,new N(10,114),new N(2,115)),new J(28,new N(19,46),new N(4,47)),new J(28,new N(28,22),new N(6,23)),new J(30,new N(33,16),new N(4,17))),new Ee(27,Int32Array.from([6,34,62,90,118]),new J(30,new N(8,122),new N(4,123)),new J(28,new N(22,45),new N(3,46)),new J(30,new N(8,23),new N(26,24)),new J(30,new N(12,15),new N(28,16))),new Ee(28,Int32Array.from([6,26,50,74,98,122]),new J(30,new N(3,117),new N(10,118)),new J(28,new N(3,45),new N(23,46)),new J(30,new N(4,24),new N(31,25)),new J(30,new N(11,15),new N(31,16))),new Ee(29,Int32Array.from([6,30,54,78,102,126]),new J(30,new N(7,116),new N(7,117)),new J(28,new N(21,45),new N(7,46)),new J(30,new N(1,23),new N(37,24)),new J(30,new N(19,15),new N(26,16))),new Ee(30,Int32Array.from([6,26,52,78,104,130]),new J(30,new N(5,115),new N(10,116)),new J(28,new N(19,47),new N(10,48)),new J(30,new N(15,24),new N(25,25)),new J(30,new N(23,15),new N(25,16))),new Ee(31,Int32Array.from([6,30,56,82,108,134]),new J(30,new N(13,115),new N(3,116)),new J(28,new N(2,46),new N(29,47)),new J(30,new N(42,24),new N(1,25)),new J(30,new N(23,15),new N(28,16))),new Ee(32,Int32Array.from([6,34,60,86,112,138]),new J(30,new N(17,115)),new J(28,new N(10,46),new N(23,47)),new J(30,new N(10,24),new N(35,25)),new J(30,new N(19,15),new N(35,16))),new Ee(33,Int32Array.from([6,30,58,86,114,142]),new J(30,new N(17,115),new N(1,116)),new J(28,new N(14,46),new N(21,47)),new J(30,new N(29,24),new N(19,25)),new J(30,new N(11,15),new N(46,16))),new Ee(34,Int32Array.from([6,34,62,90,118,146]),new J(30,new N(13,115),new N(6,116)),new J(28,new N(14,46),new N(23,47)),new J(30,new N(44,24),new N(7,25)),new J(30,new N(59,16),new N(1,17))),new Ee(35,Int32Array.from([6,30,54,78,102,126,150]),new J(30,new N(12,121),new N(7,122)),new J(28,new N(12,47),new N(26,48)),new J(30,new N(39,24),new N(14,25)),new J(30,new N(22,15),new N(41,16))),new Ee(36,Int32Array.from([6,24,50,76,102,128,154]),new J(30,new N(6,121),new N(14,122)),new J(28,new N(6,47),new N(34,48)),new J(30,new N(46,24),new N(10,25)),new J(30,new N(2,15),new N(64,16))),new Ee(37,Int32Array.from([6,28,54,80,106,132,158]),new J(30,new N(17,122),new N(4,123)),new J(28,new N(29,46),new N(14,47)),new J(30,new N(49,24),new N(10,25)),new J(30,new N(24,15),new N(46,16))),new Ee(38,Int32Array.from([6,32,58,84,110,136,162]),new J(30,new N(4,122),new N(18,123)),new J(28,new N(13,46),new N(32,47)),new J(30,new N(48,24),new N(14,25)),new J(30,new N(42,15),new N(32,16))),new Ee(39,Int32Array.from([6,26,54,82,110,138,166]),new J(30,new N(20,117),new N(4,118)),new J(28,new N(40,47),new N(7,48)),new J(30,new N(43,24),new N(22,25)),new J(30,new N(10,15),new N(67,16))),new Ee(40,Int32Array.from([6,30,58,86,114,142,170]),new J(30,new N(19,118),new N(6,119)),new J(28,new N(18,47),new N(31,48)),new J(30,new N(34,24),new N(34,25)),new J(30,new N(20,15),new N(61,16)))];var Mt;(function(b){b[b.DATA_MASK_000=0]="DATA_MASK_000",b[b.DATA_MASK_001=1]="DATA_MASK_001",b[b.DATA_MASK_010=2]="DATA_MASK_010",b[b.DATA_MASK_011=3]="DATA_MASK_011",b[b.DATA_MASK_100=4]="DATA_MASK_100",b[b.DATA_MASK_101=5]="DATA_MASK_101",b[b.DATA_MASK_110=6]="DATA_MASK_110",b[b.DATA_MASK_111=7]="DATA_MASK_111"})(Mt||(Mt={}));class dn{constructor(e,n){this.value=e,this.isMasked=n}unmaskBitMatrix(e,n){for(let i=0;i<n;i++)for(let s=0;s<n;s++)this.isMasked(i,s)&&e.flip(s,i)}}dn.values=new Map([[Mt.DATA_MASK_000,new dn(Mt.DATA_MASK_000,(b,e)=>(b+e&1)===0)],[Mt.DATA_MASK_001,new dn(Mt.DATA_MASK_001,(b,e)=>(b&1)===0)],[Mt.DATA_MASK_010,new dn(Mt.DATA_MASK_010,(b,e)=>e%3===0)],[Mt.DATA_MASK_011,new dn(Mt.DATA_MASK_011,(b,e)=>(b+e)%3===0)],[Mt.DATA_MASK_100,new dn(Mt.DATA_MASK_100,(b,e)=>(Math.floor(b/2)+Math.floor(e/3)&1)===0)],[Mt.DATA_MASK_101,new dn(Mt.DATA_MASK_101,(b,e)=>b*e%6===0)],[Mt.DATA_MASK_110,new dn(Mt.DATA_MASK_110,(b,e)=>b*e%6<3)],[Mt.DATA_MASK_111,new dn(Mt.DATA_MASK_111,(b,e)=>(b+e+b*e%3&1)===0)]]);class id{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new V;this.bitMatrix=e}readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==void 0)return this.parsedFormatInfo;let e=0;for(let a=0;a<6;a++)e=this.copyBit(a,8,e);e=this.copyBit(7,8,e),e=this.copyBit(8,8,e),e=this.copyBit(8,7,e);for(let a=5;a>=0;a--)e=this.copyBit(8,a,e);const n=this.bitMatrix.getHeight();let i=0;const s=n-7;for(let a=n-1;a>=s;a--)i=this.copyBit(8,a,i);for(let a=n-8;a<n;a++)i=this.copyBit(a,8,i);if(this.parsedFormatInfo=jt.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new V}readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==void 0)return this.parsedVersion;const e=this.bitMatrix.getHeight(),n=Math.floor((e-17)/4);if(n<=6)return Ee.getVersionForNumber(n);let i=0;const s=e-11;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(d,l,i);let a=Ee.decodeVersionInformation(i);if(a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;i=0;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(l,d,i);if(a=Ee.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new V}copyBit(e,n,i){return(this.isMirror?this.bitMatrix.get(n,e):this.bitMatrix.get(e,n))?i<<1|1:i<<1}readCodewords(){const e=this.readFormatInformation(),n=this.readVersion(),i=dn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();i.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const d=new Uint8Array(n.getTotalCodewords());let h=0,m=0,y=0;for(let E=s-1;E>0;E-=2){E===6&&E--;for(let I=0;I<s;I++){const R=l?s-1-I:I;for(let F=0;F<2;F++)a.get(E-F,R)||(y++,m<<=1,this.bitMatrix.get(E-F,R)&&(m|=1),y===8&&(d[h++]=m,y=0,m=0))}l=!l}if(h!==n.getTotalCodewords())throw new V;return d}remask(){if(this.parsedFormatInfo===null)return;const e=dn.values[this.parsedFormatInfo.getDataMask()],n=this.bitMatrix.getHeight();e.unmaskBitMatrix(this.bitMatrix,n)}setMirror(e){this.parsedVersion=null,this.parsedFormatInfo=null,this.isMirror=e}mirror(){const e=this.bitMatrix;for(let n=0,i=e.getWidth();n<i;n++)for(let s=n+1,a=e.getHeight();s<a;s++)e.get(n,s)!==e.get(s,n)&&(e.flip(s,n),e.flip(n,s))}}class eo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,i){if(e.length!==n.getTotalCodewords())throw new A;const s=n.getECBlocksForLevel(i);let a=0;const l=s.getECBlocks();for(const F of l)a+=F.getCount();const d=new Array(a);let h=0;for(const F of l)for(let U=0;U<F.getCount();U++){const q=F.getDataCodewords(),ne=s.getECCodewordsPerBlock()+q;d[h++]=new eo(q,new Uint8Array(ne))}const m=d[0].codewords.length;let y=d.length-1;for(;y>=0&&d[y].codewords.length!==m;)y--;y++;const E=m-s.getECCodewordsPerBlock();let I=0;for(let F=0;F<E;F++)for(let U=0;U<h;U++)d[U].codewords[F]=e[I++];for(let F=y;F<h;F++)d[F].codewords[E]=e[I++];const R=d[0].codewords.length;for(let F=E;F<R;F++)for(let U=0;U<h;U++){const q=U<y?F:F+1;d[U].codewords[q]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var fn;(function(b){b[b.TERMINATOR=0]="TERMINATOR",b[b.NUMERIC=1]="NUMERIC",b[b.ALPHANUMERIC=2]="ALPHANUMERIC",b[b.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",b[b.BYTE=4]="BYTE",b[b.ECI=5]="ECI",b[b.KANJI=6]="KANJI",b[b.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",b[b.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",b[b.HANZI=9]="HANZI"})(fn||(fn={}));class Se{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,Se.FOR_BITS.set(s,this),Se.FOR_VALUE.set(e,this)}static forBits(e){const n=Se.FOR_BITS.get(e);if(n===void 0)throw new A;return n}getCharacterCountBits(e){const n=e.getVersionNumber();let i;return n<=9?i=0:n<=26?i=1:i=2,this.characterCountBitsForVersions[i]}getValue(){return this.value}getBits(){return this.bits}equals(e){if(!(e instanceof Se))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Se.FOR_BITS=new Map,Se.FOR_VALUE=new Map,Se.TERMINATOR=new Se(fn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Se.NUMERIC=new Se(fn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Se.ALPHANUMERIC=new Se(fn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Se.STRUCTURED_APPEND=new Se(fn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Se.BYTE=new Se(fn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Se.ECI=new Se(fn.ECI,"ECI",Int32Array.from([0,0,0]),7),Se.KANJI=new Se(fn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Se.FNC1_FIRST_POSITION=new Se(fn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Se.FNC1_SECOND_POSITION=new Se(fn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Se.HANZI=new Se(fn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class Ct{static decode(e,n,i,s){const a=new Qi(e);let l=new ae;const d=new Array;let h=-1,m=-1;try{let y=null,E=!1,I;do{if(a.available()<4)I=Se.TERMINATOR;else{const R=a.readBits(4);I=Se.forBits(R)}switch(I){case Se.TERMINATOR:break;case Se.FNC1_FIRST_POSITION:case Se.FNC1_SECOND_POSITION:E=!0;break;case Se.STRUCTURED_APPEND:if(a.available()<16)throw new V;h=a.readBits(8),m=a.readBits(8);break;case Se.ECI:const R=Ct.parseECIValue(a);if(y=M.getCharacterSetECIByValue(R),y===null)throw new V;break;case Se.HANZI:const F=a.readBits(4),U=a.readBits(I.getCharacterCountBits(n));F===Ct.GB2312_SUBSET&&Ct.decodeHanziSegment(a,l,U);break;default:const q=a.readBits(I.getCharacterCountBits(n));switch(I){case Se.NUMERIC:Ct.decodeNumericSegment(a,l,q);break;case Se.ALPHANUMERIC:Ct.decodeAlphanumericSegment(a,l,q,E);break;case Se.BYTE:Ct.decodeByteSegment(a,l,q,y,d,s);break;case Se.KANJI:Ct.decodeKanjiSegment(a,l,q);break;default:throw new V}break}}while(I!==Se.TERMINATOR)}catch{throw new V}return new Ne(e,l.toString(),d.length===0?null:d,i===null?null:i.toString(),h,m)}static decodeHanziSegment(e,n,i){if(i*13>e.available())throw new V;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/96<<8&4294967295|l%96;d<959?d+=41377:d+=42657,s[a]=d>>8&255,s[a+1]=d&255,a+=2,i--}try{n.append(le.decode(s,fe.GB2312))}catch(l){throw new V(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new V;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/192<<8&4294967295|l%192;d<7936?d+=33088:d+=49472,s[a]=d>>8,s[a+1]=d,a+=2,i--}try{n.append(le.decode(s,fe.SHIFT_JIS))}catch(l){throw new V(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new V;const d=new Uint8Array(i);for(let m=0;m<i;m++)d[m]=e.readBits(8);let h;s===null?h=fe.guessEncoding(d,l):h=s.getName();try{n.append(le.decode(d,h))}catch(m){throw new V(m)}a.push(d)}static toAlphaNumericChar(e){if(e>=Ct.ALPHANUMERIC_CHARS.length)throw new V;return Ct.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new V;const l=e.readBits(11);n.append(Ct.toAlphaNumericChar(Math.floor(l/45))),n.append(Ct.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new V;n.append(Ct.toAlphaNumericChar(e.readBits(6)))}if(s)for(let l=a;l<n.length();l++)n.charAt(l)==="%"&&(l<n.length()-1&&n.charAt(l+1)==="%"?n.deleteCharAt(l+1):n.setCharAt(l,""))}static decodeNumericSegment(e,n,i){for(;i>=3;){if(e.available()<10)throw new V;const s=e.readBits(10);if(s>=1e3)throw new V;n.append(Ct.toAlphaNumericChar(Math.floor(s/100))),n.append(Ct.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(Ct.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new V;const s=e.readBits(7);if(s>=100)throw new V;n.append(Ct.toAlphaNumericChar(Math.floor(s/10))),n.append(Ct.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new V;const s=e.readBits(4);if(s>=10)throw new V;n.append(Ct.toAlphaNumericChar(s))}}static parseECIValue(e){const n=e.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){const i=e.readBits(8);return(n&63)<<8&4294967295|i}if((n&224)===192){const i=e.readBits(16);return(n&31)<<16&4294967295|i}throw new V}}Ct.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",Ct.GB2312_SUBSET=1;class hs{constructor(e){this.mirrored=e}isMirrored(){return this.mirrored}applyMirroredCorrection(e){if(!this.mirrored||e===null||e.length<3)return;const n=e[0];e[0]=e[2],e[2]=n}}class od{constructor(){this.rsDecoder=new bn(Ue.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(X.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new id(e);let s=null;try{return this.decodeBitMatrixParser(i,n)}catch(a){s=a}try{i.remask(),i.setMirror(!0),i.readVersion(),i.readFormatInformation(),i.mirror();const a=this.decodeBitMatrixParser(i,n);return a.setOther(new hs(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=eo.getDataBlocks(a,i,s);let d=0;for(const y of l)d+=y.getNumDataCodewords();const h=new Uint8Array(d);let m=0;for(const y of l){const E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let R=0;R<I;R++)h[m++]=E[R]}return Ct.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class to extends T{constructor(e,n,i){super(e,n),this.estimatedModuleSize=i}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=(this.getX()+n)/2,a=(this.getY()+e)/2,l=(this.estimatedModuleSize+i)/2;return new to(s,a,l)}}class fi{constructor(e,n,i,s,a,l,d){this.image=e,this.startX=n,this.startY=i,this.width=s,this.height=a,this.moduleSize=l,this.resultPointCallback=d,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}find(){const e=this.startX,n=this.height,i=this.width,s=e+i,a=this.startY+n/2,l=new Int32Array(3),d=this.image;for(let h=0;h<n;h++){const m=a+((h&1)===0?Math.floor((h+1)/2):-Math.floor((h+1)/2));l[0]=0,l[1]=0,l[2]=0;let y=e;for(;y<s&&!d.get(y,m);)y++;let E=0;for(;y<s;){if(d.get(y,m))if(E===1)l[1]++;else if(E===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,m,y);if(I!==null)return I}l[0]=l[2],l[1]=1,l[2]=0,E=1}else l[++E]++;else E===1&&E++,l[E]++;y++}if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,m,s);if(I!==null)return I}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new D}static centerFromEnd(e,n){return n-e[2]-e[1]/2}foundPatternCross(e){const n=this.moduleSize,i=n/2;for(let s=0;s<3;s++)if(Math.abs(n-e[s])>=i)return!1;return!0}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.crossCheckStateCount;d[0]=0,d[1]=0,d[2]=0;let h=e;for(;h>=0&&a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&!a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h)&&d[1]<=i;)d[1]++,h++;if(h===l||d[1]>i)return NaN;for(;h<l&&!a.get(n,h)&&d[2]<=i;)d[2]++,h++;if(d[2]>i)return NaN;const m=d[0]+d[1]+d[2];return 5*Math.abs(m-s)>=2*s?NaN:this.foundPatternCross(d)?fi.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i){const s=e[0]+e[1]+e[2],a=fi.centerFromEnd(e,i),l=this.crossCheckVertical(n,a,2*e[1],s);if(!isNaN(l)){const d=(e[0]+e[1]+e[2])/3;for(const m of this.possibleCenters)if(m.aboutEquals(d,l,a))return m.combineEstimate(l,a,d);const h=new to(a,l,d);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class no extends T{constructor(e,n,i,s){super(e,n),this.estimatedModuleSize=i,this.count=s,s===void 0&&(this.count=1)}getEstimatedModuleSize(){return this.estimatedModuleSize}getCount(){return this.count}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=this.count+1,a=(this.count*this.getX()+n)/s,l=(this.count*this.getY()+e)/s,d=(this.count*this.estimatedModuleSize+i)/s;return new no(a,l,d,s)}}class sd{constructor(e){this.bottomLeft=e[0],this.topLeft=e[1],this.topRight=e[2]}getBottomLeft(){return this.bottomLeft}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}}class Dt{constructor(e,n){this.image=e,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}getImage(){return this.image}getPossibleCenters(){return this.possibleCenters}find(e){const n=e!=null&&e.get(j.TRY_HARDER)!==void 0,i=e!=null&&e.get(j.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Dt.MAX_MODULES));(d<Dt.MIN_SKIP||n)&&(d=Dt.MIN_SKIP);let h=!1;const m=new Int32Array(5);for(let E=d-1;E<a&&!h;E+=d){m[0]=0,m[1]=0,m[2]=0,m[3]=0,m[4]=0;let I=0;for(let R=0;R<l;R++)if(s.get(R,E))(I&1)===1&&I++,m[I]++;else if((I&1)===0)if(I===4)if(Dt.foundPatternCross(m)){if(this.handlePossibleCenter(m,E,R,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const U=this.findRowSkip();U>m[2]&&(E+=U-m[2]-d,R=l-1)}else{m[0]=m[2],m[1]=m[3],m[2]=m[4],m[3]=1,m[4]=0,I=3;continue}I=0,m[0]=0,m[1]=0,m[2]=0,m[3]=0,m[4]=0}else m[0]=m[2],m[1]=m[3],m[2]=m[4],m[3]=1,m[4]=0,I=3;else m[++I]++;else m[I]++;Dt.foundPatternCross(m)&&this.handlePossibleCenter(m,E,l,i)===!0&&(d=m[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return T.orderBestPatterns(y),new sd(y)}static centerFromEnd(e,n){return n-e[4]-e[3]-e[2]/2}static foundPatternCross(e){let n=0;for(let a=0;a<5;a++){const l=e[a];if(l===0)return!1;n+=l}if(n<7)return!1;const i=n/7,s=i/2;return Math.abs(i-e[0])<s&&Math.abs(i-e[1])<s&&Math.abs(3*i-e[2])<3*s&&Math.abs(i-e[3])<s&&Math.abs(i-e[4])<s}getCrossCheckStateCount(){const e=this.crossCheckStateCount;return e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e}crossCheckDiagonal(e,n,i,s){const a=this.getCrossCheckStateCount();let l=0;const d=this.image;for(;e>=l&&n>=l&&d.get(n-l,e-l);)a[2]++,l++;if(e<l||n<l)return!1;for(;e>=l&&n>=l&&!d.get(n-l,e-l)&&a[1]<=i;)a[1]++,l++;if(e<l||n<l||a[1]>i)return!1;for(;e>=l&&n>=l&&d.get(n-l,e-l)&&a[0]<=i;)a[0]++,l++;if(a[0]>i)return!1;const h=d.getHeight(),m=d.getWidth();for(l=1;e+l<h&&n+l<m&&d.get(n+l,e+l);)a[2]++,l++;if(e+l>=h||n+l>=m)return!1;for(;e+l<h&&n+l<m&&!d.get(n+l,e+l)&&a[3]<i;)a[3]++,l++;if(e+l>=h||n+l>=m||a[3]>=i)return!1;for(;e+l<h&&n+l<m&&d.get(n+l,e+l)&&a[4]<i;)a[4]++,l++;if(a[4]>=i)return!1;const y=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(y-s)<2*s&&Dt.foundPatternCross(a)}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(n,h)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const m=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(m-s)>=2*s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}crossCheckHorizontal(e,n,i,s){const a=this.image,l=a.getWidth(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(h,n)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(h,n);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(h,n)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const m=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(m-s)>=s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Dt.centerFromEnd(e,i),d=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(d)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(d),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(d),Math.floor(l),e[2],a)))){const h=a/7;let m=!1;const y=this.possibleCenters;for(let E=0,I=y.length;E<I;E++){const R=y[E];if(R.aboutEquals(h,d,l)){y[E]=R.combineEstimate(d,l,h),m=!0;break}}if(!m){const E=new no(l,d,h);y.push(E),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(E)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const i of this.possibleCenters)if(i.getCount()>=Dt.CENTER_QUORUM)if(n==null)n=i;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-i.getX())-Math.abs(n.getY()-i.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const i=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=Dt.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/i;let a=0;for(const l of this.possibleCenters)a+=Math.abs(l.getEstimatedModuleSize()-s);return a<=.05*n}selectBestPatterns(){const e=this.possibleCenters.length;if(e<3)throw new D;const n=this.possibleCenters;let i;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const m=h.getEstimatedModuleSize();s+=m,a+=m*m}i=s/e;let l=Math.sqrt(a/e-i*i);n.sort((h,m)=>{const y=Math.abs(m.getEstimatedModuleSize()-i),E=Math.abs(h.getEstimatedModuleSize()-i);return y<E?-1:y>E?1:0});const d=Math.max(.2*i,l);for(let h=0;h<n.length&&n.length>3;h++){const m=n[h];Math.abs(m.getEstimatedModuleSize()-i)>d&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();i=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const d=Math.abs(l.getEstimatedModuleSize()-i),h=Math.abs(a.getEstimatedModuleSize()-i);return d<h?1:d>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}Dt.CENTER_QUORUM=2,Dt.MIN_SKIP=3,Dt.MAX_MODULES=57;class Rr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(j.NEED_RESULT_POINT_CALLBACK);const i=new Dt(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(i)}processFinderPatternInfo(e){const n=e.getTopLeft(),i=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,i,s);if(a<1)throw new D("No pattern found in proccess finder.");const l=Rr.computeDimension(n,i,s,a),d=Ee.getProvisionalVersionForDimension(l),h=d.getDimensionForVersion()-7;let m=null;if(d.getAlignmentPatternCenters().length>0){const R=i.getX()-n.getX()+s.getX(),F=i.getY()-n.getY()+s.getY(),U=1-3/h,q=Math.floor(n.getX()+U*(R-n.getX())),ne=Math.floor(n.getY()+U*(F-n.getY()));for(let me=4;me<=16;me<<=1)try{m=this.findAlignmentInRegion(a,q,ne,me);break}catch(xe){if(!(xe instanceof D))throw xe}}const y=Rr.createTransform(n,i,s,m,l),E=Rr.sampleGrid(this.image,y,l);let I;return m===null?I=[s,n,i]:I=[s,n,i,m],new pe(E,I)}static createTransform(e,n,i,s,a){const l=a-3.5;let d,h,m,y;return s!==null?(d=s.getX(),h=s.getY(),m=l-3,y=m):(d=n.getX()-e.getX()+i.getX(),h=n.getY()-e.getY()+i.getY(),m=l,y=l),nn.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,m,y,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),d,h,i.getX(),i.getY())}static sampleGrid(e,n,i){return An.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=je.round(T.distance(e,n)/s),l=je.round(T.distance(e,i)/s);let d=Math.floor((a+l)/2)+7;switch(d&3){case 0:d++;break;case 2:d--;break;case 3:throw new D("Dimensions could be not found.")}return d}calculateModuleSize(e,n,i){return(this.calculateModuleSizeOneWay(e,n)+this.calculateModuleSizeOneWay(e,i))/2}calculateModuleSizeOneWay(e,n){const i=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(e.getX()),Math.floor(e.getY()),Math.floor(n.getX()),Math.floor(n.getY())),s=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(n.getX()),Math.floor(n.getY()),Math.floor(e.getX()),Math.floor(e.getY()));return isNaN(i)?s/7:isNaN(s)?i/7:(i+s)/14}sizeOfBlackWhiteBlackRunBothWays(e,n,i,s){let a=this.sizeOfBlackWhiteBlackRun(e,n,i,s),l=1,d=e-(i-e);d<0?(l=e/(e-d),d=0):d>=this.image.getWidth()&&(l=(this.image.getWidth()-1-e)/(d-e),d=this.image.getWidth()-1);let h=Math.floor(n-(s-n)*l);return l=1,h<0?(l=n/(n-h),h=0):h>=this.image.getHeight()&&(l=(this.image.getHeight()-1-n)/(h-n),h=this.image.getHeight()-1),d=Math.floor(e+(d-e)*l),a+=this.sizeOfBlackWhiteBlackRun(e,n,d,h),a-1}sizeOfBlackWhiteBlackRun(e,n,i,s){const a=Math.abs(s-n)>Math.abs(i-e);if(a){let R=e;e=n,n=R,R=i,i=s,s=R}const l=Math.abs(i-e),d=Math.abs(s-n);let h=-l/2;const m=e<i?1:-1,y=n<s?1:-1;let E=0;const I=i+m;for(let R=e,F=n;R!==I;R+=m){const U=a?F:R,q=a?R:F;if(E===1===this.image.get(U,q)){if(E===2)return je.distance(R,F,e,n);E++}if(h+=d,h>0){if(F===s)break;F+=y,h-=l}}return E===2?je.distance(i+m,s,e,n):NaN}findAlignmentInRegion(e,n,i,s){const a=Math.floor(s*e),l=Math.max(0,n-a),d=Math.min(this.image.getWidth()-1,n+a);if(d-l<e*3)throw new D("Alignment top exceeds estimated module size.");const h=Math.max(0,i-a),m=Math.min(this.image.getHeight()-1,i+a);if(m-h<e*3)throw new D("Alignment bottom exceeds estimated module size.");return new fi(this.image,l,h,d-l,m-h,e,this.resultPointCallback).find()}}class Zn{constructor(){this.decoder=new od}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(j.PURE_BARCODE)!==void 0){const h=Zn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=Zn.NO_POINTS}else{const h=new Rr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof hs&&i.getOther().applyMirroredCorrection(s);const a=new Me(i.getText(),i.getRawBytes(),void 0,s,ie.QR_CODE,void 0),l=i.getByteSegments();l!==null&&a.putMetadata(Ae.BYTE_SEGMENTS,l);const d=i.getECLevel();return d!==null&&a.putMetadata(Ae.ERROR_CORRECTION_LEVEL,d),i.hasStructuredAppend()&&(a.putMetadata(Ae.STRUCTURED_APPEND_SEQUENCE,i.getStructuredAppendSequenceNumber()),a.putMetadata(Ae.STRUCTURED_APPEND_PARITY,i.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n===null||i===null)throw new D;const s=this.moduleSize(n,e);let a=n[1],l=i[1],d=n[0],h=i[0];if(d>=h||a>=l)throw new D;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new D;const m=Math.round((h-d+1)/s),y=Math.round((l-a+1)/s);if(m<=0||y<=0)throw new D;if(y!==m)throw new D;const E=Math.floor(s/2);a+=E,d+=E;const I=d+Math.floor((m-1)*s)-h;if(I>0){if(I>E)throw new D;d-=I}const R=a+Math.floor((y-1)*s)-l;if(R>0){if(R>E)throw new D;a-=R}const F=new X(m,y);for(let U=0;U<y;U++){const q=a+Math.floor(U*s);for(let ne=0;ne<m;ne++)e.get(d+Math.floor(ne*s),q)&&F.set(ne,U)}return F}static moduleSize(e,n){const i=n.getHeight(),s=n.getWidth();let a=e[0],l=e[1],d=!0,h=0;for(;a<s&&l<i;){if(d!==n.get(a,l)){if(++h===5)break;d=!d}a++,l++}if(a===s||l===i)throw new D;return(a-e[0])/7}}Zn.NO_POINTS=new Array;class Oe{PDF417Common(){}static getBitCountSum(e){return je.sum(e)}static toIntArray(e){if(e==null||!e.length)return Oe.EMPTY_INT_ARRAY;const n=new Int32Array(e.length);let i=0;for(const s of e)n[i++]=s;return n}static getCodeword(e){const n=Z.binarySearch(Oe.SYMBOL_TABLE,e&262143);return n<0?-1:(Oe.CODEWORD_TABLE[n]-1)%Oe.NUMBER_OF_CODEWORDS}}Oe.NUMBER_OF_CODEWORDS=929,Oe.MAX_CODEWORDS_IN_BARCODE=Oe.NUMBER_OF_CODEWORDS-1,Oe.MIN_ROWS_IN_BARCODE=3,Oe.MAX_ROWS_IN_BARCODE=90,Oe.MODULES_IN_CODEWORD=17,Oe.MODULES_IN_STOP_PATTERN=18,Oe.BARS_IN_MODULE=8,Oe.EMPTY_INT_ARRAY=new Int32Array([]),Oe.SYMBOL_TABLE=Int32Array.from([66142,66170,66206,66236,66290,66292,66350,66382,66396,66454,66470,66476,66594,66600,66614,66626,66628,66632,66640,66654,66662,66668,66682,66690,66718,66720,66748,66758,66776,66798,66802,66804,66820,66824,66832,66846,66848,66876,66880,66936,66950,66956,66968,66992,67006,67022,67036,67042,67044,67048,67062,67118,67150,67164,67214,67228,67256,67294,67322,67350,67366,67372,67398,67404,67416,67438,67474,67476,67490,67492,67496,67510,67618,67624,67650,67656,67664,67678,67686,67692,67706,67714,67716,67728,67742,67744,67772,67782,67788,67800,67822,67826,67828,67842,67848,67870,67872,67900,67904,67960,67974,67992,68016,68030,68046,68060,68066,68068,68072,68086,68104,68112,68126,68128,68156,68160,68216,68336,68358,68364,68376,68400,68414,68448,68476,68494,68508,68536,68546,68548,68552,68560,68574,68582,68588,68654,68686,68700,68706,68708,68712,68726,68750,68764,68792,68802,68804,68808,68816,68830,68838,68844,68858,68878,68892,68920,68976,68990,68994,68996,69e3,69008,69022,69024,69052,69062,69068,69080,69102,69106,69108,69142,69158,69164,69190,69208,69230,69254,69260,69272,69296,69310,69326,69340,69386,69394,69396,69410,69416,69430,69442,69444,69448,69456,69470,69478,69484,69554,69556,69666,69672,69698,69704,69712,69726,69754,69762,69764,69776,69790,69792,69820,69830,69836,69848,69870,69874,69876,69890,69918,69920,69948,69952,70008,70022,70040,70064,70078,70094,70108,70114,70116,70120,70134,70152,70174,70176,70264,70384,70412,70448,70462,70496,70524,70542,70556,70584,70594,70600,70608,70622,70630,70636,70664,70672,70686,70688,70716,70720,70776,70896,71136,71180,71192,71216,71230,71264,71292,71360,71416,71452,71480,71536,71550,71554,71556,71560,71568,71582,71584,71612,71622,71628,71640,71662,71726,71732,71758,71772,71778,71780,71784,71798,71822,71836,71864,71874,71880,71888,71902,71910,71916,71930,71950,71964,71992,72048,72062,72066,72068,72080,72094,72096,72124,72134,72140,72152,72174,72178,72180,72206,72220,72248,72304,72318,72416,72444,72456,72464,72478,72480,72508,72512,72568,72588,72600,72624,72638,72654,72668,72674,72676,72680,72694,72726,72742,72748,72774,72780,72792,72814,72838,72856,72880,72894,72910,72924,72930,72932,72936,72950,72966,72972,72984,73008,73022,73056,73084,73102,73116,73144,73156,73160,73168,73182,73190,73196,73210,73226,73234,73236,73250,73252,73256,73270,73282,73284,73296,73310,73318,73324,73346,73348,73352,73360,73374,73376,73404,73414,73420,73432,73454,73498,73518,73522,73524,73550,73564,73570,73572,73576,73590,73800,73822,73858,73860,73872,73886,73888,73916,73944,73970,73972,73992,74014,74016,74044,74048,74104,74118,74136,74160,74174,74210,74212,74216,74230,74244,74256,74270,74272,74360,74480,74502,74508,74544,74558,74592,74620,74638,74652,74680,74690,74696,74704,74726,74732,74782,74784,74812,74992,75232,75288,75326,75360,75388,75456,75512,75576,75632,75646,75650,75652,75664,75678,75680,75708,75718,75724,75736,75758,75808,75836,75840,75896,76016,76256,76736,76824,76848,76862,76896,76924,76992,77048,77296,77340,77368,77424,77438,77536,77564,77572,77576,77584,77600,77628,77632,77688,77702,77708,77720,77744,77758,77774,77788,77870,77902,77916,77922,77928,77966,77980,78008,78018,78024,78032,78046,78060,78074,78094,78136,78192,78206,78210,78212,78224,78238,78240,78268,78278,78284,78296,78322,78324,78350,78364,78448,78462,78560,78588,78600,78622,78624,78652,78656,78712,78726,78744,78768,78782,78798,78812,78818,78820,78824,78838,78862,78876,78904,78960,78974,79072,79100,79296,79352,79368,79376,79390,79392,79420,79424,79480,79600,79628,79640,79664,79678,79712,79740,79772,79800,79810,79812,79816,79824,79838,79846,79852,79894,79910,79916,79942,79948,79960,79982,79988,80006,80024,80048,80062,80078,80092,80098,80100,80104,80134,80140,80176,80190,80224,80252,80270,80284,80312,80328,80336,80350,80358,80364,80378,80390,80396,80408,80432,80446,80480,80508,80576,80632,80654,80668,80696,80752,80766,80776,80784,80798,80800,80828,80844,80856,80878,80882,80884,80914,80916,80930,80932,80936,80950,80962,80968,80976,80990,80998,81004,81026,81028,81040,81054,81056,81084,81094,81100,81112,81134,81154,81156,81160,81168,81182,81184,81212,81216,81272,81286,81292,81304,81328,81342,81358,81372,81380,81384,81398,81434,81454,81458,81460,81486,81500,81506,81508,81512,81526,81550,81564,81592,81602,81604,81608,81616,81630,81638,81644,81702,81708,81722,81734,81740,81752,81774,81778,81780,82050,82078,82080,82108,82180,82184,82192,82206,82208,82236,82240,82296,82316,82328,82352,82366,82402,82404,82408,82440,82448,82462,82464,82492,82496,82552,82672,82694,82700,82712,82736,82750,82784,82812,82830,82882,82884,82888,82896,82918,82924,82952,82960,82974,82976,83004,83008,83064,83184,83424,83468,83480,83504,83518,83552,83580,83648,83704,83740,83768,83824,83838,83842,83844,83848,83856,83872,83900,83910,83916,83928,83950,83984,84e3,84028,84032,84088,84208,84448,84928,85040,85054,85088,85116,85184,85240,85488,85560,85616,85630,85728,85756,85764,85768,85776,85790,85792,85820,85824,85880,85894,85900,85912,85936,85966,85980,86048,86080,86136,86256,86496,86976,88160,88188,88256,88312,88560,89056,89200,89214,89312,89340,89536,89592,89608,89616,89632,89664,89720,89840,89868,89880,89904,89952,89980,89998,90012,90040,90190,90204,90254,90268,90296,90306,90308,90312,90334,90382,90396,90424,90480,90494,90500,90504,90512,90526,90528,90556,90566,90572,90584,90610,90612,90638,90652,90680,90736,90750,90848,90876,90884,90888,90896,90910,90912,90940,90944,91e3,91014,91020,91032,91056,91070,91086,91100,91106,91108,91112,91126,91150,91164,91192,91248,91262,91360,91388,91584,91640,91664,91678,91680,91708,91712,91768,91888,91928,91952,91966,92e3,92028,92046,92060,92088,92098,92100,92104,92112,92126,92134,92140,92188,92216,92272,92384,92412,92608,92664,93168,93200,93214,93216,93244,93248,93304,93424,93664,93720,93744,93758,93792,93820,93888,93944,93980,94008,94064,94078,94084,94088,94096,94110,94112,94140,94150,94156,94168,94246,94252,94278,94284,94296,94318,94342,94348,94360,94384,94398,94414,94428,94440,94470,94476,94488,94512,94526,94560,94588,94606,94620,94648,94658,94660,94664,94672,94686,94694,94700,94714,94726,94732,94744,94768,94782,94816,94844,94912,94968,94990,95004,95032,95088,95102,95112,95120,95134,95136,95164,95180,95192,95214,95218,95220,95244,95256,95280,95294,95328,95356,95424,95480,95728,95758,95772,95800,95856,95870,95968,95996,96008,96016,96030,96032,96060,96064,96120,96152,96176,96190,96220,96226,96228,96232,96290,96292,96296,96310,96322,96324,96328,96336,96350,96358,96364,96386,96388,96392,96400,96414,96416,96444,96454,96460,96472,96494,96498,96500,96514,96516,96520,96528,96542,96544,96572,96576,96632,96646,96652,96664,96688,96702,96718,96732,96738,96740,96744,96758,96772,96776,96784,96798,96800,96828,96832,96888,97008,97030,97036,97048,97072,97086,97120,97148,97166,97180,97208,97220,97224,97232,97246,97254,97260,97326,97330,97332,97358,97372,97378,97380,97384,97398,97422,97436,97464,97474,97476,97480,97488,97502,97510,97516,97550,97564,97592,97648,97666,97668,97672,97680,97694,97696,97724,97734,97740,97752,97774,97830,97836,97850,97862,97868,97880,97902,97906,97908,97926,97932,97944,97968,97998,98012,98018,98020,98024,98038,98618,98674,98676,98838,98854,98874,98892,98904,98926,98930,98932,98968,99006,99042,99044,99048,99062,99166,99194,99246,99286,99350,99366,99372,99386,99398,99416,99438,99442,99444,99462,99504,99518,99534,99548,99554,99556,99560,99574,99590,99596,99608,99632,99646,99680,99708,99726,99740,99768,99778,99780,99784,99792,99806,99814,99820,99834,99858,99860,99874,99880,99894,99906,99920,99934,99962,99970,99972,99976,99984,99998,1e5,100028,100038,100044,100056,100078,100082,100084,100142,100174,100188,100246,100262,100268,100306,100308,100390,100396,100410,100422,100428,100440,100462,100466,100468,100486,100504,100528,100542,100558,100572,100578,100580,100584,100598,100620,100656,100670,100704,100732,100750,100792,100802,100808,100816,100830,100838,100844,100858,100888,100912,100926,100960,100988,101056,101112,101148,101176,101232,101246,101250,101252,101256,101264,101278,101280,101308,101318,101324,101336,101358,101362,101364,101410,101412,101416,101430,101442,101448,101456,101470,101478,101498,101506,101508,101520,101534,101536,101564,101580,101618,101620,101636,101640,101648,101662,101664,101692,101696,101752,101766,101784,101838,101858,101860,101864,101934,101938,101940,101966,101980,101986,101988,101992,102030,102044,102072,102082,102084,102088,102096,102138,102166,102182,102188,102214,102220,102232,102254,102282,102290,102292,102306,102308,102312,102326,102444,102458,102470,102476,102488,102514,102516,102534,102552,102576,102590,102606,102620,102626,102632,102646,102662,102668,102704,102718,102752,102780,102798,102812,102840,102850,102856,102864,102878,102886,102892,102906,102936,102974,103008,103036,103104,103160,103224,103280,103294,103298,103300,103312,103326,103328,103356,103366,103372,103384,103406,103410,103412,103472,103486,103520,103548,103616,103672,103920,103992,104048,104062,104160,104188,104194,104196,104200,104208,104224,104252,104256,104312,104326,104332,104344,104368,104382,104398,104412,104418,104420,104424,104482,104484,104514,104520,104528,104542,104550,104570,104578,104580,104592,104606,104608,104636,104652,104690,104692,104706,104712,104734,104736,104764,104768,104824,104838,104856,104910,104930,104932,104936,104968,104976,104990,104992,105020,105024,105080,105200,105240,105278,105312,105372,105410,105412,105416,105424,105446,105518,105524,105550,105564,105570,105572,105576,105614,105628,105656,105666,105672,105680,105702,105722,105742,105756,105784,105840,105854,105858,105860,105864,105872,105888,105932,105970,105972,106006,106022,106028,106054,106060,106072,106100,106118,106124,106136,106160,106174,106190,106210,106212,106216,106250,106258,106260,106274,106276,106280,106306,106308,106312,106320,106334,106348,106394,106414,106418,106420,106566,106572,106610,106612,106630,106636,106648,106672,106686,106722,106724,106728,106742,106758,106764,106776,106800,106814,106848,106876,106894,106908,106936,106946,106948,106952,106960,106974,106982,106988,107032,107056,107070,107104,107132,107200,107256,107292,107320,107376,107390,107394,107396,107400,107408,107422,107424,107452,107462,107468,107480,107502,107506,107508,107544,107568,107582,107616,107644,107712,107768,108016,108060,108088,108144,108158,108256,108284,108290,108292,108296,108304,108318,108320,108348,108352,108408,108422,108428,108440,108464,108478,108494,108508,108514,108516,108520,108592,108640,108668,108736,108792,109040,109536,109680,109694,109792,109820,110016,110072,110084,110088,110096,110112,110140,110144,110200,110320,110342,110348,110360,110384,110398,110432,110460,110478,110492,110520,110532,110536,110544,110558,110658,110686,110714,110722,110724,110728,110736,110750,110752,110780,110796,110834,110836,110850,110852,110856,110864,110878,110880,110908,110912,110968,110982,111e3,111054,111074,111076,111080,111108,111112,111120,111134,111136,111164,111168,111224,111344,111372,111422,111456,111516,111554,111556,111560,111568,111590,111632,111646,111648,111676,111680,111736,111856,112096,112152,112224,112252,112320,112440,112514,112516,112520,112528,112542,112544,112588,112686,112718,112732,112782,112796,112824,112834,112836,112840,112848,112870,112890,112910,112924,112952,113008,113022,113026,113028,113032,113040,113054,113056,113100,113138,113140,113166,113180,113208,113264,113278,113376,113404,113416,113424,113440,113468,113472,113560,113614,113634,113636,113640,113686,113702,113708,113734,113740,113752,113778,113780,113798,113804,113816,113840,113854,113870,113890,113892,113896,113926,113932,113944,113968,113982,114016,114044,114076,114114,114116,114120,114128,114150,114170,114194,114196,114210,114212,114216,114242,114244,114248,114256,114270,114278,114306,114308,114312,114320,114334,114336,114364,114380,114420,114458,114478,114482,114484,114510,114524,114530,114532,114536,114842,114866,114868,114970,114994,114996,115042,115044,115048,115062,115130,115226,115250,115252,115278,115292,115298,115300,115304,115318,115342,115394,115396,115400,115408,115422,115430,115436,115450,115478,115494,115514,115526,115532,115570,115572,115738,115758,115762,115764,115790,115804,115810,115812,115816,115830,115854,115868,115896,115906,115912,115920,115934,115942,115948,115962,115996,116024,116080,116094,116098,116100,116104,116112,116126,116128,116156,116166,116172,116184,116206,116210,116212,116246,116262,116268,116282,116294,116300,116312,116334,116338,116340,116358,116364,116376,116400,116414,116430,116444,116450,116452,116456,116498,116500,116514,116520,116534,116546,116548,116552,116560,116574,116582,116588,116602,116654,116694,116714,116762,116782,116786,116788,116814,116828,116834,116836,116840,116854,116878,116892,116920,116930,116936,116944,116958,116966,116972,116986,117006,117048,117104,117118,117122,117124,117136,117150,117152,117180,117190,117196,117208,117230,117234,117236,117304,117360,117374,117472,117500,117506,117508,117512,117520,117536,117564,117568,117624,117638,117644,117656,117680,117694,117710,117724,117730,117732,117736,117750,117782,117798,117804,117818,117830,117848,117874,117876,117894,117936,117950,117966,117986,117988,117992,118022,118028,118040,118064,118078,118112,118140,118172,118210,118212,118216,118224,118238,118246,118266,118306,118312,118338,118352,118366,118374,118394,118402,118404,118408,118416,118430,118432,118460,118476,118514,118516,118574,118578,118580,118606,118620,118626,118628,118632,118678,118694,118700,118730,118738,118740,118830,118834,118836,118862,118876,118882,118884,118888,118902,118926,118940,118968,118978,118980,118984,118992,119006,119014,119020,119034,119068,119096,119152,119166,119170,119172,119176,119184,119198,119200,119228,119238,119244,119256,119278,119282,119284,119324,119352,119408,119422,119520,119548,119554,119556,119560,119568,119582,119584,119612,119616,119672,119686,119692,119704,119728,119742,119758,119772,119778,119780,119784,119798,119920,119934,120032,120060,120256,120312,120324,120328,120336,120352,120384,120440,120560,120582,120588,120600,120624,120638,120672,120700,120718,120732,120760,120770,120772,120776,120784,120798,120806,120812,120870,120876,120890,120902,120908,120920,120946,120948,120966,120972,120984,121008,121022,121038,121058,121060,121064,121078,121100,121112,121136,121150,121184,121212,121244,121282,121284,121288,121296,121318,121338,121356,121368,121392,121406,121440,121468,121536,121592,121656,121730,121732,121736,121744,121758,121760,121804,121842,121844,121890,121922,121924,121928,121936,121950,121958,121978,121986,121988,121992,122e3,122014,122016,122044,122060,122098,122100,122116,122120,122128,122142,122144,122172,122176,122232,122246,122264,122318,122338,122340,122344,122414,122418,122420,122446,122460,122466,122468,122472,122510,122524,122552,122562,122564,122568,122576,122598,122618,122646,122662,122668,122694,122700,122712,122738,122740,122762,122770,122772,122786,122788,122792,123018,123026,123028,123042,123044,123048,123062,123098,123146,123154,123156,123170,123172,123176,123190,123202,123204,123208,123216,123238,123244,123258,123290,123314,123316,123402,123410,123412,123426,123428,123432,123446,123458,123464,123472,123486,123494,123500,123514,123522,123524,123528,123536,123552,123580,123590,123596,123608,123630,123634,123636,123674,123698,123700,123740,123746,123748,123752,123834,123914,123922,123924,123938,123944,123958,123970,123976,123984,123998,124006,124012,124026,124034,124036,124048,124062,124064,124092,124102,124108,124120,124142,124146,124148,124162,124164,124168,124176,124190,124192,124220,124224,124280,124294,124300,124312,124336,124350,124366,124380,124386,124388,124392,124406,124442,124462,124466,124468,124494,124508,124514,124520,124558,124572,124600,124610,124612,124616,124624,124646,124666,124694,124710,124716,124730,124742,124748,124760,124786,124788,124818,124820,124834,124836,124840,124854,124946,124948,124962,124964,124968,124982,124994,124996,125e3,125008,125022,125030,125036,125050,125058,125060,125064,125072,125086,125088,125116,125126,125132,125144,125166,125170,125172,125186,125188,125192,125200,125216,125244,125248,125304,125318,125324,125336,125360,125374,125390,125404,125410,125412,125416,125430,125444,125448,125456,125472,125504,125560,125680,125702,125708,125720,125744,125758,125792,125820,125838,125852,125880,125890,125892,125896,125904,125918,125926,125932,125978,125998,126002,126004,126030,126044,126050,126052,126056,126094,126108,126136,126146,126148,126152,126160,126182,126202,126222,126236,126264,126320,126334,126338,126340,126344,126352,126366,126368,126412,126450,126452,126486,126502,126508,126522,126534,126540,126552,126574,126578,126580,126598,126604,126616,126640,126654,126670,126684,126690,126692,126696,126738,126754,126756,126760,126774,126786,126788,126792,126800,126814,126822,126828,126842,126894,126898,126900,126934,127126,127142,127148,127162,127178,127186,127188,127254,127270,127276,127290,127302,127308,127320,127342,127346,127348,127370,127378,127380,127394,127396,127400,127450,127510,127526,127532,127546,127558,127576,127598,127602,127604,127622,127628,127640,127664,127678,127694,127708,127714,127716,127720,127734,127754,127762,127764,127778,127784,127810,127812,127816,127824,127838,127846,127866,127898,127918,127922,127924,128022,128038,128044,128058,128070,128076,128088,128110,128114,128116,128134,128140,128152,128176,128190,128206,128220,128226,128228,128232,128246,128262,128268,128280,128304,128318,128352,128380,128398,128412,128440,128450,128452,128456,128464,128478,128486,128492,128506,128522,128530,128532,128546,128548,128552,128566,128578,128580,128584,128592,128606,128614,128634,128642,128644,128648,128656,128670,128672,128700,128716,128754,128756,128794,128814,128818,128820,128846,128860,128866,128868,128872,128886,128918,128934,128940,128954,128978,128980,129178,129198,129202,129204,129238,129258,129306,129326,129330,129332,129358,129372,129378,129380,129384,129398,129430,129446,129452,129466,129482,129490,129492,129562,129582,129586,129588,129614,129628,129634,129636,129640,129654,129678,129692,129720,129730,129732,129736,129744,129758,129766,129772,129814,129830,129836,129850,129862,129868,129880,129902,129906,129908,129930,129938,129940,129954,129956,129960,129974,130010]),Oe.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2e3,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1e3,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]);class ad{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class $e{static detectMultiple(e,n,i){let s=e.getBlackMatrix(),a=$e.detect(i,s);return a.length||(s=s.clone(),s.rotate180(),a=$e.detect(i,s)),new ad(s,a)}static detect(e,n){const i=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const d=$e.findVertices(n,s,a);if(d[0]==null&&d[3]==null){if(!l)break;l=!1,a=0;for(const h of i)h[1]!=null&&(s=Math.trunc(Math.max(s,h[1].getY()))),h[3]!=null&&(s=Math.max(s,Math.trunc(h[3].getY())));s+=$e.ROW_STEP;continue}if(l=!0,i.push(d),!e)break;d[2]!=null?(a=Math.trunc(d[2].getX()),s=Math.trunc(d[2].getY())):(a=Math.trunc(d[4].getX()),s=Math.trunc(d[4].getY()))}return i}static findVertices(e,n,i){const s=e.getHeight(),a=e.getWidth(),l=new Array(8);return $e.copyToResult(l,$e.findRowsWithPattern(e,s,a,n,i,$e.START_PATTERN),$e.INDEXES_START_PATTERN),l[4]!=null&&(i=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),$e.copyToResult(l,$e.findRowsWithPattern(e,s,a,n,i,$e.STOP_PATTERN),$e.INDEXES_STOP_PATTERN),l}static copyToResult(e,n,i){for(let s=0;s<i.length;s++)e[i[s]]=n[s]}static findRowsWithPattern(e,n,i,s,a,l){const d=new Array(4);let h=!1;const m=new Int32Array(l.length);for(;s<n;s+=$e.ROW_STEP){let E=$e.findGuardPattern(e,a,s,i,!1,l,m);if(E!=null){for(;s>0;){const I=$e.findGuardPattern(e,a,--s,i,!1,l,m);if(I!=null)E=I;else{s++;break}}d[0]=new T(E[0],s),d[1]=new T(E[1],s),h=!0;break}}let y=s+1;if(h){let E=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;y<n;y++){const R=$e.findGuardPattern(e,I[0],y,i,!1,l,m);if(R!=null&&Math.abs(I[0]-R[0])<$e.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<$e.MAX_PATTERN_DRIFT)I=R,E=0;else{if(E>$e.SKIPPED_ROW_COUNT_MAX)break;E++}}y-=E+1,d[2]=new T(I[0],y),d[3]=new T(I[1],y)}return y-s<$e.BARCODE_MIN_HEIGHT&&Z.fill(d,null),d}static findGuardPattern(e,n,i,s,a,l,d){Z.fillWithin(d,0,d.length,0);let h=n,m=0;for(;e.get(h,i)&&h>0&&m++<$e.MAX_PIXEL_DRIFT;)h--;let y=h,E=0,I=l.length;for(let R=a;y<s;y++)if(e.get(y,i)!==R)d[E]++;else{if(E===I-1){if($e.patternMatchVariance(d,l,$e.MAX_INDIVIDUAL_VARIANCE)<$e.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=d[0]+d[1],P.arraycopy(d,2,d,0,E-1),d[E-1]=0,d[E]=0,E--}else E++;d[E]=1,R=!R}return E===I-1&&$e.patternMatchVariance(d,l,$e.MAX_INDIVIDUAL_VARIANCE)<$e.MAX_AVG_VARIANCE?new Int32Array([h,y-1]):null}static patternMatchVariance(e,n,i){let s=e.length,a=0,l=0;for(let m=0;m<s;m++)a+=e[m],l+=n[m];if(a<l)return 1/0;let d=a/l;i*=d;let h=0;for(let m=0;m<s;m++){let y=e[m],E=n[m]*d,I=y>E?y-E:E-y;if(I>i)return 1/0;h+=I}return h/a}}$e.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),$e.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),$e.MAX_AVG_VARIANCE=.42,$e.MAX_INDIVIDUAL_VARIANCE=.8,$e.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),$e.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),$e.MAX_PIXEL_DRIFT=3,$e.MAX_PATTERN_DRIFT=5,$e.SKIPPED_ROW_COUNT_MAX=25,$e.ROW_STEP=5,$e.BARCODE_MIN_HEIGHT=10;class Ft{constructor(e,n){if(n.length===0)throw new A;this.field=e;let i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(i-s),P.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);if(e===1){let s=0;for(let a of this.coefficients)s=this.field.add(s,a);return s}let n=this.coefficients[0],i=this.coefficients.length;for(let s=1;s<i;s++)n=this.field.add(this.field.multiply(e,n),this.coefficients[s]);return n}add(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){let l=n;n=i,i=l}let s=new Int32Array(i.length),a=i.length-n.length;P.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=this.field.add(n[l-a],i[l]);return new Ft(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof Ft?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new Ft(this.field,new Int32Array([0]));let n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1);for(let d=0;d<i;d++){let h=n[d];for(let m=0;m<a;m++)l[d+m]=this.field.add(l[d+m],this.field.multiply(h,s[m]))}return new Ft(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let i=0;i<e;i++)n[i]=this.field.subtract(0,this.coefficients[i]);return new Ft(this.field,n)}multiplyScalar(e){if(e===0)return new Ft(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,i=new Int32Array(n);for(let s=0;s<n;s++)i[s]=this.field.multiply(this.coefficients[s],e);return new Ft(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new Ft(this.field,new Int32Array([0]));let i=this.coefficients.length,s=new Int32Array(i+e);for(let a=0;a<i;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new Ft(this.field,s)}toString(){let e=new ae;for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);i!==0&&(i<0?(e.append(" - "),i=-i):e.length()>0&&e.append(" + "),(n===0||i!==1)&&e.append(i),n!==0&&(n===1?e.append("x"):(e.append("x^"),e.append(n))))}return e.toString()}}class ld{add(e,n){return(e+n)%this.modulus}subtract(e,n){return(this.modulus+e-n)%this.modulus}exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}inverse(e){if(e===0)throw new $t;return this.expTable[this.modulus-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.modulus-1)]}getSize(){return this.modulus}equals(e){return e===this}}class ro extends ld{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let i=1;for(let s=0;s<e;s++)this.expTable[s]=i,i=i*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new Ft(this,new Int32Array([0])),this.one=new Ft(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;let i=new Int32Array(e+1);return i[0]=n,new Ft(this,i)}}ro.PDF417_GF=new ro(Oe.NUMBER_OF_CODEWORDS,3);class ps{constructor(){this.field=ro.PDF417_GF}decode(e,n,i){let s=new Ft(this.field,e),a=new Int32Array(n),l=!1;for(let F=n;F>0;F--){let U=s.evaluateAt(this.field.exp(F));a[n-F]=U,U!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const F of i){let U=this.field.exp(e.length-1-F),q=new Ft(this.field,new Int32Array([this.field.subtract(0,U),1]));d=d.multiply(q)}let h=new Ft(this.field,a),m=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=m[0],E=m[1],I=this.findErrorLocations(y),R=this.findErrorMagnitudes(E,y,I);for(let F=0;F<I.length;F++){let U=e.length-1-this.field.log(I[F]);if(U<0)throw O.getChecksumInstance();e[U]=this.field.subtract(e[U],R[F])}return I.length}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){let I=e;e=n,n=I}let s=e,a=n,l=this.field.getZero(),d=this.field.getOne();for(;a.getDegree()>=Math.round(i/2);){let I=s,R=l;if(s=a,l=d,s.isZero())throw O.getChecksumInstance();a=I;let F=this.field.getZero(),U=s.getCoefficient(s.getDegree()),q=this.field.inverse(U);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let ne=a.getDegree()-s.getDegree(),me=this.field.multiply(a.getCoefficient(a.getDegree()),q);F=F.add(this.field.buildMonomial(ne,me)),a=a.subtract(s.multiplyByMonomial(ne,me))}d=F.multiply(l).subtract(R).negative()}let h=d.getCoefficient(0);if(h===0)throw O.getChecksumInstance();let m=this.field.inverse(h),y=d.multiply(m),E=a.multiply(m);return[y,E]}findErrorLocations(e){let n=e.getDegree(),i=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(i[s]=this.field.inverse(a),s++);if(s!==n)throw O.getChecksumInstance();return i}findErrorMagnitudes(e,n,i){let s=n.getDegree(),a=new Int32Array(s);for(let m=1;m<=s;m++)a[s-m]=this.field.multiply(m,n.getCoefficient(m));let l=new Ft(this.field,a),d=i.length,h=new Int32Array(d);for(let m=0;m<d;m++){let y=this.field.inverse(i[m]),E=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[m]=this.field.multiply(E,I)}return h}}class nr{constructor(e,n,i,s,a){e instanceof nr?this.constructor_2(e):this.constructor_1(e,n,i,s,a)}constructor_1(e,n,i,s,a){const l=n==null||i==null,d=s==null||a==null;if(l&&d)throw new D;l?(n=new T(0,s.getY()),i=new T(0,a.getY())):d&&(s=new T(e.getWidth()-1,n.getY()),a=new T(e.getWidth()-1,i.getY())),this.image=e,this.topLeft=n,this.bottomLeft=i,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),i.getX())),this.maxX=Math.trunc(Math.max(s.getX(),a.getX())),this.minY=Math.trunc(Math.min(n.getY(),s.getY())),this.maxY=Math.trunc(Math.max(i.getY(),a.getY()))}constructor_2(e){this.image=e.image,this.topLeft=e.getTopLeft(),this.bottomLeft=e.getBottomLeft(),this.topRight=e.getTopRight(),this.bottomRight=e.getBottomRight(),this.minX=e.getMinX(),this.maxX=e.getMaxX(),this.minY=e.getMinY(),this.maxY=e.getMaxY()}static merge(e,n){return e==null?n:n==null?e:new nr(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,i){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,d=this.bottomRight;if(e>0){let h=i?this.topLeft:this.topRight,m=Math.trunc(h.getY()-e);m<0&&(m=0);let y=new T(h.getX(),m);i?s=y:l=y}if(n>0){let h=i?this.bottomLeft:this.bottomRight,m=Math.trunc(h.getY()+n);m>=this.image.getHeight()&&(m=this.image.getHeight()-1);let y=new T(h.getX(),m);i?a=y:d=y}return new nr(this.image,s,a,l,d)}getMinX(){return this.minX}getMaxX(){return this.maxX}getMinY(){return this.minY}getMaxY(){return this.maxY}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}getBottomLeft(){return this.bottomLeft}getBottomRight(){return this.bottomRight}}class cd{constructor(e,n,i,s){this.columnCount=e,this.errorCorrectionLevel=s,this.rowCountUpperPart=n,this.rowCountLowerPart=i,this.rowCount=n+i}getColumnCount(){return this.columnCount}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getRowCount(){return this.rowCount}getRowCountUpperPart(){return this.rowCountUpperPart}getRowCountLowerPart(){return this.rowCountLowerPart}}class kr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,m,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=m?parseInt(m.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(E){case"s":R=n[i];break;case"c":R=n[i][0];break;case"f":R=parseFloat(n[i]).toFixed(l);break;case"p":R=parseFloat(n[i]).toPrecision(l);break;case"e":R=parseFloat(n[i]).toExponential(l);break;case"x":R=parseInt(n[i]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let F=parseInt(h),U=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+U:U+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=kr.form(e,n)}toString(){return this.buffer}}class Mr{constructor(e){this.boundingBox=new nr(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let i=1;i<Mr.MAX_NEARBY_DISTANCE;i++){let s=this.imageRowToCodewordIndex(e)-i;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+i,s<this.codewords.length&&(n=this.codewords[s],n!=null)))return n}return null}imageRowToCodewordIndex(e){return e-this.boundingBox.getMinY()}setCodeword(e,n){this.codewords[this.imageRowToCodewordIndex(e)]=n}getCodeword(e){return this.codewords[this.imageRowToCodewordIndex(e)]}getBoundingBox(){return this.boundingBox}getCodewords(){return this.codewords}toString(){const e=new kr;let n=0;for(const i of this.codewords){if(i==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,i.getRowNumber(),i.getValue())}return e.toString()}}Mr.MAX_NEARBY_DISTANCE=5;class Dr{constructor(){this.values=new Map}setValue(e){e=Math.trunc(e);let n=this.values.get(e);n==null&&(n=0),n++,this.values.set(e,n)}getValue(){let e=-1,n=new Array;for(const[i,s]of this.values.entries()){const a={getKey:()=>i,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return Oe.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class ms extends Mr{constructor(e,n){super(e),this._isLeft=n}setRowNumbers(){for(let e of this.getCodewords())e?.setRowNumberAsRowIndicatorColumn()}adjustCompleteIndicatorColumnRowNumbers(e){let n=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(n,e);let i=this.getBoundingBox(),s=this._isLeft?i.getTopLeft():i.getTopRight(),a=this._isLeft?i.getBottomLeft():i.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,m=1,y=0;for(let E=l;E<d;E++){if(n[E]==null)continue;let I=n[E],R=I.getRowNumber()-h;if(R===0)y++;else if(R===1)m=Math.max(m,y),y=1,h=I.getRowNumber();else if(R<0||I.getRowNumber()>=e.getRowCount()||R>E)n[E]=null;else{let F;m>2?F=(m-2)*R:F=R;let U=F>=E;for(let q=1;q<=F&&!U;q++)U=n[E-q]!=null;U?n[E]=null:(h=I.getRowNumber(),y=1)}}}getRowHeights(){let e=this.getBarcodeMetadata();if(e==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(e);let n=new Int32Array(e.getRowCount());for(let i of this.getCodewords())if(i!=null){let s=i.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),i=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(i.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.getCodewords(),h=-1;for(let m=a;m<l;m++){if(d[m]==null)continue;let y=d[m];y.setRowNumberAsRowIndicatorColumn();let E=y.getRowNumber()-h;E===0||(E===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?d[m]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Dr,i=new Dr,s=new Dr,a=new Dr;for(let d of e){if(d==null)continue;d.setRowNumberAsRowIndicatorColumn();let h=d.getValue()%30,m=d.getRowNumber();switch(this._isLeft||(m+=2),m%3){case 0:i.setValue(h*3+1);break;case 1:a.setValue(h/3),s.setValue(h%3);break;case 2:n.setValue(h+1);break}}if(n.getValue().length===0||i.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||i.getValue()[0]+s.getValue()[0]<Oe.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>Oe.MAX_ROWS_IN_BARCODE)return null;let l=new cd(n.getValue()[0],i.getValue()[0],s.getValue()[0],a.getValue()[0]);return this.removeIncorrectCodewords(e,l),l}removeIncorrectCodewords(e,n){for(let i=0;i<e.length;i++){let s=e[i];if(e[i]==null)continue;let a=s.getValue()%30,l=s.getRowNumber();if(l>n.getRowCount()){e[i]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:a*3+1!==n.getRowCountUpperPart()&&(e[i]=null);break;case 1:(Math.trunc(a/3)!==n.getErrorCorrectionLevel()||a%3!==n.getRowCountLowerPart())&&(e[i]=null);break;case 2:a+1!==n.getColumnCount()&&(e[i]=null);break}}}isLeft(){return this._isLeft}toString(){return"IsLeft: "+this._isLeft+`
|
|
65
|
-
`+super.toString()}}class Pr{constructor(e,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=e,this.barcodeColumnCount=e.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let e=Oe.MAX_CODEWORDS_IN_BARCODE,n;do n=e,e=this.adjustRowNumbersAndGetCount();while(e>0&&e<n);return this.detectionResultColumns}adjustIndicatorColumnRowNumbers(e){e?.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)}adjustRowNumbersAndGetCount(){let e=this.adjustRowNumbersByRow();if(e===0)return 0;for(let n=1;n<this.barcodeColumnCount+1;n++){let i=this.detectionResultColumns[n].getCodewords();for(let s=0;s<i.length;s++)i[s]!=null&&(i[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,i))}return e}adjustRowNumbersByRow(){return this.adjustRowNumbersFromBothRI(),this.adjustRowNumbersFromLRI()+this.adjustRowNumbersFromRRI()}adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)return;let e=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<e.length;i++)if(e[i]!=null&&n[i]!=null&&e[i].getRowNumber()===n[i].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[i];a!=null&&(a.setRowNumber(e[i].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[i]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,i){return i==null||i.hasValidRowNumber()||(i.isValidRowNumber(e)?(i.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,i){if(!this.detectionResultColumns[e-1])return;let s=i[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let d=new Array(14);d[2]=a[n],d[3]=l[n],n>0&&(d[0]=i[n-1],d[4]=a[n-1],d[5]=l[n-1]),n>1&&(d[8]=i[n-2],d[10]=a[n-2],d[11]=l[n-2]),n<i.length-1&&(d[1]=i[n+1],d[6]=a[n+1],d[7]=l[n+1]),n<i.length-2&&(d[9]=i[n+2],d[12]=a[n+2],d[13]=l[n+2]);for(let h of d)if(Pr.adjustRowNumber(s,h))return}static adjustRowNumber(e,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===e.getBucket()?(e.setRowNumber(n.getRowNumber()),!0):!1}getBarcodeColumnCount(){return this.barcodeColumnCount}getBarcodeRowCount(){return this.barcodeMetadata.getRowCount()}getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel()}setBoundingBox(e){this.boundingBox=e}getBoundingBox(){return this.boundingBox}setDetectionResultColumn(e,n){this.detectionResultColumns[e]=n}getDetectionResultColumn(e){return this.detectionResultColumns[e]}toString(){let e=this.detectionResultColumns[0];e==null&&(e=this.detectionResultColumns[this.barcodeColumnCount+1]);let n=new kr;for(let i=0;i<e.getCodewords().length;i++){n.format("CW %3d:",i);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[i];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Br{constructor(e,n,i,s){this.rowNumber=Br.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(i),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Br.BARCODE_ROW_UNKNOWN&&this.bucket===e%3*3}setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))}getWidth(){return this.endX-this.startX}getStartX(){return this.startX}getEndX(){return this.endX}getBucket(){return this.bucket}getValue(){return this.value}getRowNumber(){return this.rowNumber}setRowNumber(e){this.rowNumber=e}toString(){return this.rowNumber+"|"+this.value}}Br.BARCODE_ROW_UNKNOWN=-1;class Kt{static initialize(){for(let e=0;e<Oe.SYMBOL_TABLE.length;e++){let n=Oe.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<Oe.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,Kt.RATIOS_TABLE[e]||(Kt.RATIOS_TABLE[e]=new Array(Oe.BARS_IN_MODULE)),Kt.RATIOS_TABLE[e][Oe.BARS_IN_MODULE-s-1]=Math.fround(a/Oe.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=Kt.getDecodedCodewordValue(Kt.sampleBitCounts(e));return n!==-1?n:Kt.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=je.sum(e),i=new Int32Array(Oe.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Oe.MODULES_IN_CODEWORD;l++){let d=n/(2*Oe.MODULES_IN_CODEWORD)+l*n/Oe.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=Kt.getBitValue(e);return Oe.getCodeword(n)===-1?-1:n}static getBitValue(e){let n=0;for(let i=0;i<e.length;i++)for(let s=0;s<e[i];s++)n=n<<1|(i%2===0?1:0);return Math.trunc(n)}static getClosestDecodedValue(e){let n=je.sum(e),i=new Array(Oe.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=En.MAX_VALUE,a=-1;this.bSymbolTableReady||Kt.initialize();for(let l=0;l<Kt.RATIOS_TABLE.length;l++){let d=0,h=Kt.RATIOS_TABLE[l];for(let m=0;m<Oe.BARS_IN_MODULE;m++){let y=Math.fround(h[m]-i[m]);if(d+=Math.fround(y*y),d>=s)break}d<s&&(s=d,a=Oe.SYMBOL_TABLE[l])}return a}}Kt.bSymbolTableReady=!1,Kt.RATIOS_TABLE=new Array(Oe.SYMBOL_TABLE.length).map(b=>new Array(Oe.BARS_IN_MODULE));class gs{constructor(){this.segmentCount=-1,this.fileSize=-1,this.timestamp=-1,this.checksum=-1}getSegmentIndex(){return this.segmentIndex}setSegmentIndex(e){this.segmentIndex=e}getFileId(){return this.fileId}setFileId(e){this.fileId=e}getOptionalData(){return this.optionalData}setOptionalData(e){this.optionalData=e}isLastSegment(){return this.lastSegment}setLastSegment(e){this.lastSegment=e}getSegmentCount(){return this.segmentCount}setSegmentCount(e){this.segmentCount=e}getSender(){return this.sender||null}setSender(e){this.sender=e}getAddressee(){return this.addressee||null}setAddressee(e){this.addressee=e}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getFileSize(){return this.fileSize}setFileSize(e){this.fileSize=e}getChecksum(){return this.checksum}setChecksum(e){this.checksum=e}getTimestamp(){return this.timestamp}setTimestamp(e){this.timestamp=e}}class xs{static parseLong(e,n=void 0){return parseInt(e,n)}}class ys extends g{}ys.kind="NullPointerException";class ud{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new ys;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new L;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class dd extends g{}class fd extends ud{constructor(e=32){if(super(),this.count=0,e<0)throw new A("Negative initial size: "+e);this.buf=new Uint8Array(e)}ensureCapacity(e){e-this.buf.length>0&&this.grow(e)}grow(e){let i=this.buf.length<<1;if(i-e<0&&(i=e),i<0){if(e<0)throw new dd;i=$.MAX_VALUE}this.buf=Z.copyOfUint8Array(this.buf,i)}write(e){this.ensureCapacity(this.count+1),this.buf[this.count]=e,this.count+=1}writeBytesOffset(e,n,i){if(n<0||n>e.length||i<0||n+i-e.length>0)throw new L;this.ensureCapacity(this.count+i),P.arraycopy(e,n,this.buf,this.count,i),this.count+=i}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return Z.copyOfUint8Array(this.buf,this.count)}size(){return this.count}toString(e){return e?typeof e=="string"?this.toString_string(e):this.toString_number(e):this.toString_void()}toString_void(){return new String(this.buf).toString()}toString_string(e){return new String(this.buf).toString()}toString_number(e){return new String(this.buf).toString()}close(){}}var it;(function(b){b[b.ALPHA=0]="ALPHA",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.PUNCT=3]="PUNCT",b[b.ALPHA_SHIFT=4]="ALPHA_SHIFT",b[b.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(it||(it={}));function ws(){if(typeof window<"u")return window.BigInt||null;if(typeof Ci<"u")return Ci.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let hi;function jn(b){if(typeof hi>"u"&&(hi=ws()),hi===null)throw new Error("BigInt is not supported!");return hi(b)}function hd(){let b=[];b[0]=jn(1);let e=jn(900);b[1]=e;for(let n=2;n<16;n++)b[n]=b[n-1]*e;return b}class te{static decode(e,n){let i=new ae(""),s=M.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new gs;for(;a<e[0];){switch(l){case te.TEXT_COMPACTION_MODE_LATCH:a=te.textCompaction(e,a,i);break;case te.BYTE_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH_6:a=te.byteCompaction(l,e,s,a,i);break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:i.append(e[a++]);break;case te.NUMERIC_COMPACTION_MODE_LATCH:a=te.numericCompaction(e,a,i);break;case te.ECI_CHARSET:M.getCharacterSetECIByValue(e[a++]);break;case te.ECI_GENERAL_PURPOSE:a+=2;break;case te.ECI_USER_DEFINED:a++;break;case te.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=te.decodeMacroBlock(e,a,d);break;case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case te.MACRO_PDF417_TERMINATOR:throw new V;default:a--,a=te.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw V.getFormatInstance()}if(i.length()===0)throw V.getFormatInstance();let h=new Ne(null,i.toString(),null,n);return h.setOther(d),h}static decodeMacroBlock(e,n,i){if(n+te.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw V.getFormatInstance();let s=new Int32Array(te.NUMBER_OF_SEQUENCE_CODEWORDS);for(let d=0;d<te.NUMBER_OF_SEQUENCE_CODEWORDS;d++,n++)s[d]=e[n];i.setSegmentIndex($.parseInt(te.decodeBase900toBase10(s,te.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new ae;n=te.textCompaction(e,n,a),i.setFileId(a.toString());let l=-1;for(e[n]===te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case te.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let d=new ae;n=te.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case te.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new ae;n=te.textCompaction(e,n+1,h),i.setSender(h.toString());break;case te.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let m=new ae;n=te.textCompaction(e,n+1,m),i.setAddressee(m.toString());break;case te.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new ae;n=te.numericCompaction(e,n+1,y),i.setSegmentCount($.parseInt(y.toString()));break;case te.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let E=new ae;n=te.numericCompaction(e,n+1,E),i.setTimestamp(xs.parseLong(E.toString()));break;case te.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new ae;n=te.numericCompaction(e,n+1,I),i.setChecksum($.parseInt(I.toString()));break;case te.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let R=new ae;n=te.numericCompaction(e,n+1,R),i.setFileSize(xs.parseLong(R.toString()));break;default:throw V.getFormatInstance()}break;case te.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw V.getFormatInstance()}if(l!==-1){let d=n-l;i.isLastSegment()&&d--,i.setOptionalData(Z.copyOfRange(e,l,l+d))}return n}static textCompaction(e,n,i){let s=new Int32Array((e[0]-n)*2),a=new Int32Array((e[0]-n)*2),l=0,d=!1;for(;n<e[0]&&!d;){let h=e[n++];if(h<te.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case te.TEXT_COMPACTION_MODE_LATCH:s[l++]=te.TEXT_COMPACTION_MODE_LATCH;break;case te.BYTE_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH_6:case te.NUMERIC_COMPACTION_MODE_LATCH:case te.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case te.MACRO_PDF417_TERMINATOR:n--,d=!0;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return te.decodeTextCompaction(s,a,l,i),n}static decodeTextCompaction(e,n,i,s){let a=it.ALPHA,l=it.ALPHA,d=0;for(;d<i;){let h=e[d],m="";switch(a){case it.ALPHA:if(h<26)m=String.fromCharCode(65+h);else switch(h){case 26:m=" ";break;case te.LL:a=it.LOWER;break;case te.ML:a=it.MIXED;break;case te.PS:l=a,a=it.PUNCT_SHIFT;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.LOWER:if(h<26)m=String.fromCharCode(97+h);else switch(h){case 26:m=" ";break;case te.AS:l=a,a=it.ALPHA_SHIFT;break;case te.ML:a=it.MIXED;break;case te.PS:l=a,a=it.PUNCT_SHIFT;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.MIXED:if(h<te.PL)m=te.MIXED_CHARS[h];else switch(h){case te.PL:a=it.PUNCT;break;case 26:m=" ";break;case te.LL:a=it.LOWER;break;case te.AL:a=it.ALPHA;break;case te.PS:l=a,a=it.PUNCT_SHIFT;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT:if(h<te.PAL)m=te.PUNCT_CHARS[h];else switch(h){case te.PAL:a=it.ALPHA;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.ALPHA_SHIFT:if(a=l,h<26)m=String.fromCharCode(65+h);else switch(h){case 26:m=" ";break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT_SHIFT:if(a=l,h<te.PAL)m=te.PUNCT_CHARS[h];else switch(h){case te.PAL:a=it.ALPHA;break;case te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case te.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break}m!==""&&s.append(m),d++}}static byteCompaction(e,n,i,s,a){let l=new fd,d=0,h=0,m=!1;switch(e){case te.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),E=n[s++];for(;s<n[0]&&!m;)switch(y[d++]=E,h=900*h+E,E=n[s++],E){case te.TEXT_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH:case te.NUMERIC_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH_6:case te.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case te.MACRO_PDF417_TERMINATOR:s--,m=!0;break;default:if(d%5===0&&d>0){for(let I=0;I<6;++I)l.write(Number(jn(h)>>jn(8*(5-I))));h=0,d=0}break}s===n[0]&&E<te.TEXT_COMPACTION_MODE_LATCH&&(y[d++]=E);for(let I=0;I<d;I++)l.write(y[I]);break;case te.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!m;){let I=n[s++];if(I<te.TEXT_COMPACTION_MODE_LATCH)d++,h=900*h+I;else switch(I){case te.TEXT_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH:case te.NUMERIC_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH_6:case te.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case te.MACRO_PDF417_TERMINATOR:s--,m=!0;break}if(d%5===0&&d>0){for(let R=0;R<6;++R)l.write(Number(jn(h)>>jn(8*(5-R))));h=0,d=0}}break}return a.append(le.decode(l.toByteArray(),i)),s}static numericCompaction(e,n,i){let s=0,a=!1,l=new Int32Array(te.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let d=e[n++];if(n===e[0]&&(a=!0),d<te.TEXT_COMPACTION_MODE_LATCH)l[s]=d,s++;else switch(d){case te.TEXT_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH:case te.BYTE_COMPACTION_MODE_LATCH_6:case te.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case te.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%te.MAX_NUMERIC_CODEWORDS===0||d===te.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(i.append(te.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let i=jn(0);for(let a=0;a<n;a++)i+=te.EXP900[n-a-1]*jn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new V;return s.substring(1)}}te.TEXT_COMPACTION_MODE_LATCH=900,te.BYTE_COMPACTION_MODE_LATCH=901,te.NUMERIC_COMPACTION_MODE_LATCH=902,te.BYTE_COMPACTION_MODE_LATCH_6=924,te.ECI_USER_DEFINED=925,te.ECI_GENERAL_PURPOSE=926,te.ECI_CHARSET=927,te.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,te.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,te.MACRO_PDF417_TERMINATOR=922,te.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,te.MAX_NUMERIC_CODEWORDS=15,te.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,te.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,te.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,te.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,te.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,te.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,te.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,te.PL=25,te.LL=27,te.AS=27,te.ML=28,te.AL=28,te.PS=29,te.PAL=29,te.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
|
|
66
|
-
-.$/"|*()?{}'`,te.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",te.EXP900=ws()?hd():[],te.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ze{constructor(){}static decode(e,n,i,s,a,l,d){let h=new nr(e,n,i,s,a),m=null,y=null,E;for(let F=!0;;F=!1){if(n!=null&&(m=Ze.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(y=Ze.getRowIndicatorColumn(e,h,s,!1,l,d)),E=Ze.merge(m,y),E==null)throw D.getNotFoundInstance();let U=E.getBoundingBox();if(F&&U!=null&&(U.getMinY()<h.getMinY()||U.getMaxY()>h.getMaxY()))h=U;else break}E.setBoundingBox(h);let I=E.getBarcodeColumnCount()+1;E.setDetectionResultColumn(0,m),E.setDetectionResultColumn(I,y);let R=m!=null;for(let F=1;F<=I;F++){let U=R?F:I-F;if(E.getDetectionResultColumn(U)!==void 0)continue;let q;U===0||U===I?q=new ms(h,U===0):q=new Mr(h),E.setDetectionResultColumn(U,q);let ne=-1,me=ne;for(let xe=h.getMinY();xe<=h.getMaxY();xe++){if(ne=Ze.getStartColumn(E,U,xe,R),ne<0||ne>h.getMaxX()){if(me===-1)continue;ne=me}let ue=Ze.detectCodeword(e,h.getMinX(),h.getMaxX(),R,ne,xe,l,d);ue!=null&&(q.setCodeword(xe,ue),me=ne,l=Math.min(l,ue.getWidth()),d=Math.max(d,ue.getWidth()))}}return Ze.createDecoderResult(E)}static merge(e,n){if(e==null&&n==null)return null;let i=Ze.getBarcodeMetadata(e,n);if(i==null)return null;let s=nr.merge(Ze.adjustBoundingBox(e),Ze.adjustBoundingBox(n));return new Pr(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=Ze.getMax(n),s=0;for(let d of n)if(s+=i-d,d>0)break;let a=e.getCodewords();for(let d=0;s>0&&a[d]==null;d++)s--;let l=0;for(let d=n.length-1;d>=0&&(l+=i-n[d],!(n[d]>0));d--);for(let d=a.length-1;l>0&&a[d]==null;d--)l--;return e.getBoundingBox().addMissingRows(s,l,e.isLeft())}static getMax(e){let n=-1;for(let i of e)n=Math.max(n,i);return n}static getBarcodeMetadata(e,n){let i;if(e==null||(i=e.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();let s;return n==null||(s=n.getBarcodeMetadata())==null?i:i.getColumnCount()!==s.getColumnCount()&&i.getErrorCorrectionLevel()!==s.getErrorCorrectionLevel()&&i.getRowCount()!==s.getRowCount()?null:i}static getRowIndicatorColumn(e,n,i,s,a,l){let d=new ms(n,s);for(let h=0;h<2;h++){let m=h===0?1:-1,y=Math.trunc(Math.trunc(i.getX()));for(let E=Math.trunc(Math.trunc(i.getY()));E<=n.getMaxY()&&E>=n.getMinY();E+=m){let I=Ze.detectCodeword(e,0,e.getWidth(),s,y,E,a,l);I!=null&&(d.setCodeword(E,I),s?y=I.getStartX():y=I.getEndX())}}return d}static adjustCodewordCount(e,n){let i=n[0][1],s=i.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ze.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Oe.MAX_CODEWORDS_IN_BARCODE)throw D.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=Ze.createBarcodeMatrix(e);Ze.adjustCodewordCount(e,n);let i=new Array,s=new Int32Array(e.getBarcodeRowCount()*e.getBarcodeColumnCount()),a=[],l=new Array;for(let h=0;h<e.getBarcodeRowCount();h++)for(let m=0;m<e.getBarcodeColumnCount();m++){let y=n[h][m+1].getValue(),E=h*e.getBarcodeColumnCount()+m;y.length===0?i.push(E):y.length===1?s[E]=y[0]:(l.push(E),a.push(y))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return Ze.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Oe.toIntArray(i),Oe.toIntArray(l),d)}static createDecoderResultFromAmbiguousValues(e,n,i,s,a){let l=new Int32Array(s.length),d=100;for(;d-- >0;){for(let h=0;h<l.length;h++)n[s[h]]=a[h][l[h]];try{return Ze.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof O))throw h}if(l.length===0)throw O.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw O.getChecksumInstance()}throw O.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Dr;let i=0;for(let s of e.getDetectionResultColumns()){if(s!=null){for(let a of s.getCodewords())if(a!=null){let l=a.getRowNumber();if(l>=0){if(l>=n.length)continue;n[l][i].setValue(a.getValue())}}}i++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,i,s){let a=s?1:-1,l=null;if(Ze.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodeword(i)),l!=null)return s?l.getEndX():l.getStartX();if(l=e.getDetectionResultColumn(n).getCodewordNearby(i),l!=null)return s?l.getStartX():l.getEndX();if(Ze.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;Ze.isValidBarcodeColumn(e,n-a);){n-=a;for(let h of e.getDetectionResultColumn(n).getCodewords())if(h!=null)return(s?h.getEndX():h.getStartX())+a*d*(h.getEndX()-h.getStartX());d++}return s?e.getBoundingBox().getMinX():e.getBoundingBox().getMaxX()}static detectCodeword(e,n,i,s,a,l,d,h){a=Ze.adjustCodewordStartColumn(e,n,i,s,a,l);let m=Ze.getModuleBitCount(e,n,i,s,a,l);if(m==null)return null;let y,E=je.sum(m);if(s)y=a+E;else{for(let F=0;F<m.length/2;F++){let U=m[F];m[F]=m[m.length-1-F],m[m.length-1-F]=U}y=a,a=y-E}if(!Ze.checkCodewordSkew(E,d,h))return null;let I=Kt.getDecodedValue(m),R=Oe.getCodeword(I);return R===-1?null:new Br(a,y,Ze.getCodewordBucketNumber(I),R)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),m=0,y=s?1:-1,E=s;for(;(s?d<i:d>=n)&&m<h.length;)e.get(d,l)===E?(h[m]++,d+=y):(m++,E=!E);return m===h.length||d===(s?i:n)&&m===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,i,s,a,l){let d=a,h=s?-1:1;for(let m=0;m<2;m++){for(;(s?d>=n:d<i)&&s===e.get(d,l);){if(Math.abs(a-d)>Ze.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-Ze.CODEWORD_SKEW_SIZE<=e&&e<=i+Ze.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw V.getFormatInstance();let s=1<<n+1,a=Ze.correctErrors(e,i,s);Ze.verifyCodewordCount(e,s);let l=te.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(i.length),l}static correctErrors(e,n,i){if(n!=null&&n.length>i/2+Ze.MAX_ERRORS||i<0||i>Ze.MAX_EC_CODEWORDS)throw O.getChecksumInstance();return Ze.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw V.getFormatInstance();let i=e[0];if(i>e.length)throw V.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw V.getFormatInstance()}static getBitCountForCodeword(e){let n=new Int32Array(8),i=0,s=n.length-1;for(;!((e&1)!==i&&(i=e&1,s--,s<0));)n[s]++,e>>=1;return n}static getCodewordBucketNumber(e){return e instanceof Int32Array?this.getCodewordBucketNumber_Int32Array(e):this.getCodewordBucketNumber_number(e)}static getCodewordBucketNumber_number(e){return Ze.getCodewordBucketNumber(Ze.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new kr;for(let i=0;i<e.length;i++){n.format("Row %2d: ",i);for(let s=0;s<e[i].length;s++){let a=e[i][s];a.getValue().length===0?n.format(" ",null):n.format("%4d(%2d)",a.getValue()[0],a.getConfidence(a.getValue()[0]))}n.format("%n")}return n.toString()}}Ze.CODEWORD_SKEW_SIZE=2,Ze.MAX_ERRORS=3,Ze.MAX_EC_CODEWORDS=512,Ze.errorCorrection=new ps;class Ut{decode(e,n=null){let i=Ut.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw D.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Ut.decode(e,n,!0)}catch(i){throw i instanceof V||i instanceof O?D.getNotFoundInstance():i}}static decode(e,n,i){const s=new Array,a=$e.detectMultiple(e,n,i);for(const l of a.getPoints()){const d=Ze.decode(a.getBits(),l[4],l[5],l[6],l[7],Ut.getMinCodewordWidth(l),Ut.getMaxCodewordWidth(l)),h=new Me(d.getText(),d.getRawBytes(),void 0,l,ie.PDF_417);h.putMetadata(Ae.ERROR_CORRECTION_LEVEL,d.getECLevel());const m=d.getOther();m!=null&&h.putMetadata(Ae.PDF417_EXTRA_METADATA,m),s.push(h)}return s.map(l=>l)}static getMaxWidth(e,n){return e==null||n==null?0:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMinWidth(e,n){return e==null||n==null?$.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Ut.getMaxWidth(e[0],e[4]),Ut.getMaxWidth(e[6],e[2])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN),Math.max(Ut.getMaxWidth(e[1],e[5]),Ut.getMaxWidth(e[7],e[3])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Ut.getMinWidth(e[0],e[4]),Ut.getMinWidth(e[6],e[2])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN),Math.min(Ut.getMinWidth(e[1],e[5]),Ut.getMinWidth(e[7],e[3])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN)))}reset(){}}class pi extends g{}pi.kind="ReaderException";class _s{constructor(e,n){this.verbose=e===!0,n&&this.setHints(n)}decode(e,n){return n&&this.setHints(n),this.decodeInternal(e)}decodeWithState(e){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(e)}setHints(e){this.hints=e;const n=!c(e)&&e.get(j.TRY_HARDER)===!0,i=c(e)?null:e.get(j.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===ie.UPC_A||l===ie.UPC_E||l===ie.EAN_13||l===ie.EAN_8||l===ie.CODABAR||l===ie.CODE_39||l===ie.CODE_93||l===ie.CODE_128||l===ie.ITF||l===ie.RSS_14||l===ie.RSS_EXPANDED);a&&!n&&s.push(new yr(e,this.verbose)),i.includes(ie.QR_CODE)&&s.push(new Zn),i.includes(ie.DATA_MATRIX)&&s.push(new Vn),i.includes(ie.AZTEC)&&s.push(new pr),i.includes(ie.PDF_417)&&s.push(new Ut),a&&n&&s.push(new yr(e,this.verbose))}s.length===0&&(n||s.push(new yr(e,this.verbose)),s.push(new Zn),s.push(new Vn),s.push(new pr),s.push(new Ut),n&&s.push(new yr(e,this.verbose))),this.readers=s}reset(){if(this.readers!==null)for(const e of this.readers)e.reset()}decodeInternal(e){if(this.readers===null)throw new pi("No readers where selected, nothing can be read.");for(const n of this.readers)try{return n.decode(e,this.hints)}catch(i){if(i instanceof pi)continue}throw new D("No MultiFormat Readers were able to detect the code.")}}class pd extends Ve{constructor(e=null,n=500){const i=new _s;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class md extends Ve{constructor(e=500){super(new Ut,e)}}class gd extends Ve{constructor(e=500){super(new Zn,e)}}var io;(function(b){b[b.ERROR_CORRECTION=0]="ERROR_CORRECTION",b[b.CHARACTER_SET=1]="CHARACTER_SET",b[b.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",b[b.MIN_SIZE=3]="MIN_SIZE",b[b.MAX_SIZE=4]="MAX_SIZE",b[b.MARGIN=5]="MARGIN",b[b.PDF417_COMPACT=6]="PDF417_COMPACT",b[b.PDF417_COMPACTION=7]="PDF417_COMPACTION",b[b.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",b[b.AZTEC_LAYERS=9]="AZTEC_LAYERS",b[b.QR_VERSION=10]="QR_VERSION"})(io||(io={}));var Rt=io;class oo{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new Xe(e,Int32Array.from([1])))}buildGenerator(e){const n=this.cachedGenerators;if(e>=n.length){let i=n[n.length-1];const s=this.field;for(let a=n.length;a<=e;a++){const l=i.multiply(new Xe(s,Int32Array.from([1,s.exp(a-1+s.getGeneratorBase())])));n.push(l),i=l}}return n[e]}encode(e,n){if(n===0)throw new A("No error correction bytes");const i=e.length-n;if(i<=0)throw new A("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(i);P.arraycopy(e,0,a,0,i);let l=new Xe(this.field,a);l=l.multiplyByMonomial(n,1);const h=l.divide(s)[1].getCoefficients(),m=n-h.length;for(let y=0;y<m;y++)e[i+y]=0;P.arraycopy(h,0,e,i+m,h.length)}}class It{constructor(){}static applyMaskPenaltyRule1(e){return It.applyMaskPenaltyRule1Internal(e,!0)+It.applyMaskPenaltyRule1Internal(e,!1)}static applyMaskPenaltyRule2(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a-1;l++){const d=i[l];for(let h=0;h<s-1;h++){const m=d[h];m===d[h+1]&&m===i[l+1][h]&&m===i[l+1][h+1]&&n++}}return It.N2*n}static applyMaskPenaltyRule3(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a;l++)for(let d=0;d<s;d++){const h=i[l];d+6<s&&h[d]===1&&h[d+1]===0&&h[d+2]===1&&h[d+3]===1&&h[d+4]===1&&h[d+5]===0&&h[d+6]===1&&(It.isWhiteHorizontal(h,d-4,d)||It.isWhiteHorizontal(h,d+7,d+11))&&n++,l+6<a&&i[l][d]===1&&i[l+1][d]===0&&i[l+2][d]===1&&i[l+3][d]===1&&i[l+4][d]===1&&i[l+5][d]===0&&i[l+6][d]===1&&(It.isWhiteVertical(i,d,l-4,l)||It.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*It.N3}static isWhiteHorizontal(e,n,i){n=Math.max(n,0),i=Math.min(i,e.length);for(let s=n;s<i;s++)if(e[s]===1)return!1;return!0}static isWhiteVertical(e,n,i,s){i=Math.max(i,0),s=Math.min(s,e.length);for(let a=i;a<s;a++)if(e[a][n]===1)return!1;return!0}static applyMaskPenaltyRule4(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let h=0;h<a;h++){const m=i[h];for(let y=0;y<s;y++)m[y]===1&&n++}const l=e.getHeight()*e.getWidth();return Math.floor(Math.abs(n*2-l)*10/l)*It.N4}static getDataMaskBit(e,n,i){let s,a;switch(e){case 0:s=i+n&1;break;case 1:s=i&1;break;case 2:s=n%3;break;case 3:s=(i+n)%3;break;case 4:s=Math.floor(i/2)+Math.floor(n/3)&1;break;case 5:a=i*n,s=(a&1)+a%3;break;case 6:a=i*n,s=(a&1)+a%3&1;break;case 7:a=i*n,s=a%3+(i+n&1)&1;break;default:throw new A("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let i=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let d=0;d<s;d++){let h=0,m=-1;for(let y=0;y<a;y++){const E=n?l[d][y]:l[y][d];E===m?h++:(h>=5&&(i+=It.N1+(h-5)),h=1,m=E)}h>=5&&(i+=It.N1+(h-5))}return i}}It.N1=3,It.N2=3,It.N3=40,It.N4=10;class mi{constructor(e,n){this.width=e,this.height=n;const i=new Array(n);for(let s=0;s!==n;s++)i[s]=new Uint8Array(e);this.bytes=i}getHeight(){return this.height}getWidth(){return this.width}get(e,n){return this.bytes[n][e]}getArray(){return this.bytes}setNumber(e,n,i){this.bytes[n][e]=i}setBoolean(e,n,i){this.bytes[n][e]=i?1:0}clear(e){for(const n of this.bytes)Z.fill(n,e)}equals(e){if(!(e instanceof mi))return!1;const n=e;if(this.width!==n.width||this.height!==n.height)return!1;for(let i=0,s=this.height;i<s;++i){const a=this.bytes[i],l=n.bytes[i];for(let d=0,h=this.width;d<h;++d)if(a[d]!==l[d])return!1}return!0}toString(){const e=new ae;for(let n=0,i=this.height;n<i;++n){const s=this.bytes[n];for(let a=0,l=this.width;a<l;++a)switch(s[a]){case 0:e.append(" 0");break;case 1:e.append(" 1");break;default:e.append(" ");break}e.append(`
|
|
64
|
+
`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],Je.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class je{constructor(){}static round(e){return e===NaN?0:e<=Number.MIN_SAFE_INTEGER?Number.MIN_SAFE_INTEGER:e>=Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:e+(e<0?-.5:.5)|0}static distance(e,n,i,s){const a=e-i,l=n-s;return Math.sqrt(a*a+l*l)}static sum(e){let n=0;for(let i=0,s=e.length;i!==s;i++){const a=e[i];n+=a}return n}}class En{static floatToIntBits(e){return e}}En.MAX_VALUE=Number.MAX_SAFE_INTEGER;class T{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof T){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*En.floatToIntBits(this.x)+En.floatToIntBits(this.y)}toString(){return"("+this.x+","+this.y+")"}static orderBestPatterns(e){const n=this.distance(e[0],e[1]),i=this.distance(e[1],e[2]),s=this.distance(e[0],e[2]);let a,l,d;if(i>=n&&i>=s?(l=e[0],a=e[1],d=e[2]):s>=i&&s>=n?(l=e[1],a=e[0],d=e[2]):(l=e[2],a=e[0],d=e[1]),this.crossProductZ(a,l,d)<0){const h=a;a=d,d=h}e[0]=a,e[1]=l,e[2]=d}static distance(e,n){return je.distance(e.x,e.y,n.x,n.y)}static crossProductZ(e,n,i){const s=n.x,a=n.y;return(i.x-s)*(e.y-a)-(i.y-a)*(e.x-s)}}class pe{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class _t extends pe{constructor(e,n,i,s,a){super(e,n),this.compact=i,this.nbDatablocks=s,this.nbLayers=a}getNbLayers(){return this.nbLayers}getNbDatablocks(){return this.nbDatablocks}isCompact(){return this.compact}}class vt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=vt.INIT_SIZE),i==null&&(i=e.getWidth()/2|0),s==null&&(s=e.getHeight()/2|0);const a=n/2|0;if(this.leftInit=i-a,this.rightInit=i+a,this.upInit=s-a,this.downInit=s+a,this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width)throw new D}detect(){let e=this.leftInit,n=this.rightInit,i=this.upInit,s=this.downInit,a=!1,l=!0,d=!1,h=!1,p=!1,y=!1,E=!1;const I=this.width,R=this.height;for(;l;){l=!1;let F=!0;for(;(F||!h)&&n<I;)F=this.containsBlackPoint(i,s,n,!1),F?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let U=!0;for(;(U||!p)&&s<R;)U=this.containsBlackPoint(e,n,s,!0),U?(s++,l=!0,p=!0):p||s++;if(s>=R){a=!0;break}let Y=!0;for(;(Y||!y)&&e>=0;)Y=this.containsBlackPoint(i,s,e,!1),Y?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let re=!0;for(;(re||!E)&&i>=0;)re=this.containsBlackPoint(e,n,i,!0),re?(i--,l=!0,E=!0):E||i--;if(i<0){a=!0;break}l&&(d=!0)}if(!a&&d){const F=n-e;let U=null;for(let xe=1;U===null&&xe<F;xe++)U=this.getBlackPointOnSegment(e,s-xe,e+xe,s);if(U==null)throw new D;let Y=null;for(let xe=1;Y===null&&xe<F;xe++)Y=this.getBlackPointOnSegment(e,i+xe,e+xe,i);if(Y==null)throw new D;let re=null;for(let xe=1;re===null&&xe<F;xe++)re=this.getBlackPointOnSegment(n,i+xe,n-xe,i);if(re==null)throw new D;let me=null;for(let xe=1;me===null&&xe<F;xe++)me=this.getBlackPointOnSegment(n,s-xe,n-xe,s);if(me==null)throw new D;return this.centerEdges(me,U,re,Y)}else throw new D}getBlackPointOnSegment(e,n,i,s){const a=je.round(je.distance(e,n,i,s)),l=(i-e)/a,d=(s-n)/a,h=this.image;for(let p=0;p<a;p++){const y=je.round(e+p*l),E=je.round(n+p*d);if(h.get(y,E))return new T(y,E)}return null}centerEdges(e,n,i,s){const a=e.getX(),l=e.getY(),d=n.getX(),h=n.getY(),p=i.getX(),y=i.getY(),E=s.getX(),I=s.getY(),R=vt.CORR;return a<this.width/2?[new T(E-R,I+R),new T(d+R,h+R),new T(p-R,y-R),new T(a+R,l-R)]:[new T(E+R,I+R),new T(d+R,h-R),new T(p-R,y+R),new T(a-R,l-R)]}containsBlackPoint(e,n,i,s){const a=this.image;if(s){for(let l=e;l<=n;l++)if(a.get(l,i))return!0}else for(let l=e;l<=n;l++)if(a.get(i,l))return!0;return!1}}vt.INIT_SIZE=10,vt.CORR=1;class Un{static checkAndNudgePoints(e,n){const i=e.getWidth(),s=e.getHeight();let a=!0;for(let l=0;l<n.length&&a;l+=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new D;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}a=!0;for(let l=n.length-2;l>=0&&a;l-=2){const d=Math.floor(n[l]),h=Math.floor(n[l+1]);if(d<-1||d>i||h<-1||h>s)throw new D;a=!1,d===-1?(n[l]=0,a=!0):d===i&&(n[l]=i-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}}}class nn{constructor(e,n,i,s,a,l,d,h,p){this.a11=e,this.a21=n,this.a31=i,this.a12=s,this.a22=a,this.a32=l,this.a13=d,this.a23=h,this.a33=p}static quadrilateralToQuadrilateral(e,n,i,s,a,l,d,h,p,y,E,I,R,F,U,Y){const re=nn.quadrilateralToSquare(e,n,i,s,a,l,d,h);return nn.squareToQuadrilateral(p,y,E,I,R,F,U,Y).times(re)}transformPoints(e){const n=e.length,i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33;for(let I=0;I<n;I+=2){const R=e[I],F=e[I+1],U=a*R+h*F+E;e[I]=(i*R+l*F+p)/U,e[I+1]=(s*R+d*F+y)/U}}transformPointsWithValues(e,n){const i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33,I=e.length;for(let R=0;R<I;R++){const F=e[R],U=n[R],Y=a*F+h*U+E;e[R]=(i*F+l*U+p)/Y,n[R]=(s*F+d*U+y)/Y}}static squareToQuadrilateral(e,n,i,s,a,l,d,h){const p=e-i+a-d,y=n-s+l-h;if(p===0&&y===0)return new nn(i-e,a-i,e,s-n,l-s,n,0,0,1);{const E=i-a,I=d-a,R=s-l,F=h-l,U=E*F-I*R,Y=(p*F-I*y)/U,re=(E*y-p*R)/U;return new nn(i-e+Y*i,d-e+re*d,e,s-n+Y*s,h-n+re*h,n,Y,re,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return nn.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new nn(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21)}times(e){return new nn(this.a11*e.a11+this.a21*e.a12+this.a31*e.a13,this.a11*e.a21+this.a21*e.a22+this.a31*e.a23,this.a11*e.a31+this.a21*e.a32+this.a31*e.a33,this.a12*e.a11+this.a22*e.a12+this.a32*e.a13,this.a12*e.a21+this.a22*e.a22+this.a32*e.a23,this.a12*e.a31+this.a22*e.a32+this.a32*e.a33,this.a13*e.a11+this.a23*e.a12+this.a33*e.a13,this.a13*e.a21+this.a23*e.a22+this.a33*e.a23,this.a13*e.a31+this.a23*e.a32+this.a33*e.a33)}}class ai extends Un{sampleGrid(e,n,i,s,a,l,d,h,p,y,E,I,R,F,U,Y,re,me,xe){const ue=nn.quadrilateralToQuadrilateral(s,a,l,d,h,p,y,E,I,R,F,U,Y,re,me,xe);return this.sampleGridWithTransform(e,n,i,ue)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new D;const a=new q(n,i),l=new Float32Array(2*n);for(let d=0;d<i;d++){const h=l.length,p=d+.5;for(let y=0;y<h;y+=2)l[y]=y/2+.5,l[y+1]=p;s.transformPoints(l),Un.checkAndNudgePoints(e,l);try{for(let y=0;y<h;y+=2)e.get(Math.floor(l[y]),Math.floor(l[y+1]))&&a.set(y/2,d)}catch{throw new D}}return a}}class An{static setGridSampler(e){An.gridSampler=e}static getInstance(){return An.gridSampler}}An.gridSampler=new ai;class Lt{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new T(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class li{constructor(e){this.EXPECTED_CORNER_BITS=new Int32Array([3808,476,2107,1799]),this.image=e}detect(){return this.detectMirror(!1)}detectMirror(e){let n=this.getMatrixCenter(),i=this.getBullsEyeCorners(n);if(e){let l=i[0];i[0]=i[2],i[2]=l}this.extractParameters(i);let s=this.sampleGrid(this.image,i[this.shift%4],i[(this.shift+1)%4],i[(this.shift+2)%4],i[(this.shift+3)%4]),a=this.getMatrixCornerPoints(i);return new _t(s,a,this.compact,this.nbDataBlocks,this.nbLayers)}extractParameters(e){if(!this.isValidPoint(e[0])||!this.isValidPoint(e[1])||!this.isValidPoint(e[2])||!this.isValidPoint(e[3]))throw new D;let n=2*this.nbCenterLayers,i=new Int32Array([this.sampleLine(e[0],e[1],n),this.sampleLine(e[1],e[2],n),this.sampleLine(e[2],e[3],n),this.sampleLine(e[3],e[0],n)]);this.shift=this.getRotation(i,n);let s=0;for(let l=0;l<4;l++){let d=i[(this.shift+l)%4];this.compact?(s<<=7,s+=d>>1&127):(s<<=10,s+=(d>>2&992)+(d>>1&31))}let a=this.getCorrectedParameterData(s,this.compact);this.compact?(this.nbLayers=(a>>6)+1,this.nbDataBlocks=(a&63)+1):(this.nbLayers=(a>>11)+1,this.nbDataBlocks=(a&2047)+1)}getRotation(e,n){let i=0;e.forEach((s,a,l)=>{let d=(s>>n-2<<1)+(s&1);i=(i<<3)+d}),i=((i&1)<<11)+(i>>1);for(let s=0;s<4;s++)if($.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new D}getCorrectedParameterData(e,n){let i,s;n?(i=7,s=2):(i=10,s=4);let a=i-s,l=new Int32Array(i);for(let h=i-1;h>=0;--h)l[h]=e&15,e>>=4;try{new bn(Ue.AZTEC_PARAM).decode(l,a)}catch{throw new D}let d=0;for(let h=0;h<s;h++)d=(d<<4)+l[h];return d}getBullsEyeCorners(e){let n=e,i=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let E=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(i,l,1,1),R=this.getFirstDifferent(s,l,-1,1),F=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let U=this.distancePoint(F,E)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(U<.75||U>1.25||!this.isWhiteOrBlackRectangle(E,I,R,F))break}n=E,i=I,s=R,a=F,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new D;this.compact=this.nbCenterLayers===5;let d=new T(n.getX()+.5,n.getY()-.5),h=new T(i.getX()+.5,i.getY()+.5),p=new T(s.getX()-.5,s.getY()+.5),y=new T(a.getX()-.5,a.getY()-.5);return this.expandSquare([d,h,p,y],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,i,s;try{let d=new vt(this.image).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{let h=this.image.getWidth()/2,p=this.image.getHeight()/2;e=this.getFirstDifferent(new Lt(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(h+7,p+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(h-7,p-7),!1,-1,-1).toResultPoint()}let a=je.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=je.round((e.getY()+s.getY()+n.getY()+i.getY())/4);try{let d=new vt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new Lt(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(a-7,l-7),!1,-1,-1).toResultPoint()}return a=je.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=je.round((e.getY()+s.getY()+n.getY()+i.getY())/4),new Lt(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=An.getInstance(),d=this.getDimension(),h=d/2-this.nbCenterLayers,p=d/2+this.nbCenterLayers;return l.sampleGrid(e,d,d,h,h,p,h,p,p,h,p,n.getX(),n.getY(),i.getX(),i.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,i){let s=0,a=this.distanceResultPoint(e,n),l=a/i,d=e.getX(),h=e.getY(),p=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let E=0;E<i;E++)this.image.get(je.round(d+E*p),je.round(h+E*y))&&(s|=1<<i-E-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new Lt(e.getX()-a,e.getY()+a),n=new Lt(n.getX()-a,n.getY()-a),i=new Lt(i.getX()+a,i.getY()-a),s=new Lt(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let d=this.getColor(e,n);return d!==l||(d=this.getColor(n,i),d!==l)?!1:(d=this.getColor(i,s),d===l)}getColor(e,n){let i=this.distancePoint(e,n),s=(n.getX()-e.getX())/i,a=(n.getY()-e.getY())/i,l=0,d=e.getX(),h=e.getY(),p=this.image.get(e.getX(),e.getY()),y=Math.ceil(i);for(let I=0;I<y;I++)d+=s,h+=a,this.image.get(je.round(d),je.round(h))!==p&&l++;let E=l/i;return E>.1&&E<.9?0:E<=.1===p?1:-1}getFirstDifferent(e,n,i,s){let a=e.getX()+i,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i,l+=s;for(a-=i,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i;for(a-=i;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new Lt(a,l)}expandSquare(e,n,i){let s=i/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),d=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,p=new T(d+s*a,h+s*l),y=new T(d-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),d=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let E=new T(d+s*a,h+s*l),I=new T(d-s*a,h-s*l);return[p,E,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=je.round(e.getX()),i=je.round(e.getY());return this.isValid(n,i)}distancePoint(e,n){return je.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return je.distance(e.getX(),e.getY(),n.getX(),n.getY())}getDimension(){return this.compact?4*this.nbLayers+11:this.nbLayers<=4?4*this.nbLayers+15:4*this.nbLayers+2*($.truncDivision(this.nbLayers-4,8)+1)+15}}class pr{decode(e,n=null){let i=null,s=new li(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Je().decode(y)}catch(y){i=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Je().decode(y)}catch(y){throw i??y}let d=new Me(l.getText(),l.getRawBytes(),l.getNumBits(),a,ie.AZTEC,B.currentTimeMillis()),h=l.getByteSegments();h!=null&&d.putMetadata(Ae.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&d.putMetadata(Ae.ERROR_CORRECTION_LEVEL,p),d}reportFoundResultPoints(e,n){if(e!=null){let i=e.get(H.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class Wi extends Ve{constructor(e=500){super(new pr,e)}}class Ie{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(H.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),d=l.getResultMetadata();let h=270;d!==null&&d.get(Ae.ORIENTATION)===!0&&(h=h+d.get(Ae.ORIENTATION)%360),l.putMetadata(Ae.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const y=a.getHeight();for(let E=0;E<p.length;E++)p[E]=new T(y-p[E].getY()-1,p[E].getX())}return l}else throw new D}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new W(i);const l=n&&n.get(H.TRY_HARDER)===!0,d=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const p=Math.trunc(s/2);for(let y=0;y<h;y++){const E=Math.trunc((y+1)/2),I=(y&1)===0,R=p+d*(I?E:-E);if(R<0||R>=s)break;try{a=e.getBlackRow(R,a)}catch{continue}for(let F=0;F<2;F++){if(F===1&&(a.reverse(),n&&n.get(H.NEED_RESULT_POINT_CALLBACK)===!0)){const U=new Map;n.forEach((Y,re)=>U.set(re,Y)),U.delete(H.NEED_RESULT_POINT_CALLBACK),n=U}try{const U=this.decodeRow(R,a,n);if(F===1){U.putMetadata(Ae.ORIENTATION,180);const Y=U.getResultPoints();Y!==null&&(Y[0]=new T(i-Y[0].getX()-1,Y[0].getY()),Y[1]=new T(i-Y[1].getX()-1,Y[1].getY()))}return U}catch{}}}throw new D}static recordPattern(e,n,i){const s=i.length;for(let p=0;p<s;p++)i[p]=0;const a=e.getSize();if(n>=a)throw new D;let l=!e.get(n),d=0,h=n;for(;h<a;){if(e.get(h)!==l)i[d]++;else{if(++d===s)break;i[d]=1,l=!l}h++}if(!(d===s||d===s-1&&h===a))throw new D}static recordPatternInReverse(e,n,i){let s=i.length,a=e.get(n);for(;n>0&&s>=0;)e.get(--n)!==a&&(s--,a=!a);if(s>=0)throw new D;Ie.recordPattern(e,n+1,i)}static patternMatchVariance(e,n,i){const s=e.length;let a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return Number.POSITIVE_INFINITY;const d=a/l;i*=d;let h=0;for(let p=0;p<s;p++){const y=e[p],E=n[p]*d,I=y>E?y-E:E-y;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class oe extends Ie{static findStartPattern(e){const n=e.getSize(),i=e.getNextSet(0);let s=0,a=Int32Array.from([0,0,0,0,0,0]),l=i,d=!1;const h=6;for(let p=i;p<n;p++)if(e.get(p)!==d)a[s]++;else{if(s===h-1){let y=oe.MAX_AVG_VARIANCE,E=-1;for(let I=oe.CODE_START_A;I<=oe.CODE_START_C;I++){const R=Ie.patternMatchVariance(a,oe.CODE_PATTERNS[I],oe.MAX_INDIVIDUAL_VARIANCE);R<y&&(y=R,E=I)}if(E>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,E]);l+=a[0]+a[1],a=a.slice(2,a.length-1),a[s-1]=0,a[s]=0,s--}else s++;a[s]=1,d=!d}throw new D}static decodeCode(e,n,i){Ie.recordPattern(e,i,n);let s=oe.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<oe.CODE_PATTERNS.length;l++){const d=oe.CODE_PATTERNS[l],h=this.patternMatchVariance(n,d,oe.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new D}decodeRow(e,n,i){const s=i&&i.get(H.ASSUME_GS1)===!0,a=oe.findStartPattern(n),l=a[2];let d=0;const h=new Uint8Array(20);h[d++]=l;let p;switch(l){case oe.CODE_START_A:p=oe.CODE_CODE_A;break;case oe.CODE_START_B:p=oe.CODE_CODE_B;break;case oe.CODE_START_C:p=oe.CODE_CODE_C;break;default:throw new V}let y=!1,E=!1,I="",R=a[0],F=a[1];const U=Int32Array.from([0,0,0,0,0,0]);let Y=0,re=0,me=l,xe=0,ue=!0,We=!1,Be=!1;for(;!y;){const br=E;switch(E=!1,Y=re,re=oe.decodeCode(n,U,F),h[d++]=re,re!==oe.CODE_STOP&&(ue=!0),re!==oe.CODE_STOP&&(xe++,me+=xe*re),R=F,F+=U.reduce((Ad,Id)=>Ad+Id,0),re){case oe.CODE_START_A:case oe.CODE_START_B:case oe.CODE_START_C:throw new V}switch(p){case oe.CODE_CODE_A:if(re<64)Be===We?I+=String.fromCharCode(32+re):I+=String.fromCharCode(32+re+128),Be=!1;else if(re<96)Be===We?I+=String.fromCharCode(re-64):I+=String.fromCharCode(re+64),Be=!1;else switch(re!==oe.CODE_STOP&&(ue=!1),re){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_FNC_2:case oe.CODE_FNC_3:break;case oe.CODE_FNC_4_A:!We&&Be?(We=!0,Be=!1):We&&Be?(We=!1,Be=!1):Be=!0;break;case oe.CODE_SHIFT:E=!0,p=oe.CODE_CODE_B;break;case oe.CODE_CODE_B:p=oe.CODE_CODE_B;break;case oe.CODE_CODE_C:p=oe.CODE_CODE_C;break;case oe.CODE_STOP:y=!0;break}break;case oe.CODE_CODE_B:if(re<96)Be===We?I+=String.fromCharCode(32+re):I+=String.fromCharCode(32+re+128),Be=!1;else switch(re!==oe.CODE_STOP&&(ue=!1),re){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_FNC_2:case oe.CODE_FNC_3:break;case oe.CODE_FNC_4_B:!We&&Be?(We=!0,Be=!1):We&&Be?(We=!1,Be=!1):Be=!0;break;case oe.CODE_SHIFT:E=!0,p=oe.CODE_CODE_A;break;case oe.CODE_CODE_A:p=oe.CODE_CODE_A;break;case oe.CODE_CODE_C:p=oe.CODE_CODE_C;break;case oe.CODE_STOP:y=!0;break}break;case oe.CODE_CODE_C:if(re<100)re<10&&(I+="0"),I+=re;else switch(re!==oe.CODE_STOP&&(ue=!1),re){case oe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case oe.CODE_CODE_A:p=oe.CODE_CODE_A;break;case oe.CODE_CODE_B:p=oe.CODE_CODE_B;break;case oe.CODE_STOP:y=!0;break}break}br&&(p=p===oe.CODE_CODE_A?oe.CODE_CODE_B:oe.CODE_CODE_A)}const Qt=F-R;if(F=n.getNextUnset(F),!n.isRange(F,Math.min(n.getSize(),F+(F-R)/2),!1))throw new D;if(me-=xe*Y,me%103!==Y)throw new O;const gn=I.length;if(gn===0)throw new D;gn>0&&ue&&(p===oe.CODE_CODE_C?I=I.substring(0,gn-2):I=I.substring(0,gn-1));const en=(a[1]+a[0])/2,at=R+Qt/2,zt=h.length,rn=new Uint8Array(zt);for(let br=0;br<zt;br++)rn[br]=h[br];const Cr=[new T(en,e),new T(at,e)];return new Me(I,rn,0,Cr,ie.CODE_128,new Date().getTime())}}oe.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])],oe.MAX_AVG_VARIANCE=.25,oe.MAX_INDIVIDUAL_VARIANCE=.7,oe.CODE_SHIFT=98,oe.CODE_CODE_C=99,oe.CODE_CODE_B=100,oe.CODE_CODE_A=101,oe.CODE_FNC_1=102,oe.CODE_FNC_2=97,oe.CODE_FNC_3=96,oe.CODE_FNC_4_A=101,oe.CODE_FNC_4_B=100,oe.CODE_START_A=103,oe.CODE_START_B=104,oe.CODE_START_C=105,oe.CODE_STOP=106;class Re extends Ie{constructor(e=!1,n=!1){super(),this.usingCheckDigit=e,this.extendedMode=n,this.decodeRowResult="",this.counters=new Int32Array(9)}decodeRow(e,n,i){let s=this.counters;s.fill(0),this.decodeRowResult="";let a=Re.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,p;do{Re.recordPattern(n,l,s);let U=Re.toNarrowWidePattern(s);if(U<0)throw new D;h=Re.patternToChar(U),this.decodeRowResult+=h,p=l;for(let Y of s)l+=Y;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let U of s)y+=U;let E=l-p-y;if(l!==d&&E*2<y)throw new D;if(this.usingCheckDigit){let U=this.decodeRowResult.length-1,Y=0;for(let re=0;re<U;re++)Y+=Re.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(re));if(this.decodeRowResult.charAt(U)!==Re.ALPHABET_STRING.charAt(Y%43))throw new O;this.decodeRowResult=this.decodeRowResult.substring(0,U)}if(this.decodeRowResult.length===0)throw new D;let I;this.extendedMode?I=Re.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let R=(a[1]+a[0])/2,F=p+y/2;return new Me(I,null,0,[new T(R,e),new T(F,e)],ie.CODE_39,new Date().getTime())}static findAsteriskPattern(e,n){let i=e.getSize(),s=e.getNextSet(0),a=0,l=s,d=!1,h=n.length;for(let p=s;p<i;p++)if(e.get(p)!==d)n[a]++;else{if(a===h-1){if(this.toNarrowWidePattern(n)===Re.ASTERISK_ENCODING&&e.isRange(Math.max(0,l-Math.floor((p-l)/2)),l,!1))return[l,p];l+=n[0]+n[1],n.copyWithin(0,2,2+a-1),n[a-1]=0,n[a]=0,a--}else a++;n[a]=1,d=!d}throw new D}static toNarrowWidePattern(e){let n=e.length,i=0,s;do{let a=2147483647;for(let h of e)h<a&&h>i&&(a=h);i=a,s=0;let l=0,d=0;for(let h=0;h<n;h++){let p=e[h];p>i&&(d|=1<<n-1-h,s++,l+=p)}if(s===3){for(let h=0;h<n&&s>0;h++){let p=e[h];if(p>i&&(s--,p*2>=l))return-1}return d}}while(s>3);return-1}static patternToChar(e){for(let n=0;n<Re.CHARACTER_ENCODINGS.length;n++)if(Re.CHARACTER_ENCODINGS[n]===e)return Re.ALPHABET_STRING.charAt(n);if(e===Re.ASTERISK_ENCODING)return"*";throw new D}static decodeExtended(e){let n=e.length,i="";for(let s=0;s<n;s++){let a=e.charAt(s);if(a==="+"||a==="$"||a==="%"||a==="/"){let l=e.charAt(s+1),d="\0";switch(a){case"+":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)+32);else throw new V;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new V;break;case"%":if(l>="A"&&l<="E")d=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")d=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")d=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")d="\0";else if(l==="V")d="@";else if(l==="W")d="`";else if(l==="X"||l==="Y"||l==="Z")d="";else throw new V;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new V;break}i+=d,s++}else i+=a}return i}}Re.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",Re.CHARACTER_ENCODINGS=[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,168,162,138,42],Re.ASTERISK_ENCODING=148;class qe extends Ie{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new ae;qe.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(H.ALLOWED_LENGTHS)),h==null&&(h=qe.DEFAULT_ALLOWED_LENGTHS);let p=d.length,y=!1,E=0;for(let F of h){if(p===F){y=!0;break}F>E&&(E=F)}if(!y&&p>E&&(y=!0),!y)throw new V;const I=[new T(s[1],e),new T(a[0],e)];return new Me(d,null,0,I,ie.ITF,new Date().getTime())}static decodeMiddle(e,n,i,s){let a=new Int32Array(10),l=new Int32Array(5),d=new Int32Array(5);for(a.fill(0),l.fill(0),d.fill(0);n<i;){Ie.recordPattern(e,n,a);for(let p=0;p<5;p++){let y=2*p;l[p]=a[y],d[p]=a[y+1]}let h=qe.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=qe.skipWhiteSpace(e),i=qe.findGuardPattern(e,n,qe.START_PATTERN);return this.narrowLineWidth=(i[1]-i[0])/4,this.validateQuietZone(e,i[0]),i}validateQuietZone(e,n){let i=this.narrowLineWidth*10;i=i<n?i:n;for(let s=n-1;i>0&&s>=0&&!e.get(s);s--)i--;if(i!==0)throw new D}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new D;return i}decodeEnd(e){e.reverse();try{let n=qe.skipWhiteSpace(e),i;try{i=qe.findGuardPattern(e,n,qe.END_PATTERN_REVERSED[0])}catch(a){a instanceof D&&(i=qe.findGuardPattern(e,n,qe.END_PATTERN_REVERSED[1]))}this.validateQuietZone(e,i[0]);let s=i[0];return i[0]=e.getSize()-i[1],i[1]=e.getSize()-s,i}finally{e.reverse()}}static findGuardPattern(e,n,i){let s=i.length,a=new Int32Array(s),l=e.getSize(),d=!1,h=0,p=n;a.fill(0);for(let y=n;y<l;y++)if(e.get(y)!==d)a[h]++;else{if(h===s-1){if(Ie.patternMatchVariance(a,i,qe.MAX_INDIVIDUAL_VARIANCE)<qe.MAX_AVG_VARIANCE)return[p,y];p+=a[0]+a[1],B.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,d=!d}throw new D}static decodeDigit(e){let n=qe.MAX_AVG_VARIANCE,i=-1,s=qe.PATTERNS.length;for(let a=0;a<s;a++){let l=qe.PATTERNS[a],d=Ie.patternMatchVariance(e,l,qe.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new D}}qe.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])],qe.MAX_AVG_VARIANCE=.38,qe.MAX_INDIVIDUAL_VARIANCE=.5,qe.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],qe.START_PATTERN=Int32Array.from([1,1,1,1]),qe.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class pt extends Ie{constructor(){super(...arguments),this.decodeRowStringBuffer=""}static findStartGuardPattern(e){let n=!1,i,s=0,a=Int32Array.from([0,0,0]);for(;!n;){a=Int32Array.from([0,0,0]),i=pt.findGuardPattern(e,s,!1,this.START_END_PATTERN,a);let l=i[0];s=i[1];let d=l-(s-l);d>=0&&(n=e.isRange(d,l,!1))}return i}static checkChecksum(e){return pt.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return pt.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return pt.findGuardPattern(e,n,!1,pt.START_END_PATTERN,new Int32Array(pt.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,i,s){return this.findGuardPattern(e,n,i,s,new Int32Array(s.length))}static findGuardPattern(e,n,i,s,a){let l=e.getSize();n=i?e.getNextUnset(n):e.getNextSet(n);let d=0,h=n,p=s.length,y=i;for(let E=n;E<l;E++)if(e.get(E)!==y)a[d]++;else{if(d===p-1){if(Ie.patternMatchVariance(a,s,pt.MAX_INDIVIDUAL_VARIANCE)<pt.MAX_AVG_VARIANCE)return Int32Array.from([h,E]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let R=0;R<d-1;R++)a[R]=I[R];a[d-1]=0,a[d]=0,d--}else d++;a[d]=1,y=!y}throw new D}static decodeDigit(e,n,i,s){this.recordPattern(e,i,n);let a=this.MAX_AVG_VARIANCE,l=-1,d=s.length;for(let h=0;h<d;h++){let p=s[h],y=Ie.patternMatchVariance(n,p,pt.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new D}}pt.MAX_AVG_VARIANCE=.48,pt.MAX_INDIVIDUAL_VARIANCE=.7,pt.START_END_PATTERN=Int32Array.from([1,1,1]),pt.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),pt.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),pt.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])];class Or{constructor(){this.CHECK_DIGIT_ENCODINGS=[24,20,18,17,12,6,3,10,9,5],this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=Or.parseExtensionString(l),h=[new T((i[0]+i[1])/2,e),new T(a,e)],p=new Me(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&p.putAllMetadata(d),p}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let p=0;p<5&&l<a;p++){let y=pt.decodeDigit(e,s,l,pt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new D;let h=this.determineCheckDigit(d);if(Or.extensionChecksum(i.toString())!==h)throw new D;return l}static extensionChecksum(e){let n=e.length,i=0;for(let s=n-2;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;i*=3;for(let s=n-1;s>=0;s-=2)i+=e.charAt(s).charCodeAt(0)-48;return i*=3,i%10}determineCheckDigit(e){for(let n=0;n<10;n++)if(e===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new D}static parseExtensionString(e){if(e.length!==5)return null;let n=Or.parseExtension5String(e);return n==null?null:new Map([[Ae.SUGGESTED_PRICE,n]])}static parseExtension5String(e){let n;switch(e.charAt(0)){case"0":n="£";break;case"5":n="$";break;case"9":switch(e){case"90000":return null;case"99991":return"0.00";case"99990":return"Used"}n="";break;default:n="";break}let i=parseInt(e.substring(1)),s=(i/100).toString(),a=i%100,l=a<10?"0"+a:a.toString();return n+s+"."+l}}class Hi{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,i){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,i,s),l=s.toString(),d=Hi.parseExtensionString(l),h=[new T((i[0]+i[1])/2,e),new T(a,e)],p=new Me(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return d!=null&&p.putAllMetadata(d),p}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let h=0;h<2&&l<a;h++){let p=pt.decodeDigit(e,s,l,pt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+p%10);for(let y of s)l+=y;p>=10&&(d|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==2)throw new D;if(parseInt(i.toString())%4!==d)throw new D;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ae.ISSUE_NUMBER,parseInt(e)]])}}class cs{static decodeRow(e,n,i){let s=pt.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new Or().decodeRow(e,n,s)}catch{return new Hi().decodeRow(e,n,s)}}}cs.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ke extends pt{constructor(){super(),this.decodeRowStringBuffer="",Ke.L_AND_G_PATTERNS=Ke.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=Ke.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];Ke.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=Ke.findStartGuardPattern(n),a=i==null?null:i.get(H.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ue=new T((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ue)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),d=l.rowOffset,h=l.resultString;if(a!=null){const ue=new T(d,e);a.foundPossibleResultPoint(ue)}let p=this.decodeEnd(n,d);if(a!=null){const ue=new T((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ue)}let y=p[1],E=y+(y-p[0]);if(E>=n.getSize()||!n.isRange(y,E,!1))throw new D;let I=h.toString();if(I.length<8)throw new V;if(!Ke.checkChecksum(I))throw new O;let R=(s[1]+s[0])/2,F=(p[1]+p[0])/2,U=this.getBarcodeFormat(),Y=[new T(R,e),new T(F,e)],re=new Me(I,null,0,Y,U,new Date().getTime()),me=0;try{let ue=cs.decodeRow(e,n,p[1]);re.putMetadata(Ae.UPC_EAN_EXTENSION,ue.getText()),re.putAllMetadata(ue.getResultMetadata()),re.addResultPoints(ue.getResultPoints()),me=ue.getText().length}catch{}let xe=i==null?null:i.get(H.ALLOWED_EAN_EXTENSIONS);if(xe!=null){let ue=!1;for(let We in xe)if(me.toString()===We){ue=!0;break}if(!ue)throw new D}return re}decodeEnd(e,n){return Ke.findGuardPattern(e,n,!1,Ke.START_END_PATTERN,new Int32Array(Ke.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return Ke.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return Ke.getStandardUPCEANChecksum(e.substring(0,n-1))===i}static getStandardUPCEANChecksum(e){let n=e.length,i=0;for(let s=n-1;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}i*=3;for(let s=n-2;s>=0;s-=2){let a=e.charAt(s).charCodeAt(0)-48;if(a<0||a>9)throw new V;i+=a}return(1e3-i)%10}}class Qn extends Ke{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],d=0;for(let p=0;p<6&&l<a;p++){let y=Ke.decodeDigit(e,s,l,Ke.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}i=Qn.determineFirstDigit(i,d),l=Ke.findGuardPattern(e,l,!0,Ke.MIDDLE_PATTERN,new Int32Array(Ke.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+y);for(let E of s)l+=E}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return ie.EAN_13}static determineFirstDigit(e,n){for(let i=0;i<10;i++)if(n===this.FIRST_DIGIT_ENCODINGS[i])return e=String.fromCharCode(48+i)+e,e;throw new D}}Qn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class us extends Ke{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1];for(let h=0;h<4&&l<a;h++){let p=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}l=Ke.findGuardPattern(e,l,!0,Ke.MIDDLE_PATTERN,new Int32Array(Ke.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=Ke.decodeDigit(e,s,l,Ke.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return ie.EAN_8}}class ds extends Ke{constructor(){super(...arguments),this.ean13Reader=new Qn}getBarcodeFormat(){return ie.UPC_A}decode(e,n){return this.maybeReturnResult(this.ean13Reader.decode(e))}decodeRow(e,n,i){return this.maybeReturnResult(this.ean13Reader.decodeRow(e,n,i))}decodeMiddle(e,n,i){return this.ean13Reader.decodeMiddle(e,n,i)}maybeReturnResult(e){let n=e.getText();if(n.charAt(0)==="0"){let i=new Me(n.substring(1),null,null,e.getResultPoints(),ie.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new D}reset(){this.ean13Reader.reset()}}class mn extends Ke{constructor(){super(),this.decodeMiddleCounters=new Int32Array(4)}decodeMiddle(e,n,i){const s=this.decodeMiddleCounters.map(p=>p);s[0]=0,s[1]=0,s[2]=0,s[3]=0;const a=e.getSize();let l=n[1],d=0;for(let p=0;p<6&&l<a;p++){const y=mn.decodeDigit(e,s,l,mn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}let h=mn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return mn.findGuardPatternWithoutCounters(e,n,!0,mn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ke.checkChecksum(mn.convertUPCEtoUPCA(e))}static determineNumSysAndCheckDigit(e,n){for(let i=0;i<=1;i++)for(let s=0;s<10;s++)if(n===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[i][s]){let a=String.fromCharCode(48+i),l=String.fromCharCode(48+s);return a+e+l}throw D.getNotFoundInstance()}getBarcodeFormat(){return ie.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new ae;i.append(e.charAt(0));let s=n[5];switch(s){case 0:case 1:case 2:i.appendChars(n,0,2),i.append(s),i.append("0000"),i.appendChars(n,2,3);break;case 3:i.appendChars(n,0,3),i.append("00000"),i.appendChars(n,3,2);break;case 4:i.appendChars(n,0,4),i.append("00000"),i.append(n[4]);break;default:i.appendChars(n,0,5),i.append("0000"),i.append(s);break}return e.length>=8&&i.append(e.charAt(7)),i.toString()}}mn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),mn.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([56,52,50,49,44,38,35,42,41,37]),Int32Array.from([7,11,13,14,19,25,28,21,22,26])];class Gi extends Ie{constructor(e){super();let n=e==null?null:e.get(H.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new Qn),i.push(new ds),i.push(new us),i.push(new mn)):(n.indexOf(ie.EAN_13)>-1&&i.push(new Qn),n.indexOf(ie.UPC_A)>-1&&i.push(new ds),n.indexOf(ie.EAN_8)>-1&&i.push(new us),n.indexOf(ie.UPC_E)>-1&&i.push(new mn)),this.readers=i}decodeRow(e,n,i){for(let s of this.readers)try{const a=s.decodeRow(e,n,i),l=a.getBarcodeFormat()===ie.EAN_13&&a.getText().charAt(0)==="0",d=i==null?null:i.get(H.POSSIBLE_FORMATS),h=d==null||d.includes(ie.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new Me(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),ie.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new D}reset(){for(let e of this.readers)e.reset()}}class Zt extends Ie{constructor(){super(),this.decodeFinderCounters=new Int32Array(4),this.dataCharacterCounters=new Int32Array(8),this.oddRoundingErrors=new Array(4),this.evenRoundingErrors=new Array(4),this.oddCounts=new Array(this.dataCharacterCounters.length/2),this.evenCounts=new Array(this.dataCharacterCounters.length/2)}getDecodeFinderCounters(){return this.decodeFinderCounters}getDataCharacterCounters(){return this.dataCharacterCounters}getOddRoundingErrors(){return this.oddRoundingErrors}getEvenRoundingErrors(){return this.evenRoundingErrors}getOddCounts(){return this.oddCounts}getEvenCounts(){return this.evenCounts}parseFinderValue(e,n){for(let i=0;i<n.length;i++)if(Ie.patternMatchVariance(e,n[i],Zt.MAX_INDIVIDUAL_VARIANCE)<Zt.MAX_AVG_VARIANCE)return i;throw new D}static count(e){return je.sum(new Int32Array(e))}static increment(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],i=a);e[i]++}static decrement(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],i=a);e[i]--}static isFinderPattern(e){let n=e[0]+e[1],i=n+e[2]+e[3],s=n/i;if(s>=Zt.MIN_FINDER_PATTERN_RATIO&&s<=Zt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let d of e)d>l&&(l=d),d<a&&(a=d);return l<10*a}return!1}}Zt.MAX_AVG_VARIANCE=.2,Zt.MAX_INDIVIDUAL_VARIANCE=.45,Zt.MIN_FINDER_PATTERN_RATIO=9.5/12,Zt.MAX_FINDER_PATTERN_RATIO=12.5/14;class mr{constructor(e,n){this.value=e,this.checksumPortion=n}getValue(){return this.value}getChecksumPortion(){return this.checksumPortion}toString(){return this.value+"("+this.checksumPortion+")"}equals(e){if(!(e instanceof mr))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class ci{constructor(e,n,i,s,a){this.value=e,this.startEnd=n,this.value=e,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new T(i,a)),this.resultPoints.push(new T(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof ci))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class In{constructor(){}static getRSSvalue(e,n,i){let s=0;for(let h of e)s+=h;let a=0,l=0,d=e.length;for(let h=0;h<d-1;h++){let p;for(p=1,l|=1<<h;p<e[h];p++,l&=~(1<<h)){let y=In.combins(s-p-1,d-h-2);if(i&&l===0&&s-p-(d-h-1)>=d-h-1&&(y-=In.combins(s-p-(d-h),d-h-2)),d-h-1>1){let E=0;for(let I=s-p-(d-h-2);I>n;I--)E+=In.combins(s-p-I-1,d-h-3);y-=E*(d-1-h)}else s-p>n&&y--;a+=y}s-=p}return a}static combins(e,n){let i,s;e-n>n?(s=n,i=e-n):(s=e-n,i=n);let a=1,l=1;for(let d=e;d>i;d--)a*=d,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Ju{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new W(i),a=0,d=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(d&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let p=e[h],y=p.getLeftChar().getValue();for(let E=11;E>=0;--E)(y&1<<E)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let E=p.getRightChar().getValue();for(let I=11;I>=0;--I)(E&1<<I)!=0&&s.set(a),a++}}return s}}class er{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class Xi{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class Yt extends Xi{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Yt.FNC1}}Yt.FNC1="$";class tr extends Xi{constructor(e,n,i){super(e),i?(this.remaining=!0,this.remainingValue=this.remainingValue):(this.remaining=!1,this.remainingValue=0),this.newString=n}getNewString(){return this.newString}isRemaining(){return this.remaining}getRemainingValue(){return this.remainingValue}}class un extends Xi{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new V;this.firstDigit=n,this.secondDigit=i}getFirstDigit(){return this.firstDigit}getSecondDigit(){return this.secondDigit}getValue(){return this.firstDigit*10+this.secondDigit}isFirstDigitFNC1(){return this.firstDigit===un.FNC1}isSecondDigitFNC1(){return this.secondDigit===un.FNC1}isAnyFNC1(){return this.firstDigit===un.FNC1||this.secondDigit===un.FNC1}}un.FNC1=10;class _e{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new D;let n=e.substring(0,2);for(let a of _e.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(2,a[2],e):_e.processFixedAI(2,a[1],e);if(e.length<3)throw new D;let i=e.substring(0,3);for(let a of _e.THREE_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(3,a[2],e):_e.processFixedAI(3,a[1],e);for(let a of _e.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(4,a[2],e):_e.processFixedAI(4,a[1],e);if(e.length<4)throw new D;let s=e.substring(0,4);for(let a of _e.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===_e.VARIABLE_LENGTH?_e.processVariableAI(4,a[2],e):_e.processFixedAI(4,a[1],e);throw new D}static processFixedAI(e,n,i){if(i.length<e)throw new D;let s=i.substring(0,e);if(i.length<e+n)throw new D;let a=i.substring(e,e+n),l=i.substring(e+n),d="("+s+")"+a,h=_e.parseFieldsInGeneralPurpose(l);return h==null?d:d+h}static processVariableAI(e,n,i){let s=i.substring(0,e),a;i.length<e+n?a=i.length:a=e+n;let l=i.substring(e,a),d=i.substring(a),h="("+s+")"+l,p=_e.parseFieldsInGeneralPurpose(d);return p==null?h:h+p}}_e.VARIABLE_LENGTH=[],_e.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",_e.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",_e.VARIABLE_LENGTH,20],["22",_e.VARIABLE_LENGTH,29],["30",_e.VARIABLE_LENGTH,8],["37",_e.VARIABLE_LENGTH,8],["90",_e.VARIABLE_LENGTH,30],["91",_e.VARIABLE_LENGTH,30],["92",_e.VARIABLE_LENGTH,30],["93",_e.VARIABLE_LENGTH,30],["94",_e.VARIABLE_LENGTH,30],["95",_e.VARIABLE_LENGTH,30],["96",_e.VARIABLE_LENGTH,30],["97",_e.VARIABLE_LENGTH,3],["98",_e.VARIABLE_LENGTH,30],["99",_e.VARIABLE_LENGTH,30]],_e.THREE_DIGIT_DATA_LENGTH=[["240",_e.VARIABLE_LENGTH,30],["241",_e.VARIABLE_LENGTH,30],["242",_e.VARIABLE_LENGTH,6],["250",_e.VARIABLE_LENGTH,30],["251",_e.VARIABLE_LENGTH,30],["253",_e.VARIABLE_LENGTH,17],["254",_e.VARIABLE_LENGTH,20],["400",_e.VARIABLE_LENGTH,30],["401",_e.VARIABLE_LENGTH,30],["402",17],["403",_e.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",_e.VARIABLE_LENGTH,20],["421",_e.VARIABLE_LENGTH,15],["422",3],["423",_e.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],_e.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=[["310",6],["311",6],["312",6],["313",6],["314",6],["315",6],["316",6],["320",6],["321",6],["322",6],["323",6],["324",6],["325",6],["326",6],["327",6],["328",6],["329",6],["330",6],["331",6],["332",6],["333",6],["334",6],["335",6],["336",6],["340",6],["341",6],["342",6],["343",6],["344",6],["345",6],["346",6],["347",6],["348",6],["349",6],["350",6],["351",6],["352",6],["353",6],["354",6],["355",6],["356",6],["357",6],["360",6],["361",6],["362",6],["363",6],["364",6],["365",6],["366",6],["367",6],["368",6],["369",6],["390",_e.VARIABLE_LENGTH,15],["391",_e.VARIABLE_LENGTH,18],["392",_e.VARIABLE_LENGTH,15],["393",_e.VARIABLE_LENGTH,18],["703",_e.VARIABLE_LENGTH,30]],_e.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",_e.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",_e.VARIABLE_LENGTH,20],["8003",_e.VARIABLE_LENGTH,30],["8004",_e.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",_e.VARIABLE_LENGTH,30],["8008",_e.VARIABLE_LENGTH,12],["8018",18],["8020",_e.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",_e.VARIABLE_LENGTH,70],["8200",_e.VARIABLE_LENGTH,70]];class gr{constructor(e){this.buffer=new ae,this.information=e}decodeAllCodes(e,n){let i=n,s=null;do{let a=this.decodeGeneralPurposeField(i,s),l=_e.parseFieldsInGeneralPurpose(a.getNewString());if(l!=null&&e.append(l),a.isRemaining()?s=""+a.getRemainingValue():s=null,i===a.getNewPosition())break;i=a.getNewPosition()}while(!0);return e.toString()}isStillNumeric(e){if(e+7>this.information.getSize())return e+4<=this.information.getSize();for(let n=e;n<e+3;++n)if(this.information.get(n))return!0;return this.information.get(e+3)}decodeNumeric(e){if(e+7>this.information.getSize()){let a=this.extractNumericValueFromBitArray(e,4);return a===0?new un(this.information.getSize(),un.FNC1,un.FNC1):new un(this.information.getSize(),a-1,un.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new un(e+7,i,s)}extractNumericValueFromBitArray(e,n){return gr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,i){let s=0;for(let a=0;a<i;++a)e.get(n+a)&&(s|=1<<i-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let i=this.parseBlocks();return i!=null&&i.isRemaining()?new tr(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new tr(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let i=this.current.getPosition();if(this.current.isAlpha()?(n=this.parseAlphaBlock(),e=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),e=n.isFinished()):(n=this.parseNumericBlock(),e=n.isFinished()),!(i!==this.current.getPosition())&&!e)break}while(!e);return n.getDecodedInformation()}parseNumericBlock(){for(;this.isStillNumeric(this.current.getPosition());){let e=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFirstDigitFNC1()){let n;return e.isSecondDigitFNC1()?n=new tr(this.current.getPosition(),this.buffer.toString()):n=new tr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new er(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new er(!1)}parseIsoIec646Block(){for(;this.isStillIsoIec646(this.current.getPosition());){let e=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new er(!1)}parseAlphaBlock(){for(;this.isStillAlpha(this.current.getPosition());){let e=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new er(!1)}isStillIsoIec646(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+7>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<116)return!0;if(e+8>this.information.getSize())return!1;let s=this.extractNumericValueFromBitArray(e,8);return s>=232&&s<253}decodeIsoIec646(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Yt(e+5,Yt.FNC1);if(n>=5&&n<15)return new Yt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new Yt(e+7,""+(i+1));if(i>=90&&i<116)return new Yt(e+7,""+(i+7));let s=this.extractNumericValueFromBitArray(e,8),a;switch(s){case 232:a="!";break;case 233:a='"';break;case 234:a="%";break;case 235:a="&";break;case 236:a="'";break;case 237:a="(";break;case 238:a=")";break;case 239:a="*";break;case 240:a="+";break;case 241:a=",";break;case 242:a="-";break;case 243:a=".";break;case 244:a="/";break;case 245:a=":";break;case 246:a=";";break;case 247:a="<";break;case 248:a="=";break;case 249:a=">";break;case 250:a="?";break;case 251:a="_";break;case 252:a=" ";break;default:throw new V}return new Yt(e+8,a)}isStillAlpha(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+6>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,6);return i>=16&&i<63}decodeAlphanumeric(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Yt(e+5,Yt.FNC1);if(n>=5&&n<15)return new Yt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new Yt(e+6,""+(i+33));let s;switch(i){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new Vt("Decoding invalid alphanumeric value: "+i)}return new Yt(e+6,s)}isAlphaTo646ToAlphaLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<5&&n+e<this.information.getSize();++n)if(n===2){if(!this.information.get(e+2))return!1}else if(this.information.get(e+n))return!1;return!0}isAlphaOr646ToNumericLatch(e){if(e+3>this.information.getSize())return!1;for(let n=e;n<e+3;++n)if(this.information.get(n))return!1;return!0}isNumericToAlphaNumericLatch(e){if(e+1>this.information.getSize())return!1;for(let n=0;n<4&&n+e<this.information.getSize();++n)if(this.information.get(e+n))return!1;return!0}}class qi{constructor(e){this.information=e,this.generalDecoder=new gr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class Jt extends qi{constructor(e){super(e)}encodeCompressedGtin(e,n){e.append("(01)");let i=e.length();e.append("9"),this.encodeCompressedGtinWithoutAI(e,n,i)}encodeCompressedGtinWithoutAI(e,n,i){for(let s=0;s<4;++s){let a=this.getGeneralDecoder().extractNumericValueFromBitArray(n+10*s,10);a/100===0&&e.append("0"),a/10===0&&e.append("0"),e.append(a)}Jt.appendCheckDigit(e,i)}static appendCheckDigit(e,n){let i=0;for(let s=0;s<13;s++){let a=e.charAt(s+n).charCodeAt(0)-48;i+=(s&1)===0?3*a:a}i=10-i%10,i===10&&(i=0),e.append(i)}}Jt.GTIN_SIZE=40;class xr extends Jt{constructor(e){super(e)}parseInformation(){let e=new ae;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(xr.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,xr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,xr.HEADER_SIZE+44)}}xr.HEADER_SIZE=4;class ui extends qi{constructor(e){super(e)}parseInformation(){let e=new ae;return this.getGeneralDecoder().decodeAllCodes(e,ui.HEADER_SIZE)}}ui.HEADER_SIZE=5;class di extends Jt{constructor(e){super(e)}encodeCompressedWeight(e,n,i){let s=this.getGeneralDecoder().extractNumericValueFromBitArray(n,i);this.addWeightCode(e,s);let a=this.checkWeight(s),l=1e5;for(let d=0;d<5;++d)a/l===0&&e.append("0"),l/=10;e.append(a)}}class Sn extends di{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Sn.HEADER_SIZE+di.GTIN_SIZE+Sn.WEIGHT_SIZE)throw new D;let e=new ae;return this.encodeCompressedGtin(e,Sn.HEADER_SIZE),this.encodeCompressedWeight(e,Sn.HEADER_SIZE+di.GTIN_SIZE,Sn.WEIGHT_SIZE),e.toString()}}Sn.HEADER_SIZE=5,Sn.WEIGHT_SIZE=15;class Ku extends Sn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Qu extends Sn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class Tn extends Jt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Tn.HEADER_SIZE+Jt.GTIN_SIZE)throw new D;let e=new ae;this.encodeCompressedGtin(e,Tn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Tn.HEADER_SIZE+Jt.GTIN_SIZE,Tn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(Tn.HEADER_SIZE+Jt.GTIN_SIZE+Tn.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}Tn.HEADER_SIZE=8,Tn.LAST_DIGIT_SIZE=2;class Gt extends Jt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Gt.HEADER_SIZE+Jt.GTIN_SIZE)throw new D;let e=new ae;this.encodeCompressedGtin(e,Gt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Gt.HEADER_SIZE+Jt.GTIN_SIZE,Gt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(Gt.HEADER_SIZE+Jt.GTIN_SIZE+Gt.LAST_DIGIT_SIZE,Gt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Gt.HEADER_SIZE+Jt.GTIN_SIZE+Gt.LAST_DIGIT_SIZE+Gt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Gt.HEADER_SIZE=8,Gt.LAST_DIGIT_SIZE=2,Gt.FIRST_THREE_DIGITS_SIZE=10;class mt extends di{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=mt.HEADER_SIZE+mt.GTIN_SIZE+mt.WEIGHT_SIZE+mt.DATE_SIZE)throw new D;let e=new ae;return this.encodeCompressedGtin(e,mt.HEADER_SIZE),this.encodeCompressedWeight(e,mt.HEADER_SIZE+mt.GTIN_SIZE,mt.WEIGHT_SIZE),this.encodeCompressedDate(e,mt.HEADER_SIZE+mt.GTIN_SIZE+mt.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,mt.DATE_SIZE);if(i==38400)return;e.append("("),e.append(this.dateCode),e.append(")");let s=i%32;i/=32;let a=i%12+1;i/=12;let l=i;l/10==0&&e.append("0"),e.append(l),a/10==0&&e.append("0"),e.append(a),s/10==0&&e.append("0"),e.append(s)}addWeightCode(e,n){e.append("("),e.append(this.firstAIdigits),e.append(n/1e5),e.append(")")}checkWeight(e){return e%1e5}}mt.HEADER_SIZE=8,mt.WEIGHT_SIZE=20,mt.DATE_SIZE=16;function fs(b){try{if(b.get(1))return new xr(b);if(!b.get(2))return new ui(b);switch(gr.extractNumericValueFromBitArray(b,1,4)){case 4:return new Ku(b);case 5:return new Qu(b)}switch(gr.extractNumericValueFromBitArray(b,1,5)){case 12:return new Tn(b);case 13:return new Gt(b)}switch(gr.extractNumericValueFromBitArray(b,1,7)){case 56:return new mt(b,"310","11");case 57:return new mt(b,"320","11");case 58:return new mt(b,"310","13");case 59:return new mt(b,"320","13");case 60:return new mt(b,"310","15");case 61:return new mt(b,"320","15");case 62:return new mt(b,"310","17");case 63:return new mt(b,"320","17")}}catch(e){throw console.log(e),new Vt("unknown decoder: "+b)}}class zn{constructor(e,n,i,s){this.leftchar=e,this.rightchar=n,this.finderpattern=i,this.maybeLast=s}mayBeLast(){return this.maybeLast}getLeftChar(){return this.leftchar}getRightChar(){return this.rightchar}getFinderPattern(){return this.finderpattern}mustBeLast(){return this.rightchar==null}toString(){return"[ "+this.leftchar+", "+this.rightchar+" : "+(this.finderpattern==null?"null":this.finderpattern.getValue())+" ]"}static equals(e,n){return e instanceof zn?zn.equalsOrNull(e.leftchar,n.leftchar)&&zn.equalsOrNull(e.rightchar,n.rightchar)&&zn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:zn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Yi{constructor(e,n,i){this.pairs=e,this.rowNumber=n,this.wasReversed=i}getPairs(){return this.pairs}getRowNumber(){return this.rowNumber}isReversed(){return this.wasReversed}isEquivalent(e){return this.checkEqualitity(this,e)}toString(){return"{ "+this.pairs+" }"}equals(e,n){return e instanceof Yi?this.checkEqualitity(e,n)&&e.wasReversed===n.wasReversed:!1}checkEqualitity(e,n){if(!e||!n)return;let i;return e.forEach((s,a)=>{n.forEach(l=>{s.getLeftChar().getValue()===l.getLeftChar().getValue()&&s.getRightChar().getValue()===l.getRightChar().getValue()&&s.getFinderPatter().getValue()===l.getFinderPatter().getValue()&&(i=!0)})}),i}}class le extends Zt{constructor(e){super(...arguments),this.pairs=new Array(le.MAX_PAIRS),this.rows=new Array,this.startEnd=[2],this.verbose=e===!0}decodeRow(e,n,i){this.pairs.length=0,this.startFromEven=!1;try{return le.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,le.constructResult(this.decodeRow2pairs(e,n))}reset(){this.pairs.length=0,this.rows.length=0}decodeRow2pairs(e,n){let i=!1;for(;!i;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof D){if(!this.pairs.length)throw new D;i=!0}}if(this.checkChecksum())return this.pairs;let s;if(this.rows.length?s=!0:s=!1,this.storeRow(e,!1),s){let a=this.checkRowsBoolean(!1);if(a!=null||(a=this.checkRowsBoolean(!0),a!=null))return a}throw new D}checkRowsBoolean(e){if(this.rows.length>25)return this.rows.length=0,null;this.pairs.length=0,e&&(this.rows=this.rows.reverse());let n=null;try{n=this.checkRows(new Array,0)}catch(i){this.verbose&&console.log(i)}return e&&(this.rows=this.rows.reverse()),n}checkRows(e,n){for(let i=n;i<this.rows.length;i++){let s=this.rows[i];this.pairs.length=0;for(let l of e)this.pairs.push(l.getPairs());if(this.pairs.push(s.getPairs()),!le.isValidSequence(this.pairs))continue;if(this.checkChecksum())return this.pairs;let a=new Array(e);a.push(s);try{return this.checkRows(a,i+1)}catch(l){this.verbose&&console.log(l)}}throw new D}static isValidSequence(e){for(let n of le.FINDER_PATTERN_SEQUENCES){if(e.length>n.length)continue;let i=!0;for(let s=0;s<e.length;s++)if(e[s].getFinderPattern().getValue()!=n[s]){i=!1;break}if(i)return!0}return!1}storeRow(e,n){let i=0,s=!1,a=!1;for(;i<this.rows.length;){let l=this.rows[i];if(l.getRowNumber()>e){a=l.isEquivalent(this.pairs);break}s=l.isEquivalent(this.pairs),i++}a||s||le.isPartialRow(this.pairs,this.rows)||(this.rows.push(i,new Yi(this.pairs,e,n)),this.removePartialRows(this.pairs,this.rows))}removePartialRows(e,n){for(let i of n)if(i.getPairs().length!==e.length){for(let s of i.getPairs())for(let a of e)if(zn.equals(s,a))break}}static isPartialRow(e,n){for(let i of n){let s=!0;for(let a of e){let l=!1;for(let d of i.getPairs())if(a.equals(d)){l=!0;break}if(!l){s=!1;break}}if(s)return!0}return!1}getRows(){return this.rows}static constructResult(e){let n=Ju.buildBitArray(e),s=fs(n).parseInformation(),a=e[0].getFinderPattern().getResultPoints(),l=e[e.length-1].getFinderPattern().getResultPoints(),d=[a[0],a[1],l[0],l[1]];return new Me(s,null,null,d,ie.RSS_EXPANDED,null)}checkChecksum(){let e=this.pairs.get(0),n=e.getLeftChar(),i=e.getRightChar();if(i==null)return!1;let s=i.getChecksumPortion(),a=2;for(let d=1;d<this.pairs.size();++d){let h=this.pairs.get(d);s+=h.getLeftChar().getChecksumPortion(),a++;let p=h.getRightChar();p!=null&&(s+=p.getChecksumPortion(),a++)}return s%=211,211*(a-4)+s==n.getValue()}static getNextSecondBar(e,n){let i;return e.get(n)?(i=e.getNextUnset(n),i=e.getNextSet(i)):(i=e.getNextSet(n),i=e.getNextUnset(i)),i}retrieveNextPair(e,n,i){let s=n.length%2==0;this.startFromEven&&(s=!s);let a,l=!0,d=-1;do this.findNextPair(e,n,d),a=this.parseFoundFinderPattern(e,i,s),a==null?d=le.getNextSecondBar(e,this.startEnd[0]):l=!1;while(l);let h=this.decodeDataCharacter(e,a,s,!0);if(!this.isEmptyPair(n)&&n[n.length-1].mustBeLast())throw new D;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new zn(h,p,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,i){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;i>=0?l=i:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let d=n.length%2!=0;this.startFromEven&&(d=!d);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let p=0,y=l;for(let E=l;E<a;E++)if(e.get(E)!=h)s[p]++;else{if(p==3){if(d&&le.reverseCounters(s),le.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=E;return}d&&le.reverseCounters(s),y+=s[0]+s[1],s[0]=s[2],s[1]=s[3],s[2]=0,s[3]=0,p--}else p++;s[p]=1,h=!h}throw new D}static reverseCounters(e){let n=e.length;for(let i=0;i<n/2;++i){let s=e[i];e[i]=e[n-i-1],e[n-i-1]=s}}parseFoundFinderPattern(e,n,i){let s,a,l;if(i){let p=this.startEnd[0]-1;for(;p>=0&&!e.get(p);)p--;p++,s=this.startEnd[0]-p,a=p,l=this.startEnd[1]}else a=this.startEnd[0],l=e.getNextUnset(this.startEnd[1]+1),s=l-this.startEnd[1];let d=this.getDecodeFinderCounters();B.arraycopy(d,0,d,1,d.length-1),d[0]=s;let h;try{h=this.parseFinderValue(d,le.FINDER_PATTERNS)}catch{return null}return new ci(h,[a,l],a,l,n)}decodeDataCharacter(e,n,i,s){let a=this.getDataCharacterCounters();for(let at=0;at<a.length;at++)a[at]=0;if(s)le.recordPatternInReverse(e,n.getStartEnd()[0],a);else{le.recordPattern(e,n.getStartEnd()[1],a);for(let at=0,zt=a.length-1;at<zt;at++,zt--){let rn=a[at];a[at]=a[zt],a[zt]=rn}}let l=17,d=je.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(d-h)/h>.3)throw new D;let p=this.getOddCounts(),y=this.getEvenCounts(),E=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let at=0;at<a.length;at++){let zt=1*a[at]/d,rn=zt+.5;if(rn<1){if(zt<.3)throw new D;rn=1}else if(rn>8){if(zt>8.7)throw new D;rn=8}let Cr=at/2;(at&1)==0?(p[Cr]=rn,E[Cr]=zt-rn):(y[Cr]=rn,I[Cr]=zt-rn)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(i?0:2)+(s?0:1)-1,F=0,U=0;for(let at=p.length-1;at>=0;at--){if(le.isNotA1left(n,i,s)){let zt=le.WEIGHTS[R][2*at];U+=p[at]*zt}F+=p[at]}let Y=0;for(let at=y.length-1;at>=0;at--)if(le.isNotA1left(n,i,s)){let zt=le.WEIGHTS[R][2*at+1];Y+=y[at]*zt}let re=U+Y;if((F&1)!=0||F>13||F<4)throw new D;let me=(13-F)/2,xe=le.SYMBOL_WIDEST[me],ue=9-xe,We=In.getRSSvalue(p,xe,!0),Be=In.getRSSvalue(y,ue,!1),Qt=le.EVEN_TOTAL_SUBSET[me],gn=le.GSUM[me],en=We*Qt+Be+gn;return new mr(en,re)}static isNotA1left(e,n,i){return!(e.getValue()==0&&n&&i)}adjustOddEvenCounts(e){let n=je.sum(new Int32Array(this.getOddCounts())),i=je.sum(new Int32Array(this.getEvenCounts())),s=!1,a=!1;n>13?a=!0:n<4&&(s=!0);let l=!1,d=!1;i>13?d=!0:i<4&&(l=!0);let h=n+i-e,p=(n&1)==1,y=(i&1)==0;if(h==1)if(p){if(y)throw new D;a=!0}else{if(!y)throw new D;d=!0}else if(h==-1)if(p){if(y)throw new D;s=!0}else{if(!y)throw new D;l=!0}else if(h==0){if(p){if(!y)throw new D;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(y)throw new D}else throw new D;if(s){if(a)throw new D;le.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&le.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new D;le.increment(this.getEvenCounts(),this.getOddRoundingErrors())}d&&le.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}le.SYMBOL_WIDEST=[7,5,4,3,1],le.EVEN_TOTAL_SUBSET=[4,20,52,104,204],le.GSUM=[0,348,1388,2948,3988],le.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])],le.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]],le.FINDER_PAT_A=0,le.FINDER_PAT_B=1,le.FINDER_PAT_C=2,le.FINDER_PAT_D=3,le.FINDER_PAT_E=4,le.FINDER_PAT_F=5,le.FINDER_PATTERN_SEQUENCES=[[le.FINDER_PAT_A,le.FINDER_PAT_A],[le.FINDER_PAT_A,le.FINDER_PAT_B,le.FINDER_PAT_B],[le.FINDER_PAT_A,le.FINDER_PAT_C,le.FINDER_PAT_B,le.FINDER_PAT_D],[le.FINDER_PAT_A,le.FINDER_PAT_E,le.FINDER_PAT_B,le.FINDER_PAT_D,le.FINDER_PAT_C],[le.FINDER_PAT_A,le.FINDER_PAT_E,le.FINDER_PAT_B,le.FINDER_PAT_D,le.FINDER_PAT_D,le.FINDER_PAT_F],[le.FINDER_PAT_A,le.FINDER_PAT_E,le.FINDER_PAT_B,le.FINDER_PAT_D,le.FINDER_PAT_E,le.FINDER_PAT_F,le.FINDER_PAT_F],[le.FINDER_PAT_A,le.FINDER_PAT_A,le.FINDER_PAT_B,le.FINDER_PAT_B,le.FINDER_PAT_C,le.FINDER_PAT_C,le.FINDER_PAT_D,le.FINDER_PAT_D],[le.FINDER_PAT_A,le.FINDER_PAT_A,le.FINDER_PAT_B,le.FINDER_PAT_B,le.FINDER_PAT_C,le.FINDER_PAT_C,le.FINDER_PAT_D,le.FINDER_PAT_E,le.FINDER_PAT_E],[le.FINDER_PAT_A,le.FINDER_PAT_A,le.FINDER_PAT_B,le.FINDER_PAT_B,le.FINDER_PAT_C,le.FINDER_PAT_C,le.FINDER_PAT_D,le.FINDER_PAT_E,le.FINDER_PAT_F,le.FINDER_PAT_F],[le.FINDER_PAT_A,le.FINDER_PAT_A,le.FINDER_PAT_B,le.FINDER_PAT_B,le.FINDER_PAT_C,le.FINDER_PAT_D,le.FINDER_PAT_D,le.FINDER_PAT_E,le.FINDER_PAT_E,le.FINDER_PAT_F,le.FINDER_PAT_F]],le.MAX_PAIRS=11;class ed extends mr{constructor(e,n,i){super(e,n),this.count=0,this.finderPattern=i}getFinderPattern(){return this.finderPattern}getCount(){return this.count}incrementCount(){this.count++}}class At extends Zt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);At.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);At.addOrTally(this.possibleRightPairs,a),n.reverse();for(let l of this.possibleLeftPairs)if(l.getCount()>1){for(let d of this.possibleRightPairs)if(d.getCount()>1&&At.checkChecksum(l,d))return At.constructResult(l,d)}throw new D}static addOrTally(e,n){if(n==null)return;let i=!1;for(let s of e)if(s.getValue()===n.getValue()){s.incrementCount(),i=!0;break}i||e.push(n)}reset(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0}static constructResult(e,n){let i=4537077*e.getValue()+n.getValue(),s=new String(i).toString(),a=new ae;for(let p=13-s.length;p>0;p--)a.append("0");a.append(s);let l=0;for(let p=0;p<13;p++){let y=a.charAt(p).charCodeAt(0)-48;l+=(p&1)===0?3*y:y}l=10-l%10,l===10&&(l=0),a.append(l.toString());let d=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new Me(a.toString(),null,0,[d[0],d[1],h[0],h[1]],ie.RSS_14,new Date().getTime())}static checkChecksum(e,n){let i=(e.getChecksumPortion()+16*n.getChecksumPortion())%79,s=9*e.getFinderPattern().getValue()+n.getFinderPattern().getValue();return s>72&&s--,s>8&&s--,i===s}decodePair(e,n,i,s){try{let a=this.findFinderPattern(e,n),l=this.parseFoundFinderPattern(e,i,n,a),d=s==null?null:s.get(H.NEED_RESULT_POINT_CALLBACK);if(d!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),d.foundPossibleResultPoint(new T(y,i))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new ed(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let Y=0;Y<s.length;Y++)s[Y]=0;if(i)Ie.recordPatternInReverse(e,n.getStartEnd()[0],s);else{Ie.recordPattern(e,n.getStartEnd()[1]+1,s);for(let Y=0,re=s.length-1;Y<re;Y++,re--){let me=s[Y];s[Y]=s[re],s[re]=me}}let a=i?16:15,l=je.sum(new Int32Array(s))/a,d=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let Y=0;Y<s.length;Y++){let re=s[Y]/l,me=Math.floor(re+.5);me<1?me=1:me>8&&(me=8);let xe=Math.floor(Y/2);(Y&1)===0?(d[xe]=me,p[xe]=re-me):(h[xe]=me,y[xe]=re-me)}this.adjustOddEvenCounts(i,a);let E=0,I=0;for(let Y=d.length-1;Y>=0;Y--)I*=9,I+=d[Y],E+=d[Y];let R=0,F=0;for(let Y=h.length-1;Y>=0;Y--)R*=9,R+=h[Y],F+=h[Y];let U=I+3*R;if(i){if((E&1)!==0||E>12||E<4)throw new D;let Y=(12-E)/2,re=At.OUTSIDE_ODD_WIDEST[Y],me=9-re,xe=In.getRSSvalue(d,re,!1),ue=In.getRSSvalue(h,me,!0),We=At.OUTSIDE_EVEN_TOTAL_SUBSET[Y],Be=At.OUTSIDE_GSUM[Y];return new mr(xe*We+ue+Be,U)}else{if((F&1)!==0||F>10||F<4)throw new D;let Y=(10-F)/2,re=At.INSIDE_ODD_WIDEST[Y],me=9-re,xe=In.getRSSvalue(d,re,!0),ue=In.getRSSvalue(h,me,!1),We=At.INSIDE_ODD_TOTAL_SUBSET[Y],Be=At.INSIDE_GSUM[Y];return new mr(ue*We+xe+Be,U)}}findFinderPattern(e,n){let i=this.getDecodeFinderCounters();i[0]=0,i[1]=0,i[2]=0,i[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let d=0,h=l;for(let p=l;p<s;p++)if(e.get(p)!==a)i[d]++;else{if(d===3){if(Zt.isFinderPattern(i))return[h,p];h+=i[0]+i[1],i[0]=i[2],i[1]=i[3],i[2]=0,i[3]=0,d--}else d++;i[d]=1,a=!a}throw new D}parseFoundFinderPattern(e,n,i,s){let a=e.get(s[0]),l=s[0]-1;for(;l>=0&&a!==e.get(l);)l--;l++;const d=s[0]-l,h=this.getDecodeFinderCounters(),p=new Int32Array(h.length);B.arraycopy(h,0,p,1,h.length-1),p[0]=d;const y=this.parseFinderValue(p,At.FINDER_PATTERNS);let E=l,I=s[1];return i&&(E=e.getSize()-1-E,I=e.getSize()-1-I),new ci(y,[l,s[1]],E,I,n)}adjustOddEvenCounts(e,n){let i=je.sum(new Int32Array(this.getOddCounts())),s=je.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,d=!1,h=!1;e?(i>12?l=!0:i<4&&(a=!0),s>12?h=!0:s<4&&(d=!0)):(i>11?l=!0:i<5&&(a=!0),s>10?h=!0:s<4&&(d=!0));let p=i+s-n,y=(i&1)===(e?1:0),E=(s&1)===1;if(p===1)if(y){if(E)throw new D;l=!0}else{if(!E)throw new D;h=!0}else if(p===-1)if(y){if(E)throw new D;a=!0}else{if(!E)throw new D;d=!0}else if(p===0){if(y){if(!E)throw new D;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(E)throw new D}else throw new D;if(a){if(l)throw new D;Zt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Zt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new D;Zt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Zt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}At.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],At.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],At.OUTSIDE_GSUM=[0,161,961,2015,2715],At.INSIDE_GSUM=[0,336,1036,1516],At.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],At.INSIDE_ODD_WIDEST=[2,4,6,8],At.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])];class yr extends Ie{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(H.POSSIBLE_FORMATS):null,s=e&&e.get(H.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(ie.EAN_13)||i.includes(ie.UPC_A)||i.includes(ie.EAN_8)||i.includes(ie.UPC_E))&&this.readers.push(new Gi(e)),i.includes(ie.CODE_39)&&this.readers.push(new Re(s)),i.includes(ie.CODE_128)&&this.readers.push(new oe),i.includes(ie.ITF)&&this.readers.push(new qe),i.includes(ie.RSS_14)&&this.readers.push(new At),i.includes(ie.RSS_EXPANDED)&&this.readers.push(new le(this.verbose))):(this.readers.push(new Gi(e)),this.readers.push(new Re),this.readers.push(new Gi(e)),this.readers.push(new oe),this.readers.push(new qe),this.readers.push(new At),this.readers.push(new le(this.verbose)))}decodeRow(e,n,i){for(let s=0;s<this.readers.length;s++)try{return this.readers[s].decodeRow(e,n,i)}catch{}throw new D}reset(){this.readers.forEach(e=>e.reset())}}class td extends Ve{constructor(e=500,n){super(new yr(n),e,n)}}class tt{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class Qe{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class He{constructor(e,n,i,s,a,l){this.versionNumber=e,this.symbolSizeRows=n,this.symbolSizeColumns=i,this.dataRegionSizeRows=s,this.dataRegionSizeColumns=a,this.ecBlocks=l;let d=0;const h=l.getECCodewords(),p=l.getECBlocks();for(let y of p)d+=y.getCount()*(y.getDataCodewords()+h);this.totalCodewords=d}getVersionNumber(){return this.versionNumber}getSymbolSizeRows(){return this.symbolSizeRows}getSymbolSizeColumns(){return this.symbolSizeColumns}getDataRegionSizeRows(){return this.dataRegionSizeRows}getDataRegionSizeColumns(){return this.dataRegionSizeColumns}getTotalCodewords(){return this.totalCodewords}getECBlocks(){return this.ecBlocks}static getVersionForDimensions(e,n){if((e&1)!==0||(n&1)!==0)throw new V;for(let i of He.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new V}toString(){return""+this.versionNumber}static buildVersions(){return[new He(1,10,10,8,8,new tt(5,new Qe(1,3))),new He(2,12,12,10,10,new tt(7,new Qe(1,5))),new He(3,14,14,12,12,new tt(10,new Qe(1,8))),new He(4,16,16,14,14,new tt(12,new Qe(1,12))),new He(5,18,18,16,16,new tt(14,new Qe(1,18))),new He(6,20,20,18,18,new tt(18,new Qe(1,22))),new He(7,22,22,20,20,new tt(20,new Qe(1,30))),new He(8,24,24,22,22,new tt(24,new Qe(1,36))),new He(9,26,26,24,24,new tt(28,new Qe(1,44))),new He(10,32,32,14,14,new tt(36,new Qe(1,62))),new He(11,36,36,16,16,new tt(42,new Qe(1,86))),new He(12,40,40,18,18,new tt(48,new Qe(1,114))),new He(13,44,44,20,20,new tt(56,new Qe(1,144))),new He(14,48,48,22,22,new tt(68,new Qe(1,174))),new He(15,52,52,24,24,new tt(42,new Qe(2,102))),new He(16,64,64,14,14,new tt(56,new Qe(2,140))),new He(17,72,72,16,16,new tt(36,new Qe(4,92))),new He(18,80,80,18,18,new tt(48,new Qe(4,114))),new He(19,88,88,20,20,new tt(56,new Qe(4,144))),new He(20,96,96,22,22,new tt(68,new Qe(4,174))),new He(21,104,104,24,24,new tt(56,new Qe(6,136))),new He(22,120,120,18,18,new tt(68,new Qe(6,175))),new He(23,132,132,20,20,new tt(62,new Qe(8,163))),new He(24,144,144,22,22,new tt(62,new Qe(8,156),new Qe(2,155))),new He(25,8,18,6,16,new tt(7,new Qe(1,5))),new He(26,8,32,6,14,new tt(11,new Qe(1,10))),new He(27,12,26,10,24,new tt(14,new Qe(1,16))),new He(28,12,36,10,16,new tt(18,new Qe(1,22))),new He(29,16,36,14,16,new tt(24,new Qe(1,32))),new He(30,16,48,14,22,new tt(28,new Qe(1,49)))]}}He.VERSIONS=He.buildVersions();class Ji{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new V;this.version=Ji.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new q(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return He.getVersionForDimensions(n,i)}readCodewords(){const e=new Int8Array(this.version.getTotalCodewords());let n=0,i=4,s=0;const a=this.mappingBitMatrix.getHeight(),l=this.mappingBitMatrix.getWidth();let d=!1,h=!1,p=!1,y=!1;do if(i===a&&s===0&&!d)e[n++]=this.readCorner1(a,l)&255,i-=2,s+=2,d=!0;else if(i===a-2&&s===0&&(l&3)!==0&&!h)e[n++]=this.readCorner2(a,l)&255,i-=2,s+=2,h=!0;else if(i===a+4&&s===2&&(l&7)===0&&!p)e[n++]=this.readCorner3(a,l)&255,i-=2,s+=2,p=!0;else if(i===a-2&&s===0&&(l&7)===4&&!y)e[n++]=this.readCorner4(a,l)&255,i-=2,s+=2,y=!0;else{do i<a&&s>=0&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i-=2,s+=2;while(i>=0&&s<l);i+=1,s+=3;do i>=0&&s<l&&!this.readMappingMatrix.get(s,i)&&(e[n++]=this.readUtah(i,s,a,l)&255),i+=2,s-=2;while(i<a&&s>=0);i+=3,s+=1}while(i<a||s<l);if(n!==this.version.getTotalCodewords())throw new V;return e}readModule(e,n,i,s){return e<0&&(e+=i,n+=4-(i+4&7)),n<0&&(n+=s,e+=4-(s+4&7)),this.readMappingMatrix.set(n,e),this.mappingBitMatrix.get(n,e)}readUtah(e,n,i,s){let a=0;return this.readModule(e-2,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-2,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e-1,n,i,s)&&(a|=1),a<<=1,this.readModule(e,n-2,i,s)&&(a|=1),a<<=1,this.readModule(e,n-1,i,s)&&(a|=1),a<<=1,this.readModule(e,n,i,s)&&(a|=1),a}readCorner1(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,1,e,n)&&(i|=1),i<<=1,this.readModule(e-1,2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}readCorner2(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-4,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner3(e,n){let i=0;return this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(0,n-3,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-3,e,n)&&(i|=1),i<<=1,this.readModule(1,n-2,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i}readCorner4(e,n){let i=0;return this.readModule(e-3,0,e,n)&&(i|=1),i<<=1,this.readModule(e-2,0,e,n)&&(i|=1),i<<=1,this.readModule(e-1,0,e,n)&&(i|=1),i<<=1,this.readModule(0,n-2,e,n)&&(i|=1),i<<=1,this.readModule(0,n-1,e,n)&&(i|=1),i<<=1,this.readModule(1,n-1,e,n)&&(i|=1),i<<=1,this.readModule(2,n-1,e,n)&&(i|=1),i<<=1,this.readModule(3,n-1,e,n)&&(i|=1),i}extractDataRegion(e){const n=this.version.getSymbolSizeRows(),i=this.version.getSymbolSizeColumns();if(e.getHeight()!==n)throw new A("Dimension of bitMatrix must match the version size");const s=this.version.getDataRegionSizeRows(),a=this.version.getDataRegionSizeColumns(),l=n/s|0,d=i/a|0,h=l*s,p=d*a,y=new q(p,h);for(let E=0;E<l;++E){const I=E*s;for(let R=0;R<d;++R){const F=R*a;for(let U=0;U<s;++U){const Y=E*(s+2)+1+U,re=I+U;for(let me=0;me<a;++me){const xe=R*(a+2)+1+me;if(e.get(xe,Y)){const ue=F+me;y.set(ue,re)}}}}}return y}}class Ki{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n){const i=n.getECBlocks();let s=0;const a=i.getECBlocks();for(let U of a)s+=U.getCount();const l=new Array(s);let d=0;for(let U of a)for(let Y=0;Y<U.getCount();Y++){const re=U.getDataCodewords(),me=i.getECCodewords()+re;l[d++]=new Ki(re,new Uint8Array(me))}const p=l[0].codewords.length-i.getECCodewords(),y=p-1;let E=0;for(let U=0;U<y;U++)for(let Y=0;Y<d;Y++)l[Y].codewords[U]=e[E++];const I=n.getVersionNumber()===24,R=I?8:d;for(let U=0;U<R;U++)l[U].codewords[p-1]=e[E++];const F=l[0].codewords.length;for(let U=p;U<F;U++)for(let Y=0;Y<d;Y++){const re=I?(Y+8)%d:Y,me=I&&re>7?U-1:U;l[re].codewords[me]=e[E++]}if(E!==e.length)throw new A;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Qi{constructor(e){this.bytes=e,this.byteOffset=0,this.bitOffset=0}getBitOffset(){return this.bitOffset}getByteOffset(){return this.byteOffset}readBits(e){if(e<1||e>32||e>this.available())throw new A(""+e);let n=0,i=this.bitOffset,s=this.byteOffset;const a=this.bytes;if(i>0){const l=8-i,d=e<l?e:l,h=l-d,p=255>>8-d<<h;n=(a[s]&p)>>h,e-=d,i+=d,i===8&&(i=0,s++)}if(e>0){for(;e>=8;)n=n<<8|a[s]&255,s++,e-=8;if(e>0){const l=8-e,d=255>>l<<l;n=n<<e|(a[s]&d)>>l,i+=e}}return this.bitOffset=i,this.byteOffset=s,n}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var Ot;(function(b){b[b.PAD_ENCODE=0]="PAD_ENCODE",b[b.ASCII_ENCODE=1]="ASCII_ENCODE",b[b.C40_ENCODE=2]="C40_ENCODE",b[b.TEXT_ENCODE=3]="TEXT_ENCODE",b[b.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",b[b.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",b[b.BASE256_ENCODE=6]="BASE256_ENCODE"})(Ot||(Ot={}));class $n{static decode(e){const n=new Qi(e),i=new ae,s=new ae,a=new Array;let l=Ot.ASCII_ENCODE;do if(l===Ot.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Ot.C40_ENCODE:this.decodeC40Segment(n,i);break;case Ot.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Ot.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Ot.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Ot.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new V}l=Ot.ASCII_ENCODE}while(l!==Ot.PAD_ENCODE&&n.available()>0);return s.length()>0&&i.append(s.toString()),new Ne(e,i.toString(),a.length===0?null:a,null)}static decodeAsciiSegment(e,n,i){let s=!1;do{let a=e.readBits(8);if(a===0)throw new V;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Ot.ASCII_ENCODE;if(a===129)return Ot.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Ot.C40_ENCODE;case 231:return Ot.BASE256_ENCODE;case 232:n.append("");break;case 233:case 234:break;case 235:s=!0;break;case 236:n.append("[)>05"),i.insert(0,"");break;case 237:n.append("[)>06"),i.insert(0,"");break;case 238:return Ot.ANSIX12_ENCODE;case 239:return Ot.TEXT_ENCODE;case 240:return Ot.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new V;break}}while(e.available()>0);return Ot.ASCII_ENCODE}static decodeC40Segment(e,n){let i=!1;const s=[];let a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.C40_BASIC_SET_CHARS.length){const p=this.C40_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else throw new V;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.C40_SHIFT2_SET_CHARS.length){const p=this.C40_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new V}a=0;break;case 3:i?(n.append(String.fromCharCode(h+224)),i=!1):n.append(String.fromCharCode(h+96)),a=0;break;default:throw new V}}}while(e.available()>0)}static decodeTextSegment(e,n){let i=!1,s=[],a=0;do{if(e.available()===8)return;const l=e.readBits(8);if(l===254)return;this.parseTwoBytes(l,e.readBits(8),s);for(let d=0;d<3;d++){const h=s[d];switch(a){case 0:if(h<3)a=h+1;else if(h<this.TEXT_BASIC_SET_CHARS.length){const p=this.TEXT_BASIC_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else throw new V;break;case 1:i?(n.append(String.fromCharCode(h+128)),i=!1):n.append(String.fromCharCode(h)),a=0;break;case 2:if(h<this.TEXT_SHIFT2_SET_CHARS.length){const p=this.TEXT_SHIFT2_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:i=!0;break;default:throw new V}a=0;break;case 3:if(h<this.TEXT_SHIFT3_SET_CHARS.length){const p=this.TEXT_SHIFT3_SET_CHARS[h];i?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),i=!1):n.append(p),a=0}else throw new V;break;default:throw new V}}}while(e.available()>0)}static decodeAnsiX12Segment(e,n){const i=[];do{if(e.available()===8)return;const s=e.readBits(8);if(s===254)return;this.parseTwoBytes(s,e.readBits(8),i);for(let a=0;a<3;a++){const l=i[a];switch(l){case 0:n.append("\r");break;case 1:n.append("*");break;case 2:n.append(">");break;case 3:n.append(" ");break;default:if(l<14)n.append(String.fromCharCode(l+44));else if(l<40)n.append(String.fromCharCode(l+51));else throw new V;break}}}while(e.available()>0)}static parseTwoBytes(e,n,i){let s=(e<<8)+n-1,a=Math.floor(s/1600);i[0]=a,s-=a*1600,a=Math.floor(s/40),i[1]=a,i[2]=s-a*40}static decodeEdifactSegment(e,n){do{if(e.available()<=16)return;for(let i=0;i<4;i++){let s=e.readBits(6);if(s===31){const a=8-e.getBitOffset();a!==8&&e.readBits(a);return}(s&32)===0&&(s|=64),n.append(String.fromCharCode(s))}}while(e.available()>0)}static decodeBase256Segment(e,n,i){let s=1+e.getByteOffset();const a=this.unrandomize255State(e.readBits(8),s++);let l;if(a===0?l=e.available()/8|0:a<250?l=a:l=250*(a-249)+this.unrandomize255State(e.readBits(8),s++),l<0)throw new V;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new V;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(ce.decode(d,fe.ISO88591))}catch(h){throw new Vt("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const i=149*n%255+1,s=e-i;return s>=0?s:s+256}}$n.C40_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],$n.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],$n.TEXT_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],$n.TEXT_SHIFT2_SET_CHARS=$n.C40_SHIFT2_SET_CHARS,$n.TEXT_SHIFT3_SET_CHARS=["`","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","~",""];class nd{constructor(){this.rsDecoder=new bn(Ue.DATA_MATRIX_FIELD_256)}decode(e){const n=new Ji(e),i=n.getVersion(),s=n.readCodewords(),a=Ki.getDataBlocks(s,i);let l=0;for(let p of a)l+=p.getNumDataCodewords();const d=new Uint8Array(l),h=a.length;for(let p=0;p<h;p++){const y=a[p],E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let R=0;R<I;R++)d[R*h+p]=E[R]}return $n.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Nt{constructor(e){this.image=e,this.rectangleDetector=new vt(this.image)}detect(){const e=this.rectangleDetector.detect();let n=this.detectSolid1(e);if(n=this.detectSolid2(n),n[3]=this.correctTopRight(n),!n[3])throw new D;n=this.shiftToModuleCenter(n);const i=n[0],s=n[1],a=n[2],l=n[3];let d=this.transitionsBetween(i,l)+1,h=this.transitionsBetween(a,l)+1;(d&1)===1&&(d+=1),(h&1)===1&&(h+=1),4*d<7*h&&4*h<7*d&&(d=h=Math.max(d,h));let p=Nt.sampleGrid(this.image,i,s,a,l,d,h);return new pe(p,[i,s,a,l])}static shiftPoint(e,n,i){let s=(n.getX()-e.getX())/(i+1),a=(n.getY()-e.getY())/(i+1);return new T(e.getX()+s,e.getY()+a)}static moveAway(e,n,i){let s=e.getX(),a=e.getY();return s<n?s-=1:s+=1,a<i?a-=1:a+=1,new T(s,a)}detectSolid1(e){let n=e[0],i=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,i),d=this.transitionsBetween(i,s),h=this.transitionsBetween(s,a),p=this.transitionsBetween(a,n),y=l,E=[a,n,i,s];return y>d&&(y=d,E[0]=n,E[1]=i,E[2]=s,E[3]=a),y>h&&(y=h,E[0]=i,E[1]=s,E[2]=a,E[3]=n),y>p&&(E[0]=s,E[1]=a,E[2]=n,E[3]=i),E}detectSolid2(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=Nt.shiftPoint(i,s,(l+1)*4),h=Nt.shiftPoint(s,i,(l+1)*4),p=this.transitionsBetween(d,n),y=this.transitionsBetween(h,a);return p<y?(e[0]=n,e[1]=i,e[2]=s,e[3]=a):(e[0]=i,e[1]=s,e[2]=a,e[3]=n),e}correctTopRight(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=this.transitionsBetween(i,a),h=Nt.shiftPoint(n,i,(d+1)*4),p=Nt.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(p,a);let y=new T(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),E=new T(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(y))return this.isValid(E)?E:null;if(!this.isValid(E))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),R=this.transitionsBetween(h,E)+this.transitionsBetween(p,E);return I>R?y:E}shiftToModuleCenter(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,d=this.transitionsBetween(s,a)+1,h=Nt.shiftPoint(n,i,d*4),p=Nt.shiftPoint(s,i,l*4);l=this.transitionsBetween(h,a)+1,d=this.transitionsBetween(p,a)+1,(l&1)===1&&(l+=1),(d&1)===1&&(d+=1);let y=(n.getX()+i.getX()+s.getX()+a.getX())/4,E=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Nt.moveAway(n,y,E),i=Nt.moveAway(i,y,E),s=Nt.moveAway(s,y,E),a=Nt.moveAway(a,y,E);let I,R;return h=Nt.shiftPoint(n,i,d*4),h=Nt.shiftPoint(h,a,l*4),I=Nt.shiftPoint(i,n,d*4),I=Nt.shiftPoint(I,s,l*4),p=Nt.shiftPoint(s,a,d*4),p=Nt.shiftPoint(p,i,l*4),R=Nt.shiftPoint(a,s,d*4),R=Nt.shiftPoint(R,n,l*4),[h,I,p,R]}isValid(e){return e.getX()>=0&&e.getX()<this.image.getWidth()&&e.getY()>0&&e.getY()<this.image.getHeight()}static sampleGrid(e,n,i,s,a,l,d){return An.getInstance().sampleGrid(e,l,d,.5,.5,l-.5,.5,l-.5,d-.5,.5,d-.5,n.getX(),n.getY(),a.getX(),a.getY(),s.getX(),s.getY(),i.getX(),i.getY())}transitionsBetween(e,n){let i=Math.trunc(e.getX()),s=Math.trunc(e.getY()),a=Math.trunc(n.getX()),l=Math.trunc(n.getY()),d=Math.abs(l-s)>Math.abs(a-i);if(d){let U=i;i=s,s=U,U=a,a=l,l=U}let h=Math.abs(a-i),p=Math.abs(l-s),y=-h/2,E=s<l?1:-1,I=i<a?1:-1,R=0,F=this.image.get(d?s:i,d?i:s);for(let U=i,Y=s;U!==a;U+=I){let re=this.image.get(d?Y:U,d?U:Y);if(re!==F&&(R++,F=re),y+=p,y>0){if(Y===l)break;Y+=E,y-=h}}return R}}class Vn{constructor(){this.decoder=new nd}decode(e,n=null){let i,s;if(n!=null&&n.has(H.PURE_BARCODE)){const p=Vn.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(p),s=Vn.NO_POINTS}else{const p=new Nt(e.getBlackMatrix()).detect();i=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=i.getRawBytes(),l=new Me(i.getText(),a,8*a.length,s,ie.DATA_MATRIX,B.currentTimeMillis()),d=i.getByteSegments();d!=null&&l.putMetadata(Ae.BYTE_SEGMENTS,d);const h=i.getECLevel();return h!=null&&l.putMetadata(Ae.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n==null||i==null)throw new D;const s=this.moduleSize(n,e);let a=n[1];const l=i[1];let d=n[0];const p=(i[0]-d+1)/s,y=(l-a+1)/s;if(p<=0||y<=0)throw new D;const E=s/2;a+=E,d+=E;const I=new q(p,y);for(let R=0;R<y;R++){const F=a+R*s;for(let U=0;U<p;U++)e.get(d+U*s,F)&&I.set(U,R)}return I}static moduleSize(e,n){const i=n.getWidth();let s=e[0];const a=e[1];for(;s<i&&n.get(s,a);)s++;if(s===i)throw new D;const l=s-e[0];if(l===0)throw new D;return l}}Vn.NO_POINTS=[];class rd extends Ve{constructor(e=500){super(new Vn,e)}}var wr;(function(b){b[b.L=0]="L",b[b.M=1]="M",b[b.Q=2]="Q",b[b.H=3]="H"})(wr||(wr={}));class ut{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,ut.FOR_BITS.set(i,this),ut.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return ut.L;case"M":return ut.M;case"Q":return ut.Q;case"H":return ut.H;default:throw new C(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof ut))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=ut.FOR_BITS.size)throw new A;return ut.FOR_BITS.get(e)}}ut.FOR_BITS=new Map,ut.FOR_VALUE=new Map,ut.L=new ut(wr.L,"L",1),ut.M=new ut(wr.M,"M",0),ut.Q=new ut(wr.Q,"Q",3),ut.H=new ut(wr.H,"H",2);class jt{constructor(e){this.errorCorrectionLevel=ut.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return $.bitCount(e^n)}static decodeFormatInformation(e,n){const i=jt.doDecodeFormatInformation(e,n);return i!==null?i:jt.doDecodeFormatInformation(e^jt.FORMAT_INFO_MASK_QR,n^jt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=Number.MAX_SAFE_INTEGER,s=0;for(const a of jt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new jt(a[1]);let d=jt.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=jt.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=3?new jt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof jt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}jt.FORMAT_INFO_MASK_QR=21522,jt.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([21522,0]),Int32Array.from([20773,1]),Int32Array.from([24188,2]),Int32Array.from([23371,3]),Int32Array.from([17913,4]),Int32Array.from([16590,5]),Int32Array.from([20375,6]),Int32Array.from([19104,7]),Int32Array.from([30660,8]),Int32Array.from([29427,9]),Int32Array.from([32170,10]),Int32Array.from([30877,11]),Int32Array.from([26159,12]),Int32Array.from([25368,13]),Int32Array.from([27713,14]),Int32Array.from([26998,15]),Int32Array.from([5769,16]),Int32Array.from([5054,17]),Int32Array.from([7399,18]),Int32Array.from([6608,19]),Int32Array.from([1890,20]),Int32Array.from([597,21]),Int32Array.from([3340,22]),Int32Array.from([2107,23]),Int32Array.from([13663,24]),Int32Array.from([12392,25]),Int32Array.from([16177,26]),Int32Array.from([14854,27]),Int32Array.from([9396,28]),Int32Array.from([8579,29]),Int32Array.from([11994,30]),Int32Array.from([11245,31])];class J{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const i of n)e+=i.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class N{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ee{constructor(e,n,...i){this.versionNumber=e,this.alignmentPatternCenters=n,this.ecBlocks=i;let s=0;const a=i[0].getECCodewordsPerBlock(),l=i[0].getECBlocks();for(const d of l)s+=d.getCount()*(d.getDataCodewords()+a);this.totalCodewords=s}getVersionNumber(){return this.versionNumber}getAlignmentPatternCenters(){return this.alignmentPatternCenters}getTotalCodewords(){return this.totalCodewords}getDimensionForVersion(){return 17+4*this.versionNumber}getECBlocksForLevel(e){return this.ecBlocks[e.getValue()]}static getProvisionalVersionForDimension(e){if(e%4!==1)throw new V;try{return this.getVersionForNumber((e-17)/4)}catch{throw new V}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return Ee.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<Ee.VERSION_DECODE_INFO.length;s++){const a=Ee.VERSION_DECODE_INFO[s];if(a===e)return Ee.getVersionForNumber(s+7);const l=jt.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?Ee.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new q(e);n.setRegion(0,0,9,9),n.setRegion(e-8,0,8,9),n.setRegion(0,e-8,9,8);const i=this.alignmentPatternCenters.length;for(let s=0;s<i;s++){const a=this.alignmentPatternCenters[s]-2;for(let l=0;l<i;l++)s===0&&(l===0||l===i-1)||s===i-1&&l===0||n.setRegion(this.alignmentPatternCenters[l]-2,a,5,5)}return n.setRegion(6,9,1,e-17),n.setRegion(9,6,e-17,1),this.versionNumber>6&&(n.setRegion(e-11,0,3,6),n.setRegion(0,e-11,6,3)),n}toString(){return""+this.versionNumber}}Ee.VERSION_DECODE_INFO=Int32Array.from([31892,34236,39577,42195,48118,51042,55367,58893,63784,68472,70749,76311,79154,84390,87683,92361,96236,102084,102881,110507,110734,117786,119615,126325,127568,133589,136944,141498,145311,150283,152622,158308,161089,167017]),Ee.VERSIONS=[new Ee(1,new Int32Array(0),new J(7,new N(1,19)),new J(10,new N(1,16)),new J(13,new N(1,13)),new J(17,new N(1,9))),new Ee(2,Int32Array.from([6,18]),new J(10,new N(1,34)),new J(16,new N(1,28)),new J(22,new N(1,22)),new J(28,new N(1,16))),new Ee(3,Int32Array.from([6,22]),new J(15,new N(1,55)),new J(26,new N(1,44)),new J(18,new N(2,17)),new J(22,new N(2,13))),new Ee(4,Int32Array.from([6,26]),new J(20,new N(1,80)),new J(18,new N(2,32)),new J(26,new N(2,24)),new J(16,new N(4,9))),new Ee(5,Int32Array.from([6,30]),new J(26,new N(1,108)),new J(24,new N(2,43)),new J(18,new N(2,15),new N(2,16)),new J(22,new N(2,11),new N(2,12))),new Ee(6,Int32Array.from([6,34]),new J(18,new N(2,68)),new J(16,new N(4,27)),new J(24,new N(4,19)),new J(28,new N(4,15))),new Ee(7,Int32Array.from([6,22,38]),new J(20,new N(2,78)),new J(18,new N(4,31)),new J(18,new N(2,14),new N(4,15)),new J(26,new N(4,13),new N(1,14))),new Ee(8,Int32Array.from([6,24,42]),new J(24,new N(2,97)),new J(22,new N(2,38),new N(2,39)),new J(22,new N(4,18),new N(2,19)),new J(26,new N(4,14),new N(2,15))),new Ee(9,Int32Array.from([6,26,46]),new J(30,new N(2,116)),new J(22,new N(3,36),new N(2,37)),new J(20,new N(4,16),new N(4,17)),new J(24,new N(4,12),new N(4,13))),new Ee(10,Int32Array.from([6,28,50]),new J(18,new N(2,68),new N(2,69)),new J(26,new N(4,43),new N(1,44)),new J(24,new N(6,19),new N(2,20)),new J(28,new N(6,15),new N(2,16))),new Ee(11,Int32Array.from([6,30,54]),new J(20,new N(4,81)),new J(30,new N(1,50),new N(4,51)),new J(28,new N(4,22),new N(4,23)),new J(24,new N(3,12),new N(8,13))),new Ee(12,Int32Array.from([6,32,58]),new J(24,new N(2,92),new N(2,93)),new J(22,new N(6,36),new N(2,37)),new J(26,new N(4,20),new N(6,21)),new J(28,new N(7,14),new N(4,15))),new Ee(13,Int32Array.from([6,34,62]),new J(26,new N(4,107)),new J(22,new N(8,37),new N(1,38)),new J(24,new N(8,20),new N(4,21)),new J(22,new N(12,11),new N(4,12))),new Ee(14,Int32Array.from([6,26,46,66]),new J(30,new N(3,115),new N(1,116)),new J(24,new N(4,40),new N(5,41)),new J(20,new N(11,16),new N(5,17)),new J(24,new N(11,12),new N(5,13))),new Ee(15,Int32Array.from([6,26,48,70]),new J(22,new N(5,87),new N(1,88)),new J(24,new N(5,41),new N(5,42)),new J(30,new N(5,24),new N(7,25)),new J(24,new N(11,12),new N(7,13))),new Ee(16,Int32Array.from([6,26,50,74]),new J(24,new N(5,98),new N(1,99)),new J(28,new N(7,45),new N(3,46)),new J(24,new N(15,19),new N(2,20)),new J(30,new N(3,15),new N(13,16))),new Ee(17,Int32Array.from([6,30,54,78]),new J(28,new N(1,107),new N(5,108)),new J(28,new N(10,46),new N(1,47)),new J(28,new N(1,22),new N(15,23)),new J(28,new N(2,14),new N(17,15))),new Ee(18,Int32Array.from([6,30,56,82]),new J(30,new N(5,120),new N(1,121)),new J(26,new N(9,43),new N(4,44)),new J(28,new N(17,22),new N(1,23)),new J(28,new N(2,14),new N(19,15))),new Ee(19,Int32Array.from([6,30,58,86]),new J(28,new N(3,113),new N(4,114)),new J(26,new N(3,44),new N(11,45)),new J(26,new N(17,21),new N(4,22)),new J(26,new N(9,13),new N(16,14))),new Ee(20,Int32Array.from([6,34,62,90]),new J(28,new N(3,107),new N(5,108)),new J(26,new N(3,41),new N(13,42)),new J(30,new N(15,24),new N(5,25)),new J(28,new N(15,15),new N(10,16))),new Ee(21,Int32Array.from([6,28,50,72,94]),new J(28,new N(4,116),new N(4,117)),new J(26,new N(17,42)),new J(28,new N(17,22),new N(6,23)),new J(30,new N(19,16),new N(6,17))),new Ee(22,Int32Array.from([6,26,50,74,98]),new J(28,new N(2,111),new N(7,112)),new J(28,new N(17,46)),new J(30,new N(7,24),new N(16,25)),new J(24,new N(34,13))),new Ee(23,Int32Array.from([6,30,54,78,102]),new J(30,new N(4,121),new N(5,122)),new J(28,new N(4,47),new N(14,48)),new J(30,new N(11,24),new N(14,25)),new J(30,new N(16,15),new N(14,16))),new Ee(24,Int32Array.from([6,28,54,80,106]),new J(30,new N(6,117),new N(4,118)),new J(28,new N(6,45),new N(14,46)),new J(30,new N(11,24),new N(16,25)),new J(30,new N(30,16),new N(2,17))),new Ee(25,Int32Array.from([6,32,58,84,110]),new J(26,new N(8,106),new N(4,107)),new J(28,new N(8,47),new N(13,48)),new J(30,new N(7,24),new N(22,25)),new J(30,new N(22,15),new N(13,16))),new Ee(26,Int32Array.from([6,30,58,86,114]),new J(28,new N(10,114),new N(2,115)),new J(28,new N(19,46),new N(4,47)),new J(28,new N(28,22),new N(6,23)),new J(30,new N(33,16),new N(4,17))),new Ee(27,Int32Array.from([6,34,62,90,118]),new J(30,new N(8,122),new N(4,123)),new J(28,new N(22,45),new N(3,46)),new J(30,new N(8,23),new N(26,24)),new J(30,new N(12,15),new N(28,16))),new Ee(28,Int32Array.from([6,26,50,74,98,122]),new J(30,new N(3,117),new N(10,118)),new J(28,new N(3,45),new N(23,46)),new J(30,new N(4,24),new N(31,25)),new J(30,new N(11,15),new N(31,16))),new Ee(29,Int32Array.from([6,30,54,78,102,126]),new J(30,new N(7,116),new N(7,117)),new J(28,new N(21,45),new N(7,46)),new J(30,new N(1,23),new N(37,24)),new J(30,new N(19,15),new N(26,16))),new Ee(30,Int32Array.from([6,26,52,78,104,130]),new J(30,new N(5,115),new N(10,116)),new J(28,new N(19,47),new N(10,48)),new J(30,new N(15,24),new N(25,25)),new J(30,new N(23,15),new N(25,16))),new Ee(31,Int32Array.from([6,30,56,82,108,134]),new J(30,new N(13,115),new N(3,116)),new J(28,new N(2,46),new N(29,47)),new J(30,new N(42,24),new N(1,25)),new J(30,new N(23,15),new N(28,16))),new Ee(32,Int32Array.from([6,34,60,86,112,138]),new J(30,new N(17,115)),new J(28,new N(10,46),new N(23,47)),new J(30,new N(10,24),new N(35,25)),new J(30,new N(19,15),new N(35,16))),new Ee(33,Int32Array.from([6,30,58,86,114,142]),new J(30,new N(17,115),new N(1,116)),new J(28,new N(14,46),new N(21,47)),new J(30,new N(29,24),new N(19,25)),new J(30,new N(11,15),new N(46,16))),new Ee(34,Int32Array.from([6,34,62,90,118,146]),new J(30,new N(13,115),new N(6,116)),new J(28,new N(14,46),new N(23,47)),new J(30,new N(44,24),new N(7,25)),new J(30,new N(59,16),new N(1,17))),new Ee(35,Int32Array.from([6,30,54,78,102,126,150]),new J(30,new N(12,121),new N(7,122)),new J(28,new N(12,47),new N(26,48)),new J(30,new N(39,24),new N(14,25)),new J(30,new N(22,15),new N(41,16))),new Ee(36,Int32Array.from([6,24,50,76,102,128,154]),new J(30,new N(6,121),new N(14,122)),new J(28,new N(6,47),new N(34,48)),new J(30,new N(46,24),new N(10,25)),new J(30,new N(2,15),new N(64,16))),new Ee(37,Int32Array.from([6,28,54,80,106,132,158]),new J(30,new N(17,122),new N(4,123)),new J(28,new N(29,46),new N(14,47)),new J(30,new N(49,24),new N(10,25)),new J(30,new N(24,15),new N(46,16))),new Ee(38,Int32Array.from([6,32,58,84,110,136,162]),new J(30,new N(4,122),new N(18,123)),new J(28,new N(13,46),new N(32,47)),new J(30,new N(48,24),new N(14,25)),new J(30,new N(42,15),new N(32,16))),new Ee(39,Int32Array.from([6,26,54,82,110,138,166]),new J(30,new N(20,117),new N(4,118)),new J(28,new N(40,47),new N(7,48)),new J(30,new N(43,24),new N(22,25)),new J(30,new N(10,15),new N(67,16))),new Ee(40,Int32Array.from([6,30,58,86,114,142,170]),new J(30,new N(19,118),new N(6,119)),new J(28,new N(18,47),new N(31,48)),new J(30,new N(34,24),new N(34,25)),new J(30,new N(20,15),new N(61,16)))];var Mt;(function(b){b[b.DATA_MASK_000=0]="DATA_MASK_000",b[b.DATA_MASK_001=1]="DATA_MASK_001",b[b.DATA_MASK_010=2]="DATA_MASK_010",b[b.DATA_MASK_011=3]="DATA_MASK_011",b[b.DATA_MASK_100=4]="DATA_MASK_100",b[b.DATA_MASK_101=5]="DATA_MASK_101",b[b.DATA_MASK_110=6]="DATA_MASK_110",b[b.DATA_MASK_111=7]="DATA_MASK_111"})(Mt||(Mt={}));class dn{constructor(e,n){this.value=e,this.isMasked=n}unmaskBitMatrix(e,n){for(let i=0;i<n;i++)for(let s=0;s<n;s++)this.isMasked(i,s)&&e.flip(s,i)}}dn.values=new Map([[Mt.DATA_MASK_000,new dn(Mt.DATA_MASK_000,(b,e)=>(b+e&1)===0)],[Mt.DATA_MASK_001,new dn(Mt.DATA_MASK_001,(b,e)=>(b&1)===0)],[Mt.DATA_MASK_010,new dn(Mt.DATA_MASK_010,(b,e)=>e%3===0)],[Mt.DATA_MASK_011,new dn(Mt.DATA_MASK_011,(b,e)=>(b+e)%3===0)],[Mt.DATA_MASK_100,new dn(Mt.DATA_MASK_100,(b,e)=>(Math.floor(b/2)+Math.floor(e/3)&1)===0)],[Mt.DATA_MASK_101,new dn(Mt.DATA_MASK_101,(b,e)=>b*e%6===0)],[Mt.DATA_MASK_110,new dn(Mt.DATA_MASK_110,(b,e)=>b*e%6<3)],[Mt.DATA_MASK_111,new dn(Mt.DATA_MASK_111,(b,e)=>(b+e+b*e%3&1)===0)]]);class id{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new V;this.bitMatrix=e}readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==void 0)return this.parsedFormatInfo;let e=0;for(let a=0;a<6;a++)e=this.copyBit(a,8,e);e=this.copyBit(7,8,e),e=this.copyBit(8,8,e),e=this.copyBit(8,7,e);for(let a=5;a>=0;a--)e=this.copyBit(8,a,e);const n=this.bitMatrix.getHeight();let i=0;const s=n-7;for(let a=n-1;a>=s;a--)i=this.copyBit(8,a,i);for(let a=n-8;a<n;a++)i=this.copyBit(a,8,i);if(this.parsedFormatInfo=jt.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new V}readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==void 0)return this.parsedVersion;const e=this.bitMatrix.getHeight(),n=Math.floor((e-17)/4);if(n<=6)return Ee.getVersionForNumber(n);let i=0;const s=e-11;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(d,l,i);let a=Ee.decodeVersionInformation(i);if(a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;i=0;for(let l=5;l>=0;l--)for(let d=e-9;d>=s;d--)i=this.copyBit(l,d,i);if(a=Ee.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new V}copyBit(e,n,i){return(this.isMirror?this.bitMatrix.get(n,e):this.bitMatrix.get(e,n))?i<<1|1:i<<1}readCodewords(){const e=this.readFormatInformation(),n=this.readVersion(),i=dn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();i.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const d=new Uint8Array(n.getTotalCodewords());let h=0,p=0,y=0;for(let E=s-1;E>0;E-=2){E===6&&E--;for(let I=0;I<s;I++){const R=l?s-1-I:I;for(let F=0;F<2;F++)a.get(E-F,R)||(y++,p<<=1,this.bitMatrix.get(E-F,R)&&(p|=1),y===8&&(d[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new V;return d}remask(){if(this.parsedFormatInfo===null)return;const e=dn.values[this.parsedFormatInfo.getDataMask()],n=this.bitMatrix.getHeight();e.unmaskBitMatrix(this.bitMatrix,n)}setMirror(e){this.parsedVersion=null,this.parsedFormatInfo=null,this.isMirror=e}mirror(){const e=this.bitMatrix;for(let n=0,i=e.getWidth();n<i;n++)for(let s=n+1,a=e.getHeight();s<a;s++)e.get(n,s)!==e.get(s,n)&&(e.flip(s,n),e.flip(n,s))}}class eo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,i){if(e.length!==n.getTotalCodewords())throw new A;const s=n.getECBlocksForLevel(i);let a=0;const l=s.getECBlocks();for(const F of l)a+=F.getCount();const d=new Array(a);let h=0;for(const F of l)for(let U=0;U<F.getCount();U++){const Y=F.getDataCodewords(),re=s.getECCodewordsPerBlock()+Y;d[h++]=new eo(Y,new Uint8Array(re))}const p=d[0].codewords.length;let y=d.length-1;for(;y>=0&&d[y].codewords.length!==p;)y--;y++;const E=p-s.getECCodewordsPerBlock();let I=0;for(let F=0;F<E;F++)for(let U=0;U<h;U++)d[U].codewords[F]=e[I++];for(let F=y;F<h;F++)d[F].codewords[E]=e[I++];const R=d[0].codewords.length;for(let F=E;F<R;F++)for(let U=0;U<h;U++){const Y=U<y?F:F+1;d[U].codewords[Y]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var fn;(function(b){b[b.TERMINATOR=0]="TERMINATOR",b[b.NUMERIC=1]="NUMERIC",b[b.ALPHANUMERIC=2]="ALPHANUMERIC",b[b.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",b[b.BYTE=4]="BYTE",b[b.ECI=5]="ECI",b[b.KANJI=6]="KANJI",b[b.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",b[b.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",b[b.HANZI=9]="HANZI"})(fn||(fn={}));class Se{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,Se.FOR_BITS.set(s,this),Se.FOR_VALUE.set(e,this)}static forBits(e){const n=Se.FOR_BITS.get(e);if(n===void 0)throw new A;return n}getCharacterCountBits(e){const n=e.getVersionNumber();let i;return n<=9?i=0:n<=26?i=1:i=2,this.characterCountBitsForVersions[i]}getValue(){return this.value}getBits(){return this.bits}equals(e){if(!(e instanceof Se))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Se.FOR_BITS=new Map,Se.FOR_VALUE=new Map,Se.TERMINATOR=new Se(fn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Se.NUMERIC=new Se(fn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Se.ALPHANUMERIC=new Se(fn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Se.STRUCTURED_APPEND=new Se(fn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Se.BYTE=new Se(fn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Se.ECI=new Se(fn.ECI,"ECI",Int32Array.from([0,0,0]),7),Se.KANJI=new Se(fn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Se.FNC1_FIRST_POSITION=new Se(fn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Se.FNC1_SECOND_POSITION=new Se(fn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Se.HANZI=new Se(fn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class Ct{static decode(e,n,i,s){const a=new Qi(e);let l=new ae;const d=new Array;let h=-1,p=-1;try{let y=null,E=!1,I;do{if(a.available()<4)I=Se.TERMINATOR;else{const R=a.readBits(4);I=Se.forBits(R)}switch(I){case Se.TERMINATOR:break;case Se.FNC1_FIRST_POSITION:case Se.FNC1_SECOND_POSITION:E=!0;break;case Se.STRUCTURED_APPEND:if(a.available()<16)throw new V;h=a.readBits(8),p=a.readBits(8);break;case Se.ECI:const R=Ct.parseECIValue(a);if(y=M.getCharacterSetECIByValue(R),y===null)throw new V;break;case Se.HANZI:const F=a.readBits(4),U=a.readBits(I.getCharacterCountBits(n));F===Ct.GB2312_SUBSET&&Ct.decodeHanziSegment(a,l,U);break;default:const Y=a.readBits(I.getCharacterCountBits(n));switch(I){case Se.NUMERIC:Ct.decodeNumericSegment(a,l,Y);break;case Se.ALPHANUMERIC:Ct.decodeAlphanumericSegment(a,l,Y,E);break;case Se.BYTE:Ct.decodeByteSegment(a,l,Y,y,d,s);break;case Se.KANJI:Ct.decodeKanjiSegment(a,l,Y);break;default:throw new V}break}}while(I!==Se.TERMINATOR)}catch{throw new V}return new Ne(e,l.toString(),d.length===0?null:d,i===null?null:i.toString(),h,p)}static decodeHanziSegment(e,n,i){if(i*13>e.available())throw new V;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/96<<8&4294967295|l%96;d<959?d+=41377:d+=42657,s[a]=d>>8&255,s[a+1]=d&255,a+=2,i--}try{n.append(ce.decode(s,fe.GB2312))}catch(l){throw new V(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new V;const s=new Uint8Array(2*i);let a=0;for(;i>0;){const l=e.readBits(13);let d=l/192<<8&4294967295|l%192;d<7936?d+=33088:d+=49472,s[a]=d>>8,s[a+1]=d,a+=2,i--}try{n.append(ce.decode(s,fe.SHIFT_JIS))}catch(l){throw new V(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new V;const d=new Uint8Array(i);for(let p=0;p<i;p++)d[p]=e.readBits(8);let h;s===null?h=fe.guessEncoding(d,l):h=s.getName();try{n.append(ce.decode(d,h))}catch(p){throw new V(p)}a.push(d)}static toAlphaNumericChar(e){if(e>=Ct.ALPHANUMERIC_CHARS.length)throw new V;return Ct.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new V;const l=e.readBits(11);n.append(Ct.toAlphaNumericChar(Math.floor(l/45))),n.append(Ct.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new V;n.append(Ct.toAlphaNumericChar(e.readBits(6)))}if(s)for(let l=a;l<n.length();l++)n.charAt(l)==="%"&&(l<n.length()-1&&n.charAt(l+1)==="%"?n.deleteCharAt(l+1):n.setCharAt(l,""))}static decodeNumericSegment(e,n,i){for(;i>=3;){if(e.available()<10)throw new V;const s=e.readBits(10);if(s>=1e3)throw new V;n.append(Ct.toAlphaNumericChar(Math.floor(s/100))),n.append(Ct.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(Ct.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new V;const s=e.readBits(7);if(s>=100)throw new V;n.append(Ct.toAlphaNumericChar(Math.floor(s/10))),n.append(Ct.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new V;const s=e.readBits(4);if(s>=10)throw new V;n.append(Ct.toAlphaNumericChar(s))}}static parseECIValue(e){const n=e.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){const i=e.readBits(8);return(n&63)<<8&4294967295|i}if((n&224)===192){const i=e.readBits(16);return(n&31)<<16&4294967295|i}throw new V}}Ct.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",Ct.GB2312_SUBSET=1;class hs{constructor(e){this.mirrored=e}isMirrored(){return this.mirrored}applyMirroredCorrection(e){if(!this.mirrored||e===null||e.length<3)return;const n=e[0];e[0]=e[2],e[2]=n}}class od{constructor(){this.rsDecoder=new bn(Ue.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(q.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new id(e);let s=null;try{return this.decodeBitMatrixParser(i,n)}catch(a){s=a}try{i.remask(),i.setMirror(!0),i.readVersion(),i.readFormatInformation(),i.mirror();const a=this.decodeBitMatrixParser(i,n);return a.setOther(new hs(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=eo.getDataBlocks(a,i,s);let d=0;for(const y of l)d+=y.getNumDataCodewords();const h=new Uint8Array(d);let p=0;for(const y of l){const E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let R=0;R<I;R++)h[p++]=E[R]}return Ct.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class to extends T{constructor(e,n,i){super(e,n),this.estimatedModuleSize=i}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=(this.getX()+n)/2,a=(this.getY()+e)/2,l=(this.estimatedModuleSize+i)/2;return new to(s,a,l)}}class fi{constructor(e,n,i,s,a,l,d){this.image=e,this.startX=n,this.startY=i,this.width=s,this.height=a,this.moduleSize=l,this.resultPointCallback=d,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}find(){const e=this.startX,n=this.height,i=this.width,s=e+i,a=this.startY+n/2,l=new Int32Array(3),d=this.image;for(let h=0;h<n;h++){const p=a+((h&1)===0?Math.floor((h+1)/2):-Math.floor((h+1)/2));l[0]=0,l[1]=0,l[2]=0;let y=e;for(;y<s&&!d.get(y,p);)y++;let E=0;for(;y<s;){if(d.get(y,p))if(E===1)l[1]++;else if(E===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,y);if(I!==null)return I}l[0]=l[2],l[1]=1,l[2]=0,E=1}else l[++E]++;else E===1&&E++,l[E]++;y++}if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,s);if(I!==null)return I}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new D}static centerFromEnd(e,n){return n-e[2]-e[1]/2}foundPatternCross(e){const n=this.moduleSize,i=n/2;for(let s=0;s<3;s++)if(Math.abs(n-e[s])>=i)return!1;return!0}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.crossCheckStateCount;d[0]=0,d[1]=0,d[2]=0;let h=e;for(;h>=0&&a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&!a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h)&&d[1]<=i;)d[1]++,h++;if(h===l||d[1]>i)return NaN;for(;h<l&&!a.get(n,h)&&d[2]<=i;)d[2]++,h++;if(d[2]>i)return NaN;const p=d[0]+d[1]+d[2];return 5*Math.abs(p-s)>=2*s?NaN:this.foundPatternCross(d)?fi.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i){const s=e[0]+e[1]+e[2],a=fi.centerFromEnd(e,i),l=this.crossCheckVertical(n,a,2*e[1],s);if(!isNaN(l)){const d=(e[0]+e[1]+e[2])/3;for(const p of this.possibleCenters)if(p.aboutEquals(d,l,a))return p.combineEstimate(l,a,d);const h=new to(a,l,d);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class no extends T{constructor(e,n,i,s){super(e,n),this.estimatedModuleSize=i,this.count=s,s===void 0&&(this.count=1)}getEstimatedModuleSize(){return this.estimatedModuleSize}getCount(){return this.count}aboutEquals(e,n,i){if(Math.abs(n-this.getY())<=e&&Math.abs(i-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,i){const s=this.count+1,a=(this.count*this.getX()+n)/s,l=(this.count*this.getY()+e)/s,d=(this.count*this.estimatedModuleSize+i)/s;return new no(a,l,d,s)}}class sd{constructor(e){this.bottomLeft=e[0],this.topLeft=e[1],this.topRight=e[2]}getBottomLeft(){return this.bottomLeft}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}}class Dt{constructor(e,n){this.image=e,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}getImage(){return this.image}getPossibleCenters(){return this.possibleCenters}find(e){const n=e!=null&&e.get(H.TRY_HARDER)!==void 0,i=e!=null&&e.get(H.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Dt.MAX_MODULES));(d<Dt.MIN_SKIP||n)&&(d=Dt.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let E=d-1;E<a&&!h;E+=d){p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0;let I=0;for(let R=0;R<l;R++)if(s.get(R,E))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(Dt.foundPatternCross(p)){if(this.handlePossibleCenter(p,E,R,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const U=this.findRowSkip();U>p[2]&&(E+=U-p[2]-d,R=l-1)}else{p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;continue}I=0,p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0}else p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;else p[++I]++;else p[I]++;Dt.foundPatternCross(p)&&this.handlePossibleCenter(p,E,l,i)===!0&&(d=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return T.orderBestPatterns(y),new sd(y)}static centerFromEnd(e,n){return n-e[4]-e[3]-e[2]/2}static foundPatternCross(e){let n=0;for(let a=0;a<5;a++){const l=e[a];if(l===0)return!1;n+=l}if(n<7)return!1;const i=n/7,s=i/2;return Math.abs(i-e[0])<s&&Math.abs(i-e[1])<s&&Math.abs(3*i-e[2])<3*s&&Math.abs(i-e[3])<s&&Math.abs(i-e[4])<s}getCrossCheckStateCount(){const e=this.crossCheckStateCount;return e[0]=0,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e}crossCheckDiagonal(e,n,i,s){const a=this.getCrossCheckStateCount();let l=0;const d=this.image;for(;e>=l&&n>=l&&d.get(n-l,e-l);)a[2]++,l++;if(e<l||n<l)return!1;for(;e>=l&&n>=l&&!d.get(n-l,e-l)&&a[1]<=i;)a[1]++,l++;if(e<l||n<l||a[1]>i)return!1;for(;e>=l&&n>=l&&d.get(n-l,e-l)&&a[0]<=i;)a[0]++,l++;if(a[0]>i)return!1;const h=d.getHeight(),p=d.getWidth();for(l=1;e+l<h&&n+l<p&&d.get(n+l,e+l);)a[2]++,l++;if(e+l>=h||n+l>=p)return!1;for(;e+l<h&&n+l<p&&!d.get(n+l,e+l)&&a[3]<i;)a[3]++,l++;if(e+l>=h||n+l>=p||a[3]>=i)return!1;for(;e+l<h&&n+l<p&&d.get(n+l,e+l)&&a[4]<i;)a[4]++,l++;if(a[4]>=i)return!1;const y=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(y-s)<2*s&&Dt.foundPatternCross(a)}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(n,h)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=2*s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}crossCheckHorizontal(e,n,i,s){const a=this.image,l=a.getWidth(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(h,n)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(h,n);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(h,n)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Dt.centerFromEnd(e,i),d=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(d)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(d),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(d),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const y=this.possibleCenters;for(let E=0,I=y.length;E<I;E++){const R=y[E];if(R.aboutEquals(h,d,l)){y[E]=R.combineEstimate(d,l,h),p=!0;break}}if(!p){const E=new no(l,d,h);y.push(E),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(E)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const i of this.possibleCenters)if(i.getCount()>=Dt.CENTER_QUORUM)if(n==null)n=i;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-i.getX())-Math.abs(n.getY()-i.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const i=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=Dt.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/i;let a=0;for(const l of this.possibleCenters)a+=Math.abs(l.getEstimatedModuleSize()-s);return a<=.05*n}selectBestPatterns(){const e=this.possibleCenters.length;if(e<3)throw new D;const n=this.possibleCenters;let i;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const p=h.getEstimatedModuleSize();s+=p,a+=p*p}i=s/e;let l=Math.sqrt(a/e-i*i);n.sort((h,p)=>{const y=Math.abs(p.getEstimatedModuleSize()-i),E=Math.abs(h.getEstimatedModuleSize()-i);return y<E?-1:y>E?1:0});const d=Math.max(.2*i,l);for(let h=0;h<n.length&&n.length>3;h++){const p=n[h];Math.abs(p.getEstimatedModuleSize()-i)>d&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();i=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const d=Math.abs(l.getEstimatedModuleSize()-i),h=Math.abs(a.getEstimatedModuleSize()-i);return d<h?1:d>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}Dt.CENTER_QUORUM=2,Dt.MIN_SKIP=3,Dt.MAX_MODULES=57;class Rr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(H.NEED_RESULT_POINT_CALLBACK);const i=new Dt(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(i)}processFinderPatternInfo(e){const n=e.getTopLeft(),i=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,i,s);if(a<1)throw new D("No pattern found in proccess finder.");const l=Rr.computeDimension(n,i,s,a),d=Ee.getProvisionalVersionForDimension(l),h=d.getDimensionForVersion()-7;let p=null;if(d.getAlignmentPatternCenters().length>0){const R=i.getX()-n.getX()+s.getX(),F=i.getY()-n.getY()+s.getY(),U=1-3/h,Y=Math.floor(n.getX()+U*(R-n.getX())),re=Math.floor(n.getY()+U*(F-n.getY()));for(let me=4;me<=16;me<<=1)try{p=this.findAlignmentInRegion(a,Y,re,me);break}catch(xe){if(!(xe instanceof D))throw xe}}const y=Rr.createTransform(n,i,s,p,l),E=Rr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,i]:I=[s,n,i,p],new pe(E,I)}static createTransform(e,n,i,s,a){const l=a-3.5;let d,h,p,y;return s!==null?(d=s.getX(),h=s.getY(),p=l-3,y=p):(d=n.getX()-e.getX()+i.getX(),h=n.getY()-e.getY()+i.getY(),p=l,y=l),nn.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,p,y,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),d,h,i.getX(),i.getY())}static sampleGrid(e,n,i){return An.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=je.round(T.distance(e,n)/s),l=je.round(T.distance(e,i)/s);let d=Math.floor((a+l)/2)+7;switch(d&3){case 0:d++;break;case 2:d--;break;case 3:throw new D("Dimensions could be not found.")}return d}calculateModuleSize(e,n,i){return(this.calculateModuleSizeOneWay(e,n)+this.calculateModuleSizeOneWay(e,i))/2}calculateModuleSizeOneWay(e,n){const i=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(e.getX()),Math.floor(e.getY()),Math.floor(n.getX()),Math.floor(n.getY())),s=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(n.getX()),Math.floor(n.getY()),Math.floor(e.getX()),Math.floor(e.getY()));return isNaN(i)?s/7:isNaN(s)?i/7:(i+s)/14}sizeOfBlackWhiteBlackRunBothWays(e,n,i,s){let a=this.sizeOfBlackWhiteBlackRun(e,n,i,s),l=1,d=e-(i-e);d<0?(l=e/(e-d),d=0):d>=this.image.getWidth()&&(l=(this.image.getWidth()-1-e)/(d-e),d=this.image.getWidth()-1);let h=Math.floor(n-(s-n)*l);return l=1,h<0?(l=n/(n-h),h=0):h>=this.image.getHeight()&&(l=(this.image.getHeight()-1-n)/(h-n),h=this.image.getHeight()-1),d=Math.floor(e+(d-e)*l),a+=this.sizeOfBlackWhiteBlackRun(e,n,d,h),a-1}sizeOfBlackWhiteBlackRun(e,n,i,s){const a=Math.abs(s-n)>Math.abs(i-e);if(a){let R=e;e=n,n=R,R=i,i=s,s=R}const l=Math.abs(i-e),d=Math.abs(s-n);let h=-l/2;const p=e<i?1:-1,y=n<s?1:-1;let E=0;const I=i+p;for(let R=e,F=n;R!==I;R+=p){const U=a?F:R,Y=a?R:F;if(E===1===this.image.get(U,Y)){if(E===2)return je.distance(R,F,e,n);E++}if(h+=d,h>0){if(F===s)break;F+=y,h-=l}}return E===2?je.distance(i+p,s,e,n):NaN}findAlignmentInRegion(e,n,i,s){const a=Math.floor(s*e),l=Math.max(0,n-a),d=Math.min(this.image.getWidth()-1,n+a);if(d-l<e*3)throw new D("Alignment top exceeds estimated module size.");const h=Math.max(0,i-a),p=Math.min(this.image.getHeight()-1,i+a);if(p-h<e*3)throw new D("Alignment bottom exceeds estimated module size.");return new fi(this.image,l,h,d-l,p-h,e,this.resultPointCallback).find()}}class Zn{constructor(){this.decoder=new od}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(H.PURE_BARCODE)!==void 0){const h=Zn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=Zn.NO_POINTS}else{const h=new Rr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof hs&&i.getOther().applyMirroredCorrection(s);const a=new Me(i.getText(),i.getRawBytes(),void 0,s,ie.QR_CODE,void 0),l=i.getByteSegments();l!==null&&a.putMetadata(Ae.BYTE_SEGMENTS,l);const d=i.getECLevel();return d!==null&&a.putMetadata(Ae.ERROR_CORRECTION_LEVEL,d),i.hasStructuredAppend()&&(a.putMetadata(Ae.STRUCTURED_APPEND_SEQUENCE,i.getStructuredAppendSequenceNumber()),a.putMetadata(Ae.STRUCTURED_APPEND_PARITY,i.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n===null||i===null)throw new D;const s=this.moduleSize(n,e);let a=n[1],l=i[1],d=n[0],h=i[0];if(d>=h||a>=l)throw new D;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new D;const p=Math.round((h-d+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new D;if(y!==p)throw new D;const E=Math.floor(s/2);a+=E,d+=E;const I=d+Math.floor((p-1)*s)-h;if(I>0){if(I>E)throw new D;d-=I}const R=a+Math.floor((y-1)*s)-l;if(R>0){if(R>E)throw new D;a-=R}const F=new q(p,y);for(let U=0;U<y;U++){const Y=a+Math.floor(U*s);for(let re=0;re<p;re++)e.get(d+Math.floor(re*s),Y)&&F.set(re,U)}return F}static moduleSize(e,n){const i=n.getHeight(),s=n.getWidth();let a=e[0],l=e[1],d=!0,h=0;for(;a<s&&l<i;){if(d!==n.get(a,l)){if(++h===5)break;d=!d}a++,l++}if(a===s||l===i)throw new D;return(a-e[0])/7}}Zn.NO_POINTS=new Array;class Oe{PDF417Common(){}static getBitCountSum(e){return je.sum(e)}static toIntArray(e){if(e==null||!e.length)return Oe.EMPTY_INT_ARRAY;const n=new Int32Array(e.length);let i=0;for(const s of e)n[i++]=s;return n}static getCodeword(e){const n=z.binarySearch(Oe.SYMBOL_TABLE,e&262143);return n<0?-1:(Oe.CODEWORD_TABLE[n]-1)%Oe.NUMBER_OF_CODEWORDS}}Oe.NUMBER_OF_CODEWORDS=929,Oe.MAX_CODEWORDS_IN_BARCODE=Oe.NUMBER_OF_CODEWORDS-1,Oe.MIN_ROWS_IN_BARCODE=3,Oe.MAX_ROWS_IN_BARCODE=90,Oe.MODULES_IN_CODEWORD=17,Oe.MODULES_IN_STOP_PATTERN=18,Oe.BARS_IN_MODULE=8,Oe.EMPTY_INT_ARRAY=new Int32Array([]),Oe.SYMBOL_TABLE=Int32Array.from([66142,66170,66206,66236,66290,66292,66350,66382,66396,66454,66470,66476,66594,66600,66614,66626,66628,66632,66640,66654,66662,66668,66682,66690,66718,66720,66748,66758,66776,66798,66802,66804,66820,66824,66832,66846,66848,66876,66880,66936,66950,66956,66968,66992,67006,67022,67036,67042,67044,67048,67062,67118,67150,67164,67214,67228,67256,67294,67322,67350,67366,67372,67398,67404,67416,67438,67474,67476,67490,67492,67496,67510,67618,67624,67650,67656,67664,67678,67686,67692,67706,67714,67716,67728,67742,67744,67772,67782,67788,67800,67822,67826,67828,67842,67848,67870,67872,67900,67904,67960,67974,67992,68016,68030,68046,68060,68066,68068,68072,68086,68104,68112,68126,68128,68156,68160,68216,68336,68358,68364,68376,68400,68414,68448,68476,68494,68508,68536,68546,68548,68552,68560,68574,68582,68588,68654,68686,68700,68706,68708,68712,68726,68750,68764,68792,68802,68804,68808,68816,68830,68838,68844,68858,68878,68892,68920,68976,68990,68994,68996,69e3,69008,69022,69024,69052,69062,69068,69080,69102,69106,69108,69142,69158,69164,69190,69208,69230,69254,69260,69272,69296,69310,69326,69340,69386,69394,69396,69410,69416,69430,69442,69444,69448,69456,69470,69478,69484,69554,69556,69666,69672,69698,69704,69712,69726,69754,69762,69764,69776,69790,69792,69820,69830,69836,69848,69870,69874,69876,69890,69918,69920,69948,69952,70008,70022,70040,70064,70078,70094,70108,70114,70116,70120,70134,70152,70174,70176,70264,70384,70412,70448,70462,70496,70524,70542,70556,70584,70594,70600,70608,70622,70630,70636,70664,70672,70686,70688,70716,70720,70776,70896,71136,71180,71192,71216,71230,71264,71292,71360,71416,71452,71480,71536,71550,71554,71556,71560,71568,71582,71584,71612,71622,71628,71640,71662,71726,71732,71758,71772,71778,71780,71784,71798,71822,71836,71864,71874,71880,71888,71902,71910,71916,71930,71950,71964,71992,72048,72062,72066,72068,72080,72094,72096,72124,72134,72140,72152,72174,72178,72180,72206,72220,72248,72304,72318,72416,72444,72456,72464,72478,72480,72508,72512,72568,72588,72600,72624,72638,72654,72668,72674,72676,72680,72694,72726,72742,72748,72774,72780,72792,72814,72838,72856,72880,72894,72910,72924,72930,72932,72936,72950,72966,72972,72984,73008,73022,73056,73084,73102,73116,73144,73156,73160,73168,73182,73190,73196,73210,73226,73234,73236,73250,73252,73256,73270,73282,73284,73296,73310,73318,73324,73346,73348,73352,73360,73374,73376,73404,73414,73420,73432,73454,73498,73518,73522,73524,73550,73564,73570,73572,73576,73590,73800,73822,73858,73860,73872,73886,73888,73916,73944,73970,73972,73992,74014,74016,74044,74048,74104,74118,74136,74160,74174,74210,74212,74216,74230,74244,74256,74270,74272,74360,74480,74502,74508,74544,74558,74592,74620,74638,74652,74680,74690,74696,74704,74726,74732,74782,74784,74812,74992,75232,75288,75326,75360,75388,75456,75512,75576,75632,75646,75650,75652,75664,75678,75680,75708,75718,75724,75736,75758,75808,75836,75840,75896,76016,76256,76736,76824,76848,76862,76896,76924,76992,77048,77296,77340,77368,77424,77438,77536,77564,77572,77576,77584,77600,77628,77632,77688,77702,77708,77720,77744,77758,77774,77788,77870,77902,77916,77922,77928,77966,77980,78008,78018,78024,78032,78046,78060,78074,78094,78136,78192,78206,78210,78212,78224,78238,78240,78268,78278,78284,78296,78322,78324,78350,78364,78448,78462,78560,78588,78600,78622,78624,78652,78656,78712,78726,78744,78768,78782,78798,78812,78818,78820,78824,78838,78862,78876,78904,78960,78974,79072,79100,79296,79352,79368,79376,79390,79392,79420,79424,79480,79600,79628,79640,79664,79678,79712,79740,79772,79800,79810,79812,79816,79824,79838,79846,79852,79894,79910,79916,79942,79948,79960,79982,79988,80006,80024,80048,80062,80078,80092,80098,80100,80104,80134,80140,80176,80190,80224,80252,80270,80284,80312,80328,80336,80350,80358,80364,80378,80390,80396,80408,80432,80446,80480,80508,80576,80632,80654,80668,80696,80752,80766,80776,80784,80798,80800,80828,80844,80856,80878,80882,80884,80914,80916,80930,80932,80936,80950,80962,80968,80976,80990,80998,81004,81026,81028,81040,81054,81056,81084,81094,81100,81112,81134,81154,81156,81160,81168,81182,81184,81212,81216,81272,81286,81292,81304,81328,81342,81358,81372,81380,81384,81398,81434,81454,81458,81460,81486,81500,81506,81508,81512,81526,81550,81564,81592,81602,81604,81608,81616,81630,81638,81644,81702,81708,81722,81734,81740,81752,81774,81778,81780,82050,82078,82080,82108,82180,82184,82192,82206,82208,82236,82240,82296,82316,82328,82352,82366,82402,82404,82408,82440,82448,82462,82464,82492,82496,82552,82672,82694,82700,82712,82736,82750,82784,82812,82830,82882,82884,82888,82896,82918,82924,82952,82960,82974,82976,83004,83008,83064,83184,83424,83468,83480,83504,83518,83552,83580,83648,83704,83740,83768,83824,83838,83842,83844,83848,83856,83872,83900,83910,83916,83928,83950,83984,84e3,84028,84032,84088,84208,84448,84928,85040,85054,85088,85116,85184,85240,85488,85560,85616,85630,85728,85756,85764,85768,85776,85790,85792,85820,85824,85880,85894,85900,85912,85936,85966,85980,86048,86080,86136,86256,86496,86976,88160,88188,88256,88312,88560,89056,89200,89214,89312,89340,89536,89592,89608,89616,89632,89664,89720,89840,89868,89880,89904,89952,89980,89998,90012,90040,90190,90204,90254,90268,90296,90306,90308,90312,90334,90382,90396,90424,90480,90494,90500,90504,90512,90526,90528,90556,90566,90572,90584,90610,90612,90638,90652,90680,90736,90750,90848,90876,90884,90888,90896,90910,90912,90940,90944,91e3,91014,91020,91032,91056,91070,91086,91100,91106,91108,91112,91126,91150,91164,91192,91248,91262,91360,91388,91584,91640,91664,91678,91680,91708,91712,91768,91888,91928,91952,91966,92e3,92028,92046,92060,92088,92098,92100,92104,92112,92126,92134,92140,92188,92216,92272,92384,92412,92608,92664,93168,93200,93214,93216,93244,93248,93304,93424,93664,93720,93744,93758,93792,93820,93888,93944,93980,94008,94064,94078,94084,94088,94096,94110,94112,94140,94150,94156,94168,94246,94252,94278,94284,94296,94318,94342,94348,94360,94384,94398,94414,94428,94440,94470,94476,94488,94512,94526,94560,94588,94606,94620,94648,94658,94660,94664,94672,94686,94694,94700,94714,94726,94732,94744,94768,94782,94816,94844,94912,94968,94990,95004,95032,95088,95102,95112,95120,95134,95136,95164,95180,95192,95214,95218,95220,95244,95256,95280,95294,95328,95356,95424,95480,95728,95758,95772,95800,95856,95870,95968,95996,96008,96016,96030,96032,96060,96064,96120,96152,96176,96190,96220,96226,96228,96232,96290,96292,96296,96310,96322,96324,96328,96336,96350,96358,96364,96386,96388,96392,96400,96414,96416,96444,96454,96460,96472,96494,96498,96500,96514,96516,96520,96528,96542,96544,96572,96576,96632,96646,96652,96664,96688,96702,96718,96732,96738,96740,96744,96758,96772,96776,96784,96798,96800,96828,96832,96888,97008,97030,97036,97048,97072,97086,97120,97148,97166,97180,97208,97220,97224,97232,97246,97254,97260,97326,97330,97332,97358,97372,97378,97380,97384,97398,97422,97436,97464,97474,97476,97480,97488,97502,97510,97516,97550,97564,97592,97648,97666,97668,97672,97680,97694,97696,97724,97734,97740,97752,97774,97830,97836,97850,97862,97868,97880,97902,97906,97908,97926,97932,97944,97968,97998,98012,98018,98020,98024,98038,98618,98674,98676,98838,98854,98874,98892,98904,98926,98930,98932,98968,99006,99042,99044,99048,99062,99166,99194,99246,99286,99350,99366,99372,99386,99398,99416,99438,99442,99444,99462,99504,99518,99534,99548,99554,99556,99560,99574,99590,99596,99608,99632,99646,99680,99708,99726,99740,99768,99778,99780,99784,99792,99806,99814,99820,99834,99858,99860,99874,99880,99894,99906,99920,99934,99962,99970,99972,99976,99984,99998,1e5,100028,100038,100044,100056,100078,100082,100084,100142,100174,100188,100246,100262,100268,100306,100308,100390,100396,100410,100422,100428,100440,100462,100466,100468,100486,100504,100528,100542,100558,100572,100578,100580,100584,100598,100620,100656,100670,100704,100732,100750,100792,100802,100808,100816,100830,100838,100844,100858,100888,100912,100926,100960,100988,101056,101112,101148,101176,101232,101246,101250,101252,101256,101264,101278,101280,101308,101318,101324,101336,101358,101362,101364,101410,101412,101416,101430,101442,101448,101456,101470,101478,101498,101506,101508,101520,101534,101536,101564,101580,101618,101620,101636,101640,101648,101662,101664,101692,101696,101752,101766,101784,101838,101858,101860,101864,101934,101938,101940,101966,101980,101986,101988,101992,102030,102044,102072,102082,102084,102088,102096,102138,102166,102182,102188,102214,102220,102232,102254,102282,102290,102292,102306,102308,102312,102326,102444,102458,102470,102476,102488,102514,102516,102534,102552,102576,102590,102606,102620,102626,102632,102646,102662,102668,102704,102718,102752,102780,102798,102812,102840,102850,102856,102864,102878,102886,102892,102906,102936,102974,103008,103036,103104,103160,103224,103280,103294,103298,103300,103312,103326,103328,103356,103366,103372,103384,103406,103410,103412,103472,103486,103520,103548,103616,103672,103920,103992,104048,104062,104160,104188,104194,104196,104200,104208,104224,104252,104256,104312,104326,104332,104344,104368,104382,104398,104412,104418,104420,104424,104482,104484,104514,104520,104528,104542,104550,104570,104578,104580,104592,104606,104608,104636,104652,104690,104692,104706,104712,104734,104736,104764,104768,104824,104838,104856,104910,104930,104932,104936,104968,104976,104990,104992,105020,105024,105080,105200,105240,105278,105312,105372,105410,105412,105416,105424,105446,105518,105524,105550,105564,105570,105572,105576,105614,105628,105656,105666,105672,105680,105702,105722,105742,105756,105784,105840,105854,105858,105860,105864,105872,105888,105932,105970,105972,106006,106022,106028,106054,106060,106072,106100,106118,106124,106136,106160,106174,106190,106210,106212,106216,106250,106258,106260,106274,106276,106280,106306,106308,106312,106320,106334,106348,106394,106414,106418,106420,106566,106572,106610,106612,106630,106636,106648,106672,106686,106722,106724,106728,106742,106758,106764,106776,106800,106814,106848,106876,106894,106908,106936,106946,106948,106952,106960,106974,106982,106988,107032,107056,107070,107104,107132,107200,107256,107292,107320,107376,107390,107394,107396,107400,107408,107422,107424,107452,107462,107468,107480,107502,107506,107508,107544,107568,107582,107616,107644,107712,107768,108016,108060,108088,108144,108158,108256,108284,108290,108292,108296,108304,108318,108320,108348,108352,108408,108422,108428,108440,108464,108478,108494,108508,108514,108516,108520,108592,108640,108668,108736,108792,109040,109536,109680,109694,109792,109820,110016,110072,110084,110088,110096,110112,110140,110144,110200,110320,110342,110348,110360,110384,110398,110432,110460,110478,110492,110520,110532,110536,110544,110558,110658,110686,110714,110722,110724,110728,110736,110750,110752,110780,110796,110834,110836,110850,110852,110856,110864,110878,110880,110908,110912,110968,110982,111e3,111054,111074,111076,111080,111108,111112,111120,111134,111136,111164,111168,111224,111344,111372,111422,111456,111516,111554,111556,111560,111568,111590,111632,111646,111648,111676,111680,111736,111856,112096,112152,112224,112252,112320,112440,112514,112516,112520,112528,112542,112544,112588,112686,112718,112732,112782,112796,112824,112834,112836,112840,112848,112870,112890,112910,112924,112952,113008,113022,113026,113028,113032,113040,113054,113056,113100,113138,113140,113166,113180,113208,113264,113278,113376,113404,113416,113424,113440,113468,113472,113560,113614,113634,113636,113640,113686,113702,113708,113734,113740,113752,113778,113780,113798,113804,113816,113840,113854,113870,113890,113892,113896,113926,113932,113944,113968,113982,114016,114044,114076,114114,114116,114120,114128,114150,114170,114194,114196,114210,114212,114216,114242,114244,114248,114256,114270,114278,114306,114308,114312,114320,114334,114336,114364,114380,114420,114458,114478,114482,114484,114510,114524,114530,114532,114536,114842,114866,114868,114970,114994,114996,115042,115044,115048,115062,115130,115226,115250,115252,115278,115292,115298,115300,115304,115318,115342,115394,115396,115400,115408,115422,115430,115436,115450,115478,115494,115514,115526,115532,115570,115572,115738,115758,115762,115764,115790,115804,115810,115812,115816,115830,115854,115868,115896,115906,115912,115920,115934,115942,115948,115962,115996,116024,116080,116094,116098,116100,116104,116112,116126,116128,116156,116166,116172,116184,116206,116210,116212,116246,116262,116268,116282,116294,116300,116312,116334,116338,116340,116358,116364,116376,116400,116414,116430,116444,116450,116452,116456,116498,116500,116514,116520,116534,116546,116548,116552,116560,116574,116582,116588,116602,116654,116694,116714,116762,116782,116786,116788,116814,116828,116834,116836,116840,116854,116878,116892,116920,116930,116936,116944,116958,116966,116972,116986,117006,117048,117104,117118,117122,117124,117136,117150,117152,117180,117190,117196,117208,117230,117234,117236,117304,117360,117374,117472,117500,117506,117508,117512,117520,117536,117564,117568,117624,117638,117644,117656,117680,117694,117710,117724,117730,117732,117736,117750,117782,117798,117804,117818,117830,117848,117874,117876,117894,117936,117950,117966,117986,117988,117992,118022,118028,118040,118064,118078,118112,118140,118172,118210,118212,118216,118224,118238,118246,118266,118306,118312,118338,118352,118366,118374,118394,118402,118404,118408,118416,118430,118432,118460,118476,118514,118516,118574,118578,118580,118606,118620,118626,118628,118632,118678,118694,118700,118730,118738,118740,118830,118834,118836,118862,118876,118882,118884,118888,118902,118926,118940,118968,118978,118980,118984,118992,119006,119014,119020,119034,119068,119096,119152,119166,119170,119172,119176,119184,119198,119200,119228,119238,119244,119256,119278,119282,119284,119324,119352,119408,119422,119520,119548,119554,119556,119560,119568,119582,119584,119612,119616,119672,119686,119692,119704,119728,119742,119758,119772,119778,119780,119784,119798,119920,119934,120032,120060,120256,120312,120324,120328,120336,120352,120384,120440,120560,120582,120588,120600,120624,120638,120672,120700,120718,120732,120760,120770,120772,120776,120784,120798,120806,120812,120870,120876,120890,120902,120908,120920,120946,120948,120966,120972,120984,121008,121022,121038,121058,121060,121064,121078,121100,121112,121136,121150,121184,121212,121244,121282,121284,121288,121296,121318,121338,121356,121368,121392,121406,121440,121468,121536,121592,121656,121730,121732,121736,121744,121758,121760,121804,121842,121844,121890,121922,121924,121928,121936,121950,121958,121978,121986,121988,121992,122e3,122014,122016,122044,122060,122098,122100,122116,122120,122128,122142,122144,122172,122176,122232,122246,122264,122318,122338,122340,122344,122414,122418,122420,122446,122460,122466,122468,122472,122510,122524,122552,122562,122564,122568,122576,122598,122618,122646,122662,122668,122694,122700,122712,122738,122740,122762,122770,122772,122786,122788,122792,123018,123026,123028,123042,123044,123048,123062,123098,123146,123154,123156,123170,123172,123176,123190,123202,123204,123208,123216,123238,123244,123258,123290,123314,123316,123402,123410,123412,123426,123428,123432,123446,123458,123464,123472,123486,123494,123500,123514,123522,123524,123528,123536,123552,123580,123590,123596,123608,123630,123634,123636,123674,123698,123700,123740,123746,123748,123752,123834,123914,123922,123924,123938,123944,123958,123970,123976,123984,123998,124006,124012,124026,124034,124036,124048,124062,124064,124092,124102,124108,124120,124142,124146,124148,124162,124164,124168,124176,124190,124192,124220,124224,124280,124294,124300,124312,124336,124350,124366,124380,124386,124388,124392,124406,124442,124462,124466,124468,124494,124508,124514,124520,124558,124572,124600,124610,124612,124616,124624,124646,124666,124694,124710,124716,124730,124742,124748,124760,124786,124788,124818,124820,124834,124836,124840,124854,124946,124948,124962,124964,124968,124982,124994,124996,125e3,125008,125022,125030,125036,125050,125058,125060,125064,125072,125086,125088,125116,125126,125132,125144,125166,125170,125172,125186,125188,125192,125200,125216,125244,125248,125304,125318,125324,125336,125360,125374,125390,125404,125410,125412,125416,125430,125444,125448,125456,125472,125504,125560,125680,125702,125708,125720,125744,125758,125792,125820,125838,125852,125880,125890,125892,125896,125904,125918,125926,125932,125978,125998,126002,126004,126030,126044,126050,126052,126056,126094,126108,126136,126146,126148,126152,126160,126182,126202,126222,126236,126264,126320,126334,126338,126340,126344,126352,126366,126368,126412,126450,126452,126486,126502,126508,126522,126534,126540,126552,126574,126578,126580,126598,126604,126616,126640,126654,126670,126684,126690,126692,126696,126738,126754,126756,126760,126774,126786,126788,126792,126800,126814,126822,126828,126842,126894,126898,126900,126934,127126,127142,127148,127162,127178,127186,127188,127254,127270,127276,127290,127302,127308,127320,127342,127346,127348,127370,127378,127380,127394,127396,127400,127450,127510,127526,127532,127546,127558,127576,127598,127602,127604,127622,127628,127640,127664,127678,127694,127708,127714,127716,127720,127734,127754,127762,127764,127778,127784,127810,127812,127816,127824,127838,127846,127866,127898,127918,127922,127924,128022,128038,128044,128058,128070,128076,128088,128110,128114,128116,128134,128140,128152,128176,128190,128206,128220,128226,128228,128232,128246,128262,128268,128280,128304,128318,128352,128380,128398,128412,128440,128450,128452,128456,128464,128478,128486,128492,128506,128522,128530,128532,128546,128548,128552,128566,128578,128580,128584,128592,128606,128614,128634,128642,128644,128648,128656,128670,128672,128700,128716,128754,128756,128794,128814,128818,128820,128846,128860,128866,128868,128872,128886,128918,128934,128940,128954,128978,128980,129178,129198,129202,129204,129238,129258,129306,129326,129330,129332,129358,129372,129378,129380,129384,129398,129430,129446,129452,129466,129482,129490,129492,129562,129582,129586,129588,129614,129628,129634,129636,129640,129654,129678,129692,129720,129730,129732,129736,129744,129758,129766,129772,129814,129830,129836,129850,129862,129868,129880,129902,129906,129908,129930,129938,129940,129954,129956,129960,129974,130010]),Oe.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2e3,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1e3,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]);class ad{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class $e{static detectMultiple(e,n,i){let s=e.getBlackMatrix(),a=$e.detect(i,s);return a.length||(s=s.clone(),s.rotate180(),a=$e.detect(i,s)),new ad(s,a)}static detect(e,n){const i=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const d=$e.findVertices(n,s,a);if(d[0]==null&&d[3]==null){if(!l)break;l=!1,a=0;for(const h of i)h[1]!=null&&(s=Math.trunc(Math.max(s,h[1].getY()))),h[3]!=null&&(s=Math.max(s,Math.trunc(h[3].getY())));s+=$e.ROW_STEP;continue}if(l=!0,i.push(d),!e)break;d[2]!=null?(a=Math.trunc(d[2].getX()),s=Math.trunc(d[2].getY())):(a=Math.trunc(d[4].getX()),s=Math.trunc(d[4].getY()))}return i}static findVertices(e,n,i){const s=e.getHeight(),a=e.getWidth(),l=new Array(8);return $e.copyToResult(l,$e.findRowsWithPattern(e,s,a,n,i,$e.START_PATTERN),$e.INDEXES_START_PATTERN),l[4]!=null&&(i=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),$e.copyToResult(l,$e.findRowsWithPattern(e,s,a,n,i,$e.STOP_PATTERN),$e.INDEXES_STOP_PATTERN),l}static copyToResult(e,n,i){for(let s=0;s<i.length;s++)e[i[s]]=n[s]}static findRowsWithPattern(e,n,i,s,a,l){const d=new Array(4);let h=!1;const p=new Int32Array(l.length);for(;s<n;s+=$e.ROW_STEP){let E=$e.findGuardPattern(e,a,s,i,!1,l,p);if(E!=null){for(;s>0;){const I=$e.findGuardPattern(e,a,--s,i,!1,l,p);if(I!=null)E=I;else{s++;break}}d[0]=new T(E[0],s),d[1]=new T(E[1],s),h=!0;break}}let y=s+1;if(h){let E=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;y<n;y++){const R=$e.findGuardPattern(e,I[0],y,i,!1,l,p);if(R!=null&&Math.abs(I[0]-R[0])<$e.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<$e.MAX_PATTERN_DRIFT)I=R,E=0;else{if(E>$e.SKIPPED_ROW_COUNT_MAX)break;E++}}y-=E+1,d[2]=new T(I[0],y),d[3]=new T(I[1],y)}return y-s<$e.BARCODE_MIN_HEIGHT&&z.fill(d,null),d}static findGuardPattern(e,n,i,s,a,l,d){z.fillWithin(d,0,d.length,0);let h=n,p=0;for(;e.get(h,i)&&h>0&&p++<$e.MAX_PIXEL_DRIFT;)h--;let y=h,E=0,I=l.length;for(let R=a;y<s;y++)if(e.get(y,i)!==R)d[E]++;else{if(E===I-1){if($e.patternMatchVariance(d,l,$e.MAX_INDIVIDUAL_VARIANCE)<$e.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=d[0]+d[1],B.arraycopy(d,2,d,0,E-1),d[E-1]=0,d[E]=0,E--}else E++;d[E]=1,R=!R}return E===I-1&&$e.patternMatchVariance(d,l,$e.MAX_INDIVIDUAL_VARIANCE)<$e.MAX_AVG_VARIANCE?new Int32Array([h,y-1]):null}static patternMatchVariance(e,n,i){let s=e.length,a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return 1/0;let d=a/l;i*=d;let h=0;for(let p=0;p<s;p++){let y=e[p],E=n[p]*d,I=y>E?y-E:E-y;if(I>i)return 1/0;h+=I}return h/a}}$e.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),$e.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),$e.MAX_AVG_VARIANCE=.42,$e.MAX_INDIVIDUAL_VARIANCE=.8,$e.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),$e.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),$e.MAX_PIXEL_DRIFT=3,$e.MAX_PATTERN_DRIFT=5,$e.SKIPPED_ROW_COUNT_MAX=25,$e.ROW_STEP=5,$e.BARCODE_MIN_HEIGHT=10;class Ft{constructor(e,n){if(n.length===0)throw new A;this.field=e;let i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(i-s),B.arraycopy(n,s,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}getCoefficients(){return this.coefficients}getDegree(){return this.coefficients.length-1}isZero(){return this.coefficients[0]===0}getCoefficient(e){return this.coefficients[this.coefficients.length-1-e]}evaluateAt(e){if(e===0)return this.getCoefficient(0);if(e===1){let s=0;for(let a of this.coefficients)s=this.field.add(s,a);return s}let n=this.coefficients[0],i=this.coefficients.length;for(let s=1;s<i;s++)n=this.field.add(this.field.multiply(e,n),this.coefficients[s]);return n}add(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero())return e;if(e.isZero())return this;let n=this.coefficients,i=e.coefficients;if(n.length>i.length){let l=n;n=i,i=l}let s=new Int32Array(i.length),a=i.length-n.length;B.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=this.field.add(n[l-a],i[l]);return new Ft(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof Ft?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new Ft(this.field,new Int32Array([0]));let n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1);for(let d=0;d<i;d++){let h=n[d];for(let p=0;p<a;p++)l[d+p]=this.field.add(l[d+p],this.field.multiply(h,s[p]))}return new Ft(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let i=0;i<e;i++)n[i]=this.field.subtract(0,this.coefficients[i]);return new Ft(this.field,n)}multiplyScalar(e){if(e===0)return new Ft(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,i=new Int32Array(n);for(let s=0;s<n;s++)i[s]=this.field.multiply(this.coefficients[s],e);return new Ft(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new Ft(this.field,new Int32Array([0]));let i=this.coefficients.length,s=new Int32Array(i+e);for(let a=0;a<i;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new Ft(this.field,s)}toString(){let e=new ae;for(let n=this.getDegree();n>=0;n--){let i=this.getCoefficient(n);i!==0&&(i<0?(e.append(" - "),i=-i):e.length()>0&&e.append(" + "),(n===0||i!==1)&&e.append(i),n!==0&&(n===1?e.append("x"):(e.append("x^"),e.append(n))))}return e.toString()}}class ld{add(e,n){return(e+n)%this.modulus}subtract(e,n){return(this.modulus+e-n)%this.modulus}exp(e){return this.expTable[e]}log(e){if(e===0)throw new A;return this.logTable[e]}inverse(e){if(e===0)throw new $t;return this.expTable[this.modulus-this.logTable[e]-1]}multiply(e,n){return e===0||n===0?0:this.expTable[(this.logTable[e]+this.logTable[n])%(this.modulus-1)]}getSize(){return this.modulus}equals(e){return e===this}}class ro extends ld{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let i=1;for(let s=0;s<e;s++)this.expTable[s]=i,i=i*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new Ft(this,new Int32Array([0])),this.one=new Ft(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;let i=new Int32Array(e+1);return i[0]=n,new Ft(this,i)}}ro.PDF417_GF=new ro(Oe.NUMBER_OF_CODEWORDS,3);class ps{constructor(){this.field=ro.PDF417_GF}decode(e,n,i){let s=new Ft(this.field,e),a=new Int32Array(n),l=!1;for(let F=n;F>0;F--){let U=s.evaluateAt(this.field.exp(F));a[n-F]=U,U!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const F of i){let U=this.field.exp(e.length-1-F),Y=new Ft(this.field,new Int32Array([this.field.subtract(0,U),1]));d=d.multiply(Y)}let h=new Ft(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],E=p[1],I=this.findErrorLocations(y),R=this.findErrorMagnitudes(E,y,I);for(let F=0;F<I.length;F++){let U=e.length-1-this.field.log(I[F]);if(U<0)throw O.getChecksumInstance();e[U]=this.field.subtract(e[U],R[F])}return I.length}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){let I=e;e=n,n=I}let s=e,a=n,l=this.field.getZero(),d=this.field.getOne();for(;a.getDegree()>=Math.round(i/2);){let I=s,R=l;if(s=a,l=d,s.isZero())throw O.getChecksumInstance();a=I;let F=this.field.getZero(),U=s.getCoefficient(s.getDegree()),Y=this.field.inverse(U);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let re=a.getDegree()-s.getDegree(),me=this.field.multiply(a.getCoefficient(a.getDegree()),Y);F=F.add(this.field.buildMonomial(re,me)),a=a.subtract(s.multiplyByMonomial(re,me))}d=F.multiply(l).subtract(R).negative()}let h=d.getCoefficient(0);if(h===0)throw O.getChecksumInstance();let p=this.field.inverse(h),y=d.multiply(p),E=a.multiply(p);return[y,E]}findErrorLocations(e){let n=e.getDegree(),i=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(i[s]=this.field.inverse(a),s++);if(s!==n)throw O.getChecksumInstance();return i}findErrorMagnitudes(e,n,i){let s=n.getDegree(),a=new Int32Array(s);for(let p=1;p<=s;p++)a[s-p]=this.field.multiply(p,n.getCoefficient(p));let l=new Ft(this.field,a),d=i.length,h=new Int32Array(d);for(let p=0;p<d;p++){let y=this.field.inverse(i[p]),E=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(E,I)}return h}}class nr{constructor(e,n,i,s,a){e instanceof nr?this.constructor_2(e):this.constructor_1(e,n,i,s,a)}constructor_1(e,n,i,s,a){const l=n==null||i==null,d=s==null||a==null;if(l&&d)throw new D;l?(n=new T(0,s.getY()),i=new T(0,a.getY())):d&&(s=new T(e.getWidth()-1,n.getY()),a=new T(e.getWidth()-1,i.getY())),this.image=e,this.topLeft=n,this.bottomLeft=i,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),i.getX())),this.maxX=Math.trunc(Math.max(s.getX(),a.getX())),this.minY=Math.trunc(Math.min(n.getY(),s.getY())),this.maxY=Math.trunc(Math.max(i.getY(),a.getY()))}constructor_2(e){this.image=e.image,this.topLeft=e.getTopLeft(),this.bottomLeft=e.getBottomLeft(),this.topRight=e.getTopRight(),this.bottomRight=e.getBottomRight(),this.minX=e.getMinX(),this.maxX=e.getMaxX(),this.minY=e.getMinY(),this.maxY=e.getMaxY()}static merge(e,n){return e==null?n:n==null?e:new nr(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,i){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,d=this.bottomRight;if(e>0){let h=i?this.topLeft:this.topRight,p=Math.trunc(h.getY()-e);p<0&&(p=0);let y=new T(h.getX(),p);i?s=y:l=y}if(n>0){let h=i?this.bottomLeft:this.bottomRight,p=Math.trunc(h.getY()+n);p>=this.image.getHeight()&&(p=this.image.getHeight()-1);let y=new T(h.getX(),p);i?a=y:d=y}return new nr(this.image,s,a,l,d)}getMinX(){return this.minX}getMaxX(){return this.maxX}getMinY(){return this.minY}getMaxY(){return this.maxY}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}getBottomLeft(){return this.bottomLeft}getBottomRight(){return this.bottomRight}}class cd{constructor(e,n,i,s){this.columnCount=e,this.errorCorrectionLevel=s,this.rowCountUpperPart=n,this.rowCountLowerPart=i,this.rowCount=n+i}getColumnCount(){return this.columnCount}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getRowCount(){return this.rowCount}getRowCountUpperPart(){return this.rowCountUpperPart}getRowCountLowerPart(){return this.rowCountLowerPart}}class kr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(E){case"s":R=n[i];break;case"c":R=n[i][0];break;case"f":R=parseFloat(n[i]).toFixed(l);break;case"p":R=parseFloat(n[i]).toPrecision(l);break;case"e":R=parseFloat(n[i]).toExponential(l);break;case"x":R=parseInt(n[i]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let F=parseInt(h),U=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+U:U+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=kr.form(e,n)}toString(){return this.buffer}}class Mr{constructor(e){this.boundingBox=new nr(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let i=1;i<Mr.MAX_NEARBY_DISTANCE;i++){let s=this.imageRowToCodewordIndex(e)-i;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+i,s<this.codewords.length&&(n=this.codewords[s],n!=null)))return n}return null}imageRowToCodewordIndex(e){return e-this.boundingBox.getMinY()}setCodeword(e,n){this.codewords[this.imageRowToCodewordIndex(e)]=n}getCodeword(e){return this.codewords[this.imageRowToCodewordIndex(e)]}getBoundingBox(){return this.boundingBox}getCodewords(){return this.codewords}toString(){const e=new kr;let n=0;for(const i of this.codewords){if(i==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,i.getRowNumber(),i.getValue())}return e.toString()}}Mr.MAX_NEARBY_DISTANCE=5;class Dr{constructor(){this.values=new Map}setValue(e){e=Math.trunc(e);let n=this.values.get(e);n==null&&(n=0),n++,this.values.set(e,n)}getValue(){let e=-1,n=new Array;for(const[i,s]of this.values.entries()){const a={getKey:()=>i,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return Oe.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class ms extends Mr{constructor(e,n){super(e),this._isLeft=n}setRowNumbers(){for(let e of this.getCodewords())e?.setRowNumberAsRowIndicatorColumn()}adjustCompleteIndicatorColumnRowNumbers(e){let n=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(n,e);let i=this.getBoundingBox(),s=this._isLeft?i.getTopLeft():i.getTopRight(),a=this._isLeft?i.getBottomLeft():i.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,p=1,y=0;for(let E=l;E<d;E++){if(n[E]==null)continue;let I=n[E],R=I.getRowNumber()-h;if(R===0)y++;else if(R===1)p=Math.max(p,y),y=1,h=I.getRowNumber();else if(R<0||I.getRowNumber()>=e.getRowCount()||R>E)n[E]=null;else{let F;p>2?F=(p-2)*R:F=R;let U=F>=E;for(let Y=1;Y<=F&&!U;Y++)U=n[E-Y]!=null;U?n[E]=null:(h=I.getRowNumber(),y=1)}}}getRowHeights(){let e=this.getBarcodeMetadata();if(e==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(e);let n=new Int32Array(e.getRowCount());for(let i of this.getCodewords())if(i!=null){let s=i.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),i=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(i.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.getCodewords(),h=-1;for(let p=a;p<l;p++){if(d[p]==null)continue;let y=d[p];y.setRowNumberAsRowIndicatorColumn();let E=y.getRowNumber()-h;E===0||(E===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?d[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Dr,i=new Dr,s=new Dr,a=new Dr;for(let d of e){if(d==null)continue;d.setRowNumberAsRowIndicatorColumn();let h=d.getValue()%30,p=d.getRowNumber();switch(this._isLeft||(p+=2),p%3){case 0:i.setValue(h*3+1);break;case 1:a.setValue(h/3),s.setValue(h%3);break;case 2:n.setValue(h+1);break}}if(n.getValue().length===0||i.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||i.getValue()[0]+s.getValue()[0]<Oe.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>Oe.MAX_ROWS_IN_BARCODE)return null;let l=new cd(n.getValue()[0],i.getValue()[0],s.getValue()[0],a.getValue()[0]);return this.removeIncorrectCodewords(e,l),l}removeIncorrectCodewords(e,n){for(let i=0;i<e.length;i++){let s=e[i];if(e[i]==null)continue;let a=s.getValue()%30,l=s.getRowNumber();if(l>n.getRowCount()){e[i]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:a*3+1!==n.getRowCountUpperPart()&&(e[i]=null);break;case 1:(Math.trunc(a/3)!==n.getErrorCorrectionLevel()||a%3!==n.getRowCountLowerPart())&&(e[i]=null);break;case 2:a+1!==n.getColumnCount()&&(e[i]=null);break}}}isLeft(){return this._isLeft}toString(){return"IsLeft: "+this._isLeft+`
|
|
65
|
+
`+super.toString()}}class Pr{constructor(e,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=e,this.barcodeColumnCount=e.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let e=Oe.MAX_CODEWORDS_IN_BARCODE,n;do n=e,e=this.adjustRowNumbersAndGetCount();while(e>0&&e<n);return this.detectionResultColumns}adjustIndicatorColumnRowNumbers(e){e?.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)}adjustRowNumbersAndGetCount(){let e=this.adjustRowNumbersByRow();if(e===0)return 0;for(let n=1;n<this.barcodeColumnCount+1;n++){let i=this.detectionResultColumns[n].getCodewords();for(let s=0;s<i.length;s++)i[s]!=null&&(i[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,i))}return e}adjustRowNumbersByRow(){return this.adjustRowNumbersFromBothRI(),this.adjustRowNumbersFromLRI()+this.adjustRowNumbersFromRRI()}adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)return;let e=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<e.length;i++)if(e[i]!=null&&n[i]!=null&&e[i].getRowNumber()===n[i].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[i];a!=null&&(a.setRowNumber(e[i].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[i]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,i){return i==null||i.hasValidRowNumber()||(i.isValidRowNumber(e)?(i.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,i){if(!this.detectionResultColumns[e-1])return;let s=i[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let d=new Array(14);d[2]=a[n],d[3]=l[n],n>0&&(d[0]=i[n-1],d[4]=a[n-1],d[5]=l[n-1]),n>1&&(d[8]=i[n-2],d[10]=a[n-2],d[11]=l[n-2]),n<i.length-1&&(d[1]=i[n+1],d[6]=a[n+1],d[7]=l[n+1]),n<i.length-2&&(d[9]=i[n+2],d[12]=a[n+2],d[13]=l[n+2]);for(let h of d)if(Pr.adjustRowNumber(s,h))return}static adjustRowNumber(e,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===e.getBucket()?(e.setRowNumber(n.getRowNumber()),!0):!1}getBarcodeColumnCount(){return this.barcodeColumnCount}getBarcodeRowCount(){return this.barcodeMetadata.getRowCount()}getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel()}setBoundingBox(e){this.boundingBox=e}getBoundingBox(){return this.boundingBox}setDetectionResultColumn(e,n){this.detectionResultColumns[e]=n}getDetectionResultColumn(e){return this.detectionResultColumns[e]}toString(){let e=this.detectionResultColumns[0];e==null&&(e=this.detectionResultColumns[this.barcodeColumnCount+1]);let n=new kr;for(let i=0;i<e.getCodewords().length;i++){n.format("CW %3d:",i);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[i];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Br{constructor(e,n,i,s){this.rowNumber=Br.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(i),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Br.BARCODE_ROW_UNKNOWN&&this.bucket===e%3*3}setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))}getWidth(){return this.endX-this.startX}getStartX(){return this.startX}getEndX(){return this.endX}getBucket(){return this.bucket}getValue(){return this.value}getRowNumber(){return this.rowNumber}setRowNumber(e){this.rowNumber=e}toString(){return this.rowNumber+"|"+this.value}}Br.BARCODE_ROW_UNKNOWN=-1;class Kt{static initialize(){for(let e=0;e<Oe.SYMBOL_TABLE.length;e++){let n=Oe.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<Oe.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,Kt.RATIOS_TABLE[e]||(Kt.RATIOS_TABLE[e]=new Array(Oe.BARS_IN_MODULE)),Kt.RATIOS_TABLE[e][Oe.BARS_IN_MODULE-s-1]=Math.fround(a/Oe.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=Kt.getDecodedCodewordValue(Kt.sampleBitCounts(e));return n!==-1?n:Kt.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=je.sum(e),i=new Int32Array(Oe.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Oe.MODULES_IN_CODEWORD;l++){let d=n/(2*Oe.MODULES_IN_CODEWORD)+l*n/Oe.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=Kt.getBitValue(e);return Oe.getCodeword(n)===-1?-1:n}static getBitValue(e){let n=0;for(let i=0;i<e.length;i++)for(let s=0;s<e[i];s++)n=n<<1|(i%2===0?1:0);return Math.trunc(n)}static getClosestDecodedValue(e){let n=je.sum(e),i=new Array(Oe.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=En.MAX_VALUE,a=-1;this.bSymbolTableReady||Kt.initialize();for(let l=0;l<Kt.RATIOS_TABLE.length;l++){let d=0,h=Kt.RATIOS_TABLE[l];for(let p=0;p<Oe.BARS_IN_MODULE;p++){let y=Math.fround(h[p]-i[p]);if(d+=Math.fround(y*y),d>=s)break}d<s&&(s=d,a=Oe.SYMBOL_TABLE[l])}return a}}Kt.bSymbolTableReady=!1,Kt.RATIOS_TABLE=new Array(Oe.SYMBOL_TABLE.length).map(b=>new Array(Oe.BARS_IN_MODULE));class gs{constructor(){this.segmentCount=-1,this.fileSize=-1,this.timestamp=-1,this.checksum=-1}getSegmentIndex(){return this.segmentIndex}setSegmentIndex(e){this.segmentIndex=e}getFileId(){return this.fileId}setFileId(e){this.fileId=e}getOptionalData(){return this.optionalData}setOptionalData(e){this.optionalData=e}isLastSegment(){return this.lastSegment}setLastSegment(e){this.lastSegment=e}getSegmentCount(){return this.segmentCount}setSegmentCount(e){this.segmentCount=e}getSender(){return this.sender||null}setSender(e){this.sender=e}getAddressee(){return this.addressee||null}setAddressee(e){this.addressee=e}getFileName(){return this.fileName}setFileName(e){this.fileName=e}getFileSize(){return this.fileSize}setFileSize(e){this.fileSize=e}getChecksum(){return this.checksum}setChecksum(e){this.checksum=e}getTimestamp(){return this.timestamp}setTimestamp(e){this.timestamp=e}}class xs{static parseLong(e,n=void 0){return parseInt(e,n)}}class ys extends g{}ys.kind="NullPointerException";class ud{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new ys;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new L;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class dd extends g{}class fd extends ud{constructor(e=32){if(super(),this.count=0,e<0)throw new A("Negative initial size: "+e);this.buf=new Uint8Array(e)}ensureCapacity(e){e-this.buf.length>0&&this.grow(e)}grow(e){let i=this.buf.length<<1;if(i-e<0&&(i=e),i<0){if(e<0)throw new dd;i=$.MAX_VALUE}this.buf=z.copyOfUint8Array(this.buf,i)}write(e){this.ensureCapacity(this.count+1),this.buf[this.count]=e,this.count+=1}writeBytesOffset(e,n,i){if(n<0||n>e.length||i<0||n+i-e.length>0)throw new L;this.ensureCapacity(this.count+i),B.arraycopy(e,n,this.buf,this.count,i),this.count+=i}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return z.copyOfUint8Array(this.buf,this.count)}size(){return this.count}toString(e){return e?typeof e=="string"?this.toString_string(e):this.toString_number(e):this.toString_void()}toString_void(){return new String(this.buf).toString()}toString_string(e){return new String(this.buf).toString()}toString_number(e){return new String(this.buf).toString()}close(){}}var it;(function(b){b[b.ALPHA=0]="ALPHA",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.PUNCT=3]="PUNCT",b[b.ALPHA_SHIFT=4]="ALPHA_SHIFT",b[b.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(it||(it={}));function ws(){if(typeof window<"u")return window.BigInt||null;if(typeof Ci<"u")return Ci.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let hi;function jn(b){if(typeof hi>"u"&&(hi=ws()),hi===null)throw new Error("BigInt is not supported!");return hi(b)}function hd(){let b=[];b[0]=jn(1);let e=jn(900);b[1]=e;for(let n=2;n<16;n++)b[n]=b[n-1]*e;return b}class ne{static decode(e,n){let i=new ae(""),s=M.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new gs;for(;a<e[0];){switch(l){case ne.TEXT_COMPACTION_MODE_LATCH:a=ne.textCompaction(e,a,i);break;case ne.BYTE_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH_6:a=ne.byteCompaction(l,e,s,a,i);break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:i.append(e[a++]);break;case ne.NUMERIC_COMPACTION_MODE_LATCH:a=ne.numericCompaction(e,a,i);break;case ne.ECI_CHARSET:M.getCharacterSetECIByValue(e[a++]);break;case ne.ECI_GENERAL_PURPOSE:a+=2;break;case ne.ECI_USER_DEFINED:a++;break;case ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=ne.decodeMacroBlock(e,a,d);break;case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case ne.MACRO_PDF417_TERMINATOR:throw new V;default:a--,a=ne.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw V.getFormatInstance()}if(i.length()===0)throw V.getFormatInstance();let h=new Ne(null,i.toString(),null,n);return h.setOther(d),h}static decodeMacroBlock(e,n,i){if(n+ne.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw V.getFormatInstance();let s=new Int32Array(ne.NUMBER_OF_SEQUENCE_CODEWORDS);for(let d=0;d<ne.NUMBER_OF_SEQUENCE_CODEWORDS;d++,n++)s[d]=e[n];i.setSegmentIndex($.parseInt(ne.decodeBase900toBase10(s,ne.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new ae;n=ne.textCompaction(e,n,a),i.setFileId(a.toString());let l=-1;for(e[n]===ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case ne.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let d=new ae;n=ne.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case ne.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new ae;n=ne.textCompaction(e,n+1,h),i.setSender(h.toString());break;case ne.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new ae;n=ne.textCompaction(e,n+1,p),i.setAddressee(p.toString());break;case ne.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new ae;n=ne.numericCompaction(e,n+1,y),i.setSegmentCount($.parseInt(y.toString()));break;case ne.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let E=new ae;n=ne.numericCompaction(e,n+1,E),i.setTimestamp(xs.parseLong(E.toString()));break;case ne.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new ae;n=ne.numericCompaction(e,n+1,I),i.setChecksum($.parseInt(I.toString()));break;case ne.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let R=new ae;n=ne.numericCompaction(e,n+1,R),i.setFileSize(xs.parseLong(R.toString()));break;default:throw V.getFormatInstance()}break;case ne.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw V.getFormatInstance()}if(l!==-1){let d=n-l;i.isLastSegment()&&d--,i.setOptionalData(z.copyOfRange(e,l,l+d))}return n}static textCompaction(e,n,i){let s=new Int32Array((e[0]-n)*2),a=new Int32Array((e[0]-n)*2),l=0,d=!1;for(;n<e[0]&&!d;){let h=e[n++];if(h<ne.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case ne.TEXT_COMPACTION_MODE_LATCH:s[l++]=ne.TEXT_COMPACTION_MODE_LATCH;break;case ne.BYTE_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH_6:case ne.NUMERIC_COMPACTION_MODE_LATCH:case ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case ne.MACRO_PDF417_TERMINATOR:n--,d=!0;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return ne.decodeTextCompaction(s,a,l,i),n}static decodeTextCompaction(e,n,i,s){let a=it.ALPHA,l=it.ALPHA,d=0;for(;d<i;){let h=e[d],p="";switch(a){case it.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case ne.LL:a=it.LOWER;break;case ne.ML:a=it.MIXED;break;case ne.PS:l=a,a=it.PUNCT_SHIFT;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case ne.AS:l=a,a=it.ALPHA_SHIFT;break;case ne.ML:a=it.MIXED;break;case ne.PS:l=a,a=it.PUNCT_SHIFT;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.MIXED:if(h<ne.PL)p=ne.MIXED_CHARS[h];else switch(h){case ne.PL:a=it.PUNCT;break;case 26:p=" ";break;case ne.LL:a=it.LOWER;break;case ne.AL:a=it.ALPHA;break;case ne.PS:l=a,a=it.PUNCT_SHIFT;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT:if(h<ne.PAL)p=ne.PUNCT_CHARS[h];else switch(h){case ne.PAL:a=it.ALPHA;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT_SHIFT:if(a=l,h<ne.PAL)p=ne.PUNCT_CHARS[h];else switch(h){case ne.PAL:a=it.ALPHA;break;case ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case ne.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break}p!==""&&s.append(p),d++}}static byteCompaction(e,n,i,s,a){let l=new fd,d=0,h=0,p=!1;switch(e){case ne.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),E=n[s++];for(;s<n[0]&&!p;)switch(y[d++]=E,h=900*h+E,E=n[s++],E){case ne.TEXT_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH:case ne.NUMERIC_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH_6:case ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case ne.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(d%5===0&&d>0){for(let I=0;I<6;++I)l.write(Number(jn(h)>>jn(8*(5-I))));h=0,d=0}break}s===n[0]&&E<ne.TEXT_COMPACTION_MODE_LATCH&&(y[d++]=E);for(let I=0;I<d;I++)l.write(y[I]);break;case ne.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<ne.TEXT_COMPACTION_MODE_LATCH)d++,h=900*h+I;else switch(I){case ne.TEXT_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH:case ne.NUMERIC_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH_6:case ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case ne.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(d%5===0&&d>0){for(let R=0;R<6;++R)l.write(Number(jn(h)>>jn(8*(5-R))));h=0,d=0}}break}return a.append(ce.decode(l.toByteArray(),i)),s}static numericCompaction(e,n,i){let s=0,a=!1,l=new Int32Array(ne.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let d=e[n++];if(n===e[0]&&(a=!0),d<ne.TEXT_COMPACTION_MODE_LATCH)l[s]=d,s++;else switch(d){case ne.TEXT_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH:case ne.BYTE_COMPACTION_MODE_LATCH_6:case ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case ne.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%ne.MAX_NUMERIC_CODEWORDS===0||d===ne.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(i.append(ne.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let i=jn(0);for(let a=0;a<n;a++)i+=ne.EXP900[n-a-1]*jn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new V;return s.substring(1)}}ne.TEXT_COMPACTION_MODE_LATCH=900,ne.BYTE_COMPACTION_MODE_LATCH=901,ne.NUMERIC_COMPACTION_MODE_LATCH=902,ne.BYTE_COMPACTION_MODE_LATCH_6=924,ne.ECI_USER_DEFINED=925,ne.ECI_GENERAL_PURPOSE=926,ne.ECI_CHARSET=927,ne.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,ne.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,ne.MACRO_PDF417_TERMINATOR=922,ne.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,ne.MAX_NUMERIC_CODEWORDS=15,ne.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,ne.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,ne.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,ne.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,ne.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,ne.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,ne.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,ne.PL=25,ne.LL=27,ne.AS=27,ne.ML=28,ne.AL=28,ne.PS=29,ne.PAL=29,ne.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
|
|
66
|
+
-.$/"|*()?{}'`,ne.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",ne.EXP900=ws()?hd():[],ne.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ze{constructor(){}static decode(e,n,i,s,a,l,d){let h=new nr(e,n,i,s,a),p=null,y=null,E;for(let F=!0;;F=!1){if(n!=null&&(p=Ze.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(y=Ze.getRowIndicatorColumn(e,h,s,!1,l,d)),E=Ze.merge(p,y),E==null)throw D.getNotFoundInstance();let U=E.getBoundingBox();if(F&&U!=null&&(U.getMinY()<h.getMinY()||U.getMaxY()>h.getMaxY()))h=U;else break}E.setBoundingBox(h);let I=E.getBarcodeColumnCount()+1;E.setDetectionResultColumn(0,p),E.setDetectionResultColumn(I,y);let R=p!=null;for(let F=1;F<=I;F++){let U=R?F:I-F;if(E.getDetectionResultColumn(U)!==void 0)continue;let Y;U===0||U===I?Y=new ms(h,U===0):Y=new Mr(h),E.setDetectionResultColumn(U,Y);let re=-1,me=re;for(let xe=h.getMinY();xe<=h.getMaxY();xe++){if(re=Ze.getStartColumn(E,U,xe,R),re<0||re>h.getMaxX()){if(me===-1)continue;re=me}let ue=Ze.detectCodeword(e,h.getMinX(),h.getMaxX(),R,re,xe,l,d);ue!=null&&(Y.setCodeword(xe,ue),me=re,l=Math.min(l,ue.getWidth()),d=Math.max(d,ue.getWidth()))}}return Ze.createDecoderResult(E)}static merge(e,n){if(e==null&&n==null)return null;let i=Ze.getBarcodeMetadata(e,n);if(i==null)return null;let s=nr.merge(Ze.adjustBoundingBox(e),Ze.adjustBoundingBox(n));return new Pr(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=Ze.getMax(n),s=0;for(let d of n)if(s+=i-d,d>0)break;let a=e.getCodewords();for(let d=0;s>0&&a[d]==null;d++)s--;let l=0;for(let d=n.length-1;d>=0&&(l+=i-n[d],!(n[d]>0));d--);for(let d=a.length-1;l>0&&a[d]==null;d--)l--;return e.getBoundingBox().addMissingRows(s,l,e.isLeft())}static getMax(e){let n=-1;for(let i of e)n=Math.max(n,i);return n}static getBarcodeMetadata(e,n){let i;if(e==null||(i=e.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();let s;return n==null||(s=n.getBarcodeMetadata())==null?i:i.getColumnCount()!==s.getColumnCount()&&i.getErrorCorrectionLevel()!==s.getErrorCorrectionLevel()&&i.getRowCount()!==s.getRowCount()?null:i}static getRowIndicatorColumn(e,n,i,s,a,l){let d=new ms(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(i.getX()));for(let E=Math.trunc(Math.trunc(i.getY()));E<=n.getMaxY()&&E>=n.getMinY();E+=p){let I=Ze.detectCodeword(e,0,e.getWidth(),s,y,E,a,l);I!=null&&(d.setCodeword(E,I),s?y=I.getStartX():y=I.getEndX())}}return d}static adjustCodewordCount(e,n){let i=n[0][1],s=i.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ze.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Oe.MAX_CODEWORDS_IN_BARCODE)throw D.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=Ze.createBarcodeMatrix(e);Ze.adjustCodewordCount(e,n);let i=new Array,s=new Int32Array(e.getBarcodeRowCount()*e.getBarcodeColumnCount()),a=[],l=new Array;for(let h=0;h<e.getBarcodeRowCount();h++)for(let p=0;p<e.getBarcodeColumnCount();p++){let y=n[h][p+1].getValue(),E=h*e.getBarcodeColumnCount()+p;y.length===0?i.push(E):y.length===1?s[E]=y[0]:(l.push(E),a.push(y))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return Ze.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Oe.toIntArray(i),Oe.toIntArray(l),d)}static createDecoderResultFromAmbiguousValues(e,n,i,s,a){let l=new Int32Array(s.length),d=100;for(;d-- >0;){for(let h=0;h<l.length;h++)n[s[h]]=a[h][l[h]];try{return Ze.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof O))throw h}if(l.length===0)throw O.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw O.getChecksumInstance()}throw O.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Dr;let i=0;for(let s of e.getDetectionResultColumns()){if(s!=null){for(let a of s.getCodewords())if(a!=null){let l=a.getRowNumber();if(l>=0){if(l>=n.length)continue;n[l][i].setValue(a.getValue())}}}i++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,i,s){let a=s?1:-1,l=null;if(Ze.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodeword(i)),l!=null)return s?l.getEndX():l.getStartX();if(l=e.getDetectionResultColumn(n).getCodewordNearby(i),l!=null)return s?l.getStartX():l.getEndX();if(Ze.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;Ze.isValidBarcodeColumn(e,n-a);){n-=a;for(let h of e.getDetectionResultColumn(n).getCodewords())if(h!=null)return(s?h.getEndX():h.getStartX())+a*d*(h.getEndX()-h.getStartX());d++}return s?e.getBoundingBox().getMinX():e.getBoundingBox().getMaxX()}static detectCodeword(e,n,i,s,a,l,d,h){a=Ze.adjustCodewordStartColumn(e,n,i,s,a,l);let p=Ze.getModuleBitCount(e,n,i,s,a,l);if(p==null)return null;let y,E=je.sum(p);if(s)y=a+E;else{for(let F=0;F<p.length/2;F++){let U=p[F];p[F]=p[p.length-1-F],p[p.length-1-F]=U}y=a,a=y-E}if(!Ze.checkCodewordSkew(E,d,h))return null;let I=Kt.getDecodedValue(p),R=Oe.getCodeword(I);return R===-1?null:new Br(a,y,Ze.getCodewordBucketNumber(I),R)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),p=0,y=s?1:-1,E=s;for(;(s?d<i:d>=n)&&p<h.length;)e.get(d,l)===E?(h[p]++,d+=y):(p++,E=!E);return p===h.length||d===(s?i:n)&&p===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,i,s,a,l){let d=a,h=s?-1:1;for(let p=0;p<2;p++){for(;(s?d>=n:d<i)&&s===e.get(d,l);){if(Math.abs(a-d)>Ze.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-Ze.CODEWORD_SKEW_SIZE<=e&&e<=i+Ze.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw V.getFormatInstance();let s=1<<n+1,a=Ze.correctErrors(e,i,s);Ze.verifyCodewordCount(e,s);let l=ne.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(i.length),l}static correctErrors(e,n,i){if(n!=null&&n.length>i/2+Ze.MAX_ERRORS||i<0||i>Ze.MAX_EC_CODEWORDS)throw O.getChecksumInstance();return Ze.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw V.getFormatInstance();let i=e[0];if(i>e.length)throw V.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw V.getFormatInstance()}static getBitCountForCodeword(e){let n=new Int32Array(8),i=0,s=n.length-1;for(;!((e&1)!==i&&(i=e&1,s--,s<0));)n[s]++,e>>=1;return n}static getCodewordBucketNumber(e){return e instanceof Int32Array?this.getCodewordBucketNumber_Int32Array(e):this.getCodewordBucketNumber_number(e)}static getCodewordBucketNumber_number(e){return Ze.getCodewordBucketNumber(Ze.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new kr;for(let i=0;i<e.length;i++){n.format("Row %2d: ",i);for(let s=0;s<e[i].length;s++){let a=e[i][s];a.getValue().length===0?n.format(" ",null):n.format("%4d(%2d)",a.getValue()[0],a.getConfidence(a.getValue()[0]))}n.format("%n")}return n.toString()}}Ze.CODEWORD_SKEW_SIZE=2,Ze.MAX_ERRORS=3,Ze.MAX_EC_CODEWORDS=512,Ze.errorCorrection=new ps;class Ut{decode(e,n=null){let i=Ut.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw D.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Ut.decode(e,n,!0)}catch(i){throw i instanceof V||i instanceof O?D.getNotFoundInstance():i}}static decode(e,n,i){const s=new Array,a=$e.detectMultiple(e,n,i);for(const l of a.getPoints()){const d=Ze.decode(a.getBits(),l[4],l[5],l[6],l[7],Ut.getMinCodewordWidth(l),Ut.getMaxCodewordWidth(l)),h=new Me(d.getText(),d.getRawBytes(),void 0,l,ie.PDF_417);h.putMetadata(Ae.ERROR_CORRECTION_LEVEL,d.getECLevel());const p=d.getOther();p!=null&&h.putMetadata(Ae.PDF417_EXTRA_METADATA,p),s.push(h)}return s.map(l=>l)}static getMaxWidth(e,n){return e==null||n==null?0:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMinWidth(e,n){return e==null||n==null?$.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Ut.getMaxWidth(e[0],e[4]),Ut.getMaxWidth(e[6],e[2])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN),Math.max(Ut.getMaxWidth(e[1],e[5]),Ut.getMaxWidth(e[7],e[3])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Ut.getMinWidth(e[0],e[4]),Ut.getMinWidth(e[6],e[2])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN),Math.min(Ut.getMinWidth(e[1],e[5]),Ut.getMinWidth(e[7],e[3])*Oe.MODULES_IN_CODEWORD/Oe.MODULES_IN_STOP_PATTERN)))}reset(){}}class pi extends g{}pi.kind="ReaderException";class _s{constructor(e,n){this.verbose=e===!0,n&&this.setHints(n)}decode(e,n){return n&&this.setHints(n),this.decodeInternal(e)}decodeWithState(e){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(e)}setHints(e){this.hints=e;const n=!c(e)&&e.get(H.TRY_HARDER)===!0,i=c(e)?null:e.get(H.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===ie.UPC_A||l===ie.UPC_E||l===ie.EAN_13||l===ie.EAN_8||l===ie.CODABAR||l===ie.CODE_39||l===ie.CODE_93||l===ie.CODE_128||l===ie.ITF||l===ie.RSS_14||l===ie.RSS_EXPANDED);a&&!n&&s.push(new yr(e,this.verbose)),i.includes(ie.QR_CODE)&&s.push(new Zn),i.includes(ie.DATA_MATRIX)&&s.push(new Vn),i.includes(ie.AZTEC)&&s.push(new pr),i.includes(ie.PDF_417)&&s.push(new Ut),a&&n&&s.push(new yr(e,this.verbose))}s.length===0&&(n||s.push(new yr(e,this.verbose)),s.push(new Zn),s.push(new Vn),s.push(new pr),s.push(new Ut),n&&s.push(new yr(e,this.verbose))),this.readers=s}reset(){if(this.readers!==null)for(const e of this.readers)e.reset()}decodeInternal(e){if(this.readers===null)throw new pi("No readers where selected, nothing can be read.");for(const n of this.readers)try{return n.decode(e,this.hints)}catch(i){if(i instanceof pi)continue}throw new D("No MultiFormat Readers were able to detect the code.")}}class pd extends Ve{constructor(e=null,n=500){const i=new _s;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class md extends Ve{constructor(e=500){super(new Ut,e)}}class gd extends Ve{constructor(e=500){super(new Zn,e)}}var io;(function(b){b[b.ERROR_CORRECTION=0]="ERROR_CORRECTION",b[b.CHARACTER_SET=1]="CHARACTER_SET",b[b.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",b[b.MIN_SIZE=3]="MIN_SIZE",b[b.MAX_SIZE=4]="MAX_SIZE",b[b.MARGIN=5]="MARGIN",b[b.PDF417_COMPACT=6]="PDF417_COMPACT",b[b.PDF417_COMPACTION=7]="PDF417_COMPACTION",b[b.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",b[b.AZTEC_LAYERS=9]="AZTEC_LAYERS",b[b.QR_VERSION=10]="QR_VERSION"})(io||(io={}));var Rt=io;class oo{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new Xe(e,Int32Array.from([1])))}buildGenerator(e){const n=this.cachedGenerators;if(e>=n.length){let i=n[n.length-1];const s=this.field;for(let a=n.length;a<=e;a++){const l=i.multiply(new Xe(s,Int32Array.from([1,s.exp(a-1+s.getGeneratorBase())])));n.push(l),i=l}}return n[e]}encode(e,n){if(n===0)throw new A("No error correction bytes");const i=e.length-n;if(i<=0)throw new A("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(i);B.arraycopy(e,0,a,0,i);let l=new Xe(this.field,a);l=l.multiplyByMonomial(n,1);const h=l.divide(s)[1].getCoefficients(),p=n-h.length;for(let y=0;y<p;y++)e[i+y]=0;B.arraycopy(h,0,e,i+p,h.length)}}class It{constructor(){}static applyMaskPenaltyRule1(e){return It.applyMaskPenaltyRule1Internal(e,!0)+It.applyMaskPenaltyRule1Internal(e,!1)}static applyMaskPenaltyRule2(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a-1;l++){const d=i[l];for(let h=0;h<s-1;h++){const p=d[h];p===d[h+1]&&p===i[l+1][h]&&p===i[l+1][h+1]&&n++}}return It.N2*n}static applyMaskPenaltyRule3(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a;l++)for(let d=0;d<s;d++){const h=i[l];d+6<s&&h[d]===1&&h[d+1]===0&&h[d+2]===1&&h[d+3]===1&&h[d+4]===1&&h[d+5]===0&&h[d+6]===1&&(It.isWhiteHorizontal(h,d-4,d)||It.isWhiteHorizontal(h,d+7,d+11))&&n++,l+6<a&&i[l][d]===1&&i[l+1][d]===0&&i[l+2][d]===1&&i[l+3][d]===1&&i[l+4][d]===1&&i[l+5][d]===0&&i[l+6][d]===1&&(It.isWhiteVertical(i,d,l-4,l)||It.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*It.N3}static isWhiteHorizontal(e,n,i){n=Math.max(n,0),i=Math.min(i,e.length);for(let s=n;s<i;s++)if(e[s]===1)return!1;return!0}static isWhiteVertical(e,n,i,s){i=Math.max(i,0),s=Math.min(s,e.length);for(let a=i;a<s;a++)if(e[a][n]===1)return!1;return!0}static applyMaskPenaltyRule4(e){let n=0;const i=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let h=0;h<a;h++){const p=i[h];for(let y=0;y<s;y++)p[y]===1&&n++}const l=e.getHeight()*e.getWidth();return Math.floor(Math.abs(n*2-l)*10/l)*It.N4}static getDataMaskBit(e,n,i){let s,a;switch(e){case 0:s=i+n&1;break;case 1:s=i&1;break;case 2:s=n%3;break;case 3:s=(i+n)%3;break;case 4:s=Math.floor(i/2)+Math.floor(n/3)&1;break;case 5:a=i*n,s=(a&1)+a%3;break;case 6:a=i*n,s=(a&1)+a%3&1;break;case 7:a=i*n,s=a%3+(i+n&1)&1;break;default:throw new A("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let i=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let d=0;d<s;d++){let h=0,p=-1;for(let y=0;y<a;y++){const E=n?l[d][y]:l[y][d];E===p?h++:(h>=5&&(i+=It.N1+(h-5)),h=1,p=E)}h>=5&&(i+=It.N1+(h-5))}return i}}It.N1=3,It.N2=3,It.N3=40,It.N4=10;class mi{constructor(e,n){this.width=e,this.height=n;const i=new Array(n);for(let s=0;s!==n;s++)i[s]=new Uint8Array(e);this.bytes=i}getHeight(){return this.height}getWidth(){return this.width}get(e,n){return this.bytes[n][e]}getArray(){return this.bytes}setNumber(e,n,i){this.bytes[n][e]=i}setBoolean(e,n,i){this.bytes[n][e]=i?1:0}clear(e){for(const n of this.bytes)z.fill(n,e)}equals(e){if(!(e instanceof mi))return!1;const n=e;if(this.width!==n.width||this.height!==n.height)return!1;for(let i=0,s=this.height;i<s;++i){const a=this.bytes[i],l=n.bytes[i];for(let d=0,h=this.width;d<h;++d)if(a[d]!==l[d])return!1}return!0}toString(){const e=new ae;for(let n=0,i=this.height;n<i;++n){const s=this.bytes[n];for(let a=0,l=this.width;a<l;++a)switch(s[a]){case 0:e.append(" 0");break;case 1:e.append(" 1");break;default:e.append(" ");break}e.append(`
|
|
67
67
|
`)}return e.toString()}}class rr{constructor(){this.maskPattern=-1}getMode(){return this.mode}getECLevel(){return this.ecLevel}getVersion(){return this.version}getMaskPattern(){return this.maskPattern}getMatrix(){return this.matrix}toString(){const e=new ae;return e.append(`<<
|
|
68
68
|
`),e.append(" mode: "),e.append(this.mode?this.mode.toString():"null"),e.append(`
|
|
69
69
|
ecLevel: `),e.append(this.ecLevel?this.ecLevel.toString():"null"),e.append(`
|
|
@@ -73,9 +73,9 @@ ${this.tempPrompt}
|
|
|
73
73
|
`),e.append(this.matrix.toString())):e.append(`
|
|
74
74
|
matrix: null
|
|
75
75
|
`),e.append(`>>
|
|
76
|
-
`),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<rr.NUM_MASK_PATTERNS}}rr.NUM_MASK_PATTERNS=8;class st extends g{}st.kind="WriterException";class Te{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Te.clearMatrix(a),Te.embedBasicPatterns(i,a),Te.embedTypeInfo(n,s,a),Te.maybeEmbedVersionInfo(i,a),Te.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Te.embedPositionDetectionPatternsAndSeparators(n),Te.embedDarkDotAtLeftBottomCorner(n),Te.maybeEmbedPositionAdjustmentPatterns(e,n),Te.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new H;Te.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Te.TYPE_INFO_COORDINATES[a],m=h[0],y=h[1];if(i.setBoolean(m,y,d),a<8){const E=i.getWidth()-a-1;i.setBoolean(E,8,d)}else{const I=i.getHeight()-7+(a-8);i.setBoolean(8,I,d)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const i=new H;Te.makeVersionInfoBits(e,i);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const d=i.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,d),n.setBoolean(n.getHeight()-11+l,a,d)}}static embedDataBits(e,n,i){let s=0,a=-1,l=i.getWidth()-1,d=i.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);d>=0&&d<i.getHeight();){for(let h=0;h<2;++h){const m=l-h;if(!Te.isEmpty(i.get(m,d)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&It.getDataMaskBit(n,m,d)&&(y=!y),i.setBoolean(m,d,y)}d+=a}a=-a,d+=a,l-=2}if(s!==e.getSize())throw new st("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-$.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const i=Te.findMSBSet(n);for(e<<=i-1;Te.findMSBSet(e)>=i;)e^=n<<Te.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!rr.isValidMaskPattern(n))throw new st("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Te.calculateBCHCode(s,Te.TYPE_INFO_POLY);i.appendBits(a,10);const l=new H;if(l.appendBits(Te.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new st("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Te.calculateBCHCode(e.getVersionNumber(),Te.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new st("should not happen but we got: "+n.getSize())}static isEmpty(e){return e===255}static embedTimingPatterns(e){for(let n=8;n<e.getWidth()-8;++n){const i=(n+1)%2;Te.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Te.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new st;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Te.isEmpty(i.get(e+s,n)))throw new st;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Te.isEmpty(i.get(e,n+s)))throw new st;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Te.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,i){for(let s=0;s<7;++s){const a=Te.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Te.POSITION_DETECTION_PATTERN[0].length;Te.embedPositionDetectionPattern(0,0,e),Te.embedPositionDetectionPattern(e.getWidth()-n,0,e),Te.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Te.embedHorizontalSeparationPattern(0,i-1,e),Te.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Te.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Te.embedVerticalSeparationPattern(s,0,e),Te.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Te.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Te.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[i];for(let a=0,l=s.length;a!==l;a++){const d=s[a];if(d>=0)for(let h=0;h!==l;h++){const m=s[h];m>=0&&Te.isEmpty(n.get(m,d))&&Te.embedPositionAdjustmentPattern(m-2,d-2,n)}}}}Te.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),Te.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),Te.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),Te.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),Te.VERSION_INFO_POLY=7973,Te.TYPE_INFO_POLY=1335,Te.TYPE_INFO_MASK_PATTERN=21522;class xd{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class dt{constructor(){}static calculateMaskPenalty(e){return It.applyMaskPenaltyRule1(e)+It.applyMaskPenaltyRule2(e)+It.applyMaskPenaltyRule3(e)+It.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=dt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Rt.CHARACTER_SET)!==void 0;a&&(s=i.get(Rt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new H;if(l===Se.BYTE&&(a||dt.DEFAULT_BYTE_MODE_ENCODING!==s)){const xe=M.getCharacterSetECIByName(s);xe!==void 0&&this.appendECI(xe,d)}this.appendModeInfo(l,d);const h=new H;this.appendBytes(e,l,h,s);let m;if(i!==null&&i.get(Rt.QR_VERSION)!==void 0){const xe=Number.parseInt(i.get(Rt.QR_VERSION).toString(),10);m=Ee.getVersionForNumber(xe);const ue=this.calculateBitsNeeded(l,d,h,m);if(!this.willFit(ue,m,n))throw new st("Data too big for requested version")}else m=this.recommendVersion(n,l,d,h);const y=new H;y.appendBitArray(d);const E=l===Se.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(E,m,l,y),y.appendBitArray(h);const I=m.getECBlocksForLevel(n),R=m.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(R,y);const F=this.interleaveWithECBytes(y,m.getTotalCodewords(),R,I.getNumBlocks()),U=new rr;U.setECLevel(n),U.setMode(l),U.setVersion(m);const q=m.getDimensionForVersion(),ne=new mi(q,q),me=this.chooseMaskPattern(F,n,m,ne);return U.setMaskPattern(me),Te.buildMatrix(F,n,m,me,ne),U.setMatrix(ne),U}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,Ee.getVersionForNumber(1)),l=this.chooseVersion(a,e),d=this.calculateBitsNeeded(n,i,s,l);return this.chooseVersion(d,e)}static calculateBitsNeeded(e,n,i,s){return n.getSize()+e.getCharacterCountBits(s)+i.getSize()}static getAlphanumericCode(e){return e<dt.ALPHANUMERIC_TABLE.length?dt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(M.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Se.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(dt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return Se.BYTE}return s?Se.ALPHANUMERIC:i?Se.NUMERIC:Se.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=le.encode(e,M.SJIS)}catch{return!1}const i=n.length;if(i%2!==0)return!1;for(let s=0;s<i;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,i,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let d=0;d<rr.NUM_MASK_PATTERNS;d++){Te.buildMatrix(e,n,i,d,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=d)}return l}static chooseVersion(e,n){for(let i=1;i<=40;i++){const s=Ee.getVersionForNumber(i);if(dt.willFit(e,s,n))return s}throw new st("Data too big")}static willFit(e,n,i){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(i).getTotalECCodewords(),d=s-l,h=(e+7)/8;return d>=h}static terminateBits(e,n){const i=e*8;if(n.getSize()>i)throw new st("data bits cannot fit in the QR Code"+n.getSize()+" > "+i);for(let l=0;l<4&&n.getSize()<i;++l)n.appendBit(!1);const s=n.getSize()&7;if(s>0)for(let l=s;l<8;l++)n.appendBit(!1);const a=e-n.getSizeInBytes();for(let l=0;l<a;++l)n.appendBits((l&1)===0?236:17,8);if(n.getSize()!==i)throw new st("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new st("Block ID too large");const d=e%i,h=i-d,m=Math.floor(e/i),y=m+1,E=Math.floor(n/i),I=E+1,R=m-E,F=y-I;if(R!==F)throw new st("EC bytes mismatch");if(i!==h+d)throw new st("RS blocks mismatch");if(e!==(E+R)*h+(I+F)*d)throw new st("Total bytes mismatch");s<h?(a[0]=E,l[0]=R):(a[0]=I,l[0]=F)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new st("Number of bits and data bytes does not match");let a=0,l=0,d=0;const h=new Array;for(let y=0;y<s;++y){const E=new Int32Array(1),I=new Int32Array(1);dt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,y,E,I);const R=E[0],F=new Uint8Array(R);e.toBytes(8*a,F,0,R);const U=dt.generateECBytes(F,I[0]);h.push(new xd(F,U)),l=Math.max(l,R),d=Math.max(d,U.length),a+=E[0]}if(i!==a)throw new st("Data bytes does not match offset");const m=new H;for(let y=0;y<l;++y)for(const E of h){const I=E.getDataBytes();y<I.length&&m.appendBits(I[y],8)}for(let y=0;y<d;++y)for(const E of h){const I=E.getErrorCorrectionBytes();y<I.length&&m.appendBits(I[y],8)}if(n!==m.getSizeInBytes())throw new st("Interleaving error: "+n+" and "+m.getSizeInBytes()+" differ.");return m}static generateECBytes(e,n){const i=e.length,s=new Int32Array(i+n);for(let l=0;l<i;l++)s[l]=e[l]&255;new oo(Ue.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[i+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,i,s){const a=i.getCharacterCountBits(n);if(e>=1<<a)throw new st(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case Se.NUMERIC:dt.appendNumericBytes(e,i);break;case Se.ALPHANUMERIC:dt.appendAlphanumericBytes(e,i);break;case Se.BYTE:dt.append8BitBytes(e,i,s);break;case Se.KANJI:dt.appendKanjiBytes(e,i);break;default:throw new st("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=dt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getDigit(e.charAt(s));if(s+2<i){const l=dt.getDigit(e.charAt(s+1)),d=dt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=dt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new st;if(s+1<i){const l=dt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new st;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=le.encode(e,i)}catch(a){throw new st(a)}for(let a=0,l=s.length;a!==l;a++){const d=s[a];n.appendBits(d,8)}}static appendKanjiBytes(e,n){let i;try{i=le.encode(e,M.SJIS)}catch(a){throw new st(a)}const s=i.length;for(let a=0;a<s;a+=2){const l=i[a]&255,d=i[a+1]&255,h=l<<8&4294967295|d;let m=-1;if(h>=33088&&h<=40956?m=h-33088:h>=57408&&h<=60351&&(m=h-49472),m===-1)throw new st("Invalid byte sequence");const y=(m>>8)*192+(m&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Se.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}dt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),dt.DEFAULT_BYTE_MODE_ENCODING=M.UTF8.getName();class ir{write(e,n,i,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||i<0)throw new A("Requested dimensions are too small: "+n+"x"+i);let a=ut.L,l=ir.QUIET_ZONE_SIZE;s!==null&&(s.get(Rt.ERROR_CORRECTION)!==void 0&&(a=ut.fromString(s.get(Rt.ERROR_CORRECTION).toString())),s.get(Rt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Rt.MARGIN).toString(),10)));const d=dt.encode(e,a,s);return this.renderResult(d,n,i,l)}writeToDom(e,n,i,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,i,s,a);e&&e.appendChild(l)}renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,m=d+s*2,y=Math.max(n,h),E=Math.max(i,m),I=Math.min(Math.floor(y/h),Math.floor(E/m)),R=Math.floor((y-l*I)/2),F=Math.floor((E-d*I)/2),U=this.createSVGElement(y,E);for(let q=0,ne=F;q<d;q++,ne+=I)for(let me=0,xe=R;me<l;me++,xe+=I)if(a.get(me,q)===1){const ue=this.createSvgRectElement(xe,ne,I,I);U.appendChild(ue)}return U}createSVGElement(e,n){const i=document.createElementNS(ir.SVG_NS,"svg");return i.setAttributeNS(null,"height",e.toString()),i.setAttributeNS(null,"width",n.toString()),i}createSvgRectElement(e,n,i,s){const a=document.createElementNS(ir.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",i.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}ir.QUIET_ZONE_SIZE=4,ir.SVG_NS="http://www.w3.org/2000/svg";class _r{encode(e,n,i,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==ie.QR_CODE)throw new A("Can only encode QR_CODE, but got "+n);if(i<0||s<0)throw new A(`Requested dimensions are too small: ${i}x${s}`);let l=ut.L,d=_r.QUIET_ZONE_SIZE;a!==null&&(a.get(Rt.ERROR_CORRECTION)!==void 0&&(l=ut.fromString(a.get(Rt.ERROR_CORRECTION).toString())),a.get(Rt.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Rt.MARGIN).toString(),10)));const h=dt.encode(e,l,a);return _r.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,m=d+s*2,y=Math.max(n,h),E=Math.max(i,m),I=Math.min(Math.floor(y/h),Math.floor(E/m)),R=Math.floor((y-l*I)/2),F=Math.floor((E-d*I)/2),U=new X(y,E);for(let q=0,ne=F;q<d;q++,ne+=I)for(let me=0,xe=R;me<l;me++,xe+=I)a.get(me,q)===1&&U.setRegion(xe,ne,I,I);return U}}_r.QUIET_ZONE_SIZE=4;class yd{encode(e,n,i,s,a){let l;switch(n){case ie.QR_CODE:l=new _r;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class Nn extends ee{constructor(e,n,i,s,a,l,d,h){if(super(l,d),this.yuvData=e,this.dataWidth=n,this.dataHeight=i,this.left=s,this.top=a,s+l>n||a+d>i)throw new A("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,d)}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.yuvData,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.yuvData,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;P.arraycopy(this.yuvData,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new Nn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/Nn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/Nn.THUMBNAIL_SCALE_FACTOR,i=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const d=l*e;for(let h=0;h<e;h++){const m=s[a+h*Nn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|m*65793}a+=this.dataWidth*Nn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/Nn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/Nn.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const i=this.yuvData;for(let s=0,a=this.top*this.dataWidth+this.left;s<n;s++,a+=this.dataWidth){const l=a+e/2;for(let d=a,h=a+e-1;d<l;d++,h--){const m=i[d];i[d]=i[h],i[h]=m}}}invert(){return new he(this)}}Nn.THUMBNAIL_SCALE_FACTOR=2;class so extends ee{constructor(e,n,i,s,a,l,d){if(super(n,i),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=d,e.BYTES_PER_ELEMENT===4){const h=n*i,m=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const E=e[y],I=E>>16&255,R=E>>7&510,F=E&255;m[y]=(I+R+F)/4&255}this.luminances=m}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=i),l===void 0&&(this.left=0),d===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+i>this.dataHeight)throw new A("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.luminances,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.luminances,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;P.arraycopy(this.luminances,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new so(this.luminances,i,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new he(this)}}class vs extends M{static forName(e){return this.getCharacterSetECIByName(e)}}class ao{}ao.ISO_8859_1=M.ISO8859_1;class Cs{isCompact(){return this.compact}setCompact(e){this.compact=e}getSize(){return this.size}setSize(e){this.size=e}getLayers(){return this.layers}setLayers(e){this.layers=e}getCodeWords(){return this.codeWords}setCodeWords(e){this.codeWords=e}getMatrix(){return this.matrix}setMatrix(e){this.matrix=e}}class bs{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class wd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class vr extends wd{constructor(e,n,i){super(e),this.value=n,this.bitCount=i}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new vr(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new vr(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+$.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class lo extends vr{constructor(e,n,i){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=i}appendTo(e,n){for(let i=0;i<this.binaryShiftByteCount;i++)(i===0||i===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):i===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+i],8)}addBinaryShift(e,n){return new lo(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function _d(b,e,n){return new lo(b,e,n)}function Lr(b,e,n){return new vr(b,e,n)}const vd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Wn=0,gi=1,hn=2,Es=3,On=4,Cd=new vr(null,0,0),co=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])];function bd(b){for(let e of b)Z.fill(e,-1);return b[Wn][On]=0,b[gi][On]=0,b[gi][Wn]=28,b[Es][On]=0,b[hn][On]=0,b[hn][Wn]=15,b}const As=bd(Z.createInt32Array(6,6));class Rn{constructor(e,n,i,s){this.token=e,this.mode=n,this.binaryShiftByteCount=i,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let i=this.bitCount,s=this.token;if(e!==this.mode){let l=co[this.mode][e];s=Lr(s,l&65535,l>>16),i+=l>>16}let a=e===hn?4:5;return s=Lr(s,n,a),new Rn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===hn?4:5;return i=Lr(i,As[this.mode][e],s),i=Lr(i,n,5),new Rn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===On||this.mode===hn){let d=co[i][Wn];n=Lr(n,d&65535,d>>16),s+=d>>16,i=Wn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Rn(n,i,this.binaryShiftByteCount+1,s+a);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(e+1)),l}endBinaryShift(e){if(this.binaryShiftByteCount===0)return this;let n=this.token;return n=_d(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Rn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(co[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Rn.calculateBinaryShiftCost(e)-Rn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let i=new H;for(const s of n)s.appendTo(i,e);return i}toString(){return fe.format("%s bits=%d bytes=%d",vd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Rn.INITIAL_STATE=new Rn(Cd,Wn,0,0);function Ed(b){const e=fe.getCharCode(" "),n=fe.getCharCode("."),i=fe.getCharCode(",");b[Wn][e]=1;const s=fe.getCharCode("Z"),a=fe.getCharCode("A");for(let I=a;I<=s;I++)b[Wn][I]=I-a+2;b[gi][e]=1;const l=fe.getCharCode("z"),d=fe.getCharCode("a");for(let I=d;I<=l;I++)b[gi][I]=I-d+2;b[hn][e]=1;const h=fe.getCharCode("9"),m=fe.getCharCode("0");for(let I=m;I<=h;I++)b[hn][I]=I-m+2;b[hn][i]=12,b[hn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
|
|
77
|
-
`,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)b[Es][fe.getCharCode(y[I])]=I;const E=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<E.length;I++)fe.getCharCode(E[I])>0&&(b[On][fe.getCharCode(E[I])]=I);return b}const uo=Ed(
|
|
78
|
-
`);let i=bs.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,d=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case fe.getCharCode("\r"):l=d===n?2:0;break;case fe.getCharCode("."):l=d===e?3:0;break;case fe.getCharCode(","):l=d===e?4:0;break;case fe.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Fr.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return bs.min(i,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const i=[];for(let s of e)this.updateStateForChar(s,n,i);return Fr.simplifyStates(i)}updateStateForChar(e,n,i){let s=this.text[n]&255,a=uo[e.getMode()][s]>0,l=null;for(let d=0;d<=On;d++){let h=uo[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===hn){const m=l.latchAndAppend(d,h);i.push(m)}if(!a&&As[e.getMode()][d]>=0){const m=l.shiftAndAppend(d,h);i.push(m)}}}if(e.getBinaryShiftByteCount()>0||uo[e.getMode()][s]===0){let d=e.addBinaryShiftChar(n);i.push(d)}}static updateStateListForPair(e,n,i){const s=[];for(let a of e)this.updateStateForPair(a,n,i,s);return this.simplifyStates(s)}static updateStateForPair(e,n,i,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(On,i)),e.getMode()!==On&&s.push(a.shiftAndAppend(On,i)),i===3||i===4){let l=a.latchAndAppend(hn,16-i).latchAndAppend(hn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const i of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(i)){s=!1;break}i.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(i)}return n}}class Ge{constructor(){}static encodeBytes(e){return Ge.encode(e,Ge.DEFAULT_EC_PERCENT,Ge.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Fr(e).encode(),a=$.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,m,y,E;if(i!==Ge.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?Ge.MAX_NB_BITS_COMPACT:Ge.MAX_NB_BITS))throw new A(fe.format("Illegal value %s for layers",i));m=Ge.totalBitsInLayer(h,d),y=Ge.WORD_SIZE[h];let ue=m-m%y;if(E=Ge.stuffBits(s,y),E.getSize()+a>ue)throw new A("Data to large for user specified layer");if(d&&E.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,E=null;for(let ue=0;;ue++){if(ue>Ge.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(d=ue<=3,h=d?ue+1:ue,m=Ge.totalBitsInLayer(h,d),l>m)continue;(E==null||y!==Ge.WORD_SIZE[h])&&(y=Ge.WORD_SIZE[h],E=Ge.stuffBits(s,y));let We=m-m%y;if(!(d&&E.getSize()>y*64)&&E.getSize()+a<=We)break}}let I=Ge.generateCheckWords(E,m,y),R=E.getSize()/y,F=Ge.generateModeMessage(d,h,R),U=(d?11:14)+h*4,q=new Int32Array(U),ne;if(d){ne=U;for(let ue=0;ue<q.length;ue++)q[ue]=ue}else{ne=U+1+2*$.truncDivision($.truncDivision(U,2)-1,15);let ue=$.truncDivision(U,2),We=$.truncDivision(ne,2);for(let Be=0;Be<ue;Be++){let Qt=Be+$.truncDivision(Be,15);q[ue-Be-1]=We-Qt-1,q[ue+Be]=We+Qt+1}}let me=new X(ne);for(let ue=0,We=0;ue<h;ue++){let Be=(h-ue)*4+(d?9:12);for(let Qt=0;Qt<Be;Qt++){let gn=Qt*2;for(let en=0;en<2;en++)I.get(We+gn+en)&&me.set(q[ue*2+en],q[ue*2+Qt]),I.get(We+Be*2+gn+en)&&me.set(q[ue*2+Qt],q[U-1-ue*2-en]),I.get(We+Be*4+gn+en)&&me.set(q[U-1-ue*2-en],q[U-1-ue*2-Qt]),I.get(We+Be*6+gn+en)&&me.set(q[U-1-ue*2-Qt],q[ue*2+en])}We+=Be*8}if(Ge.drawModeMessage(me,d,ne,F),d)Ge.drawBullsEye(me,$.truncDivision(ne,2),5);else{Ge.drawBullsEye(me,$.truncDivision(ne,2),7);for(let ue=0,We=0;ue<$.truncDivision(U,2)-1;ue+=15,We+=16)for(let Be=$.truncDivision(ne,2)&1;Be<ne;Be+=2)me.set($.truncDivision(ne,2)-We,Be),me.set($.truncDivision(ne,2)+We,Be),me.set(Be,$.truncDivision(ne,2)-We),me.set(Be,$.truncDivision(ne,2)+We)}let xe=new Cs;return xe.setCompact(d),xe.setSize(ne),xe.setLayers(h),xe.setCodeWords(R),xe.setMatrix(me),xe}static drawBullsEye(e,n,i){for(let s=0;s<i;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-i,n-i),e.set(n-i+1,n-i),e.set(n-i,n-i+1),e.set(n+i,n-i),e.set(n+i,n-i+1),e.set(n+i,n+i-1)}static generateModeMessage(e,n,i){let s=new H;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=Ge.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=Ge.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=$.truncDivision(i,2);if(n)for(let l=0;l<7;l++){let d=a-3+l;s.get(l)&&e.set(d,a-5),s.get(l+7)&&e.set(a+5,d),s.get(20-l)&&e.set(d,a+5),s.get(27-l)&&e.set(a-5,d)}else for(let l=0;l<10;l++){let d=a-5+l+$.truncDivision(l,5);s.get(l)&&e.set(d,a-7),s.get(l+10)&&e.set(a+7,d),s.get(29-l)&&e.set(d,a+7),s.get(39-l)&&e.set(a-7,d)}}static generateCheckWords(e,n,i){let s=e.getSize()/i,a=new oo(Ge.getGF(i)),l=$.truncDivision(n,i),d=Ge.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,m=new H;m.appendBits(0,h);for(const y of Array.from(d))m.appendBits(y,i);return m}static bitsToWords(e,n,i){let s=new Int32Array(i),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let d=0;for(let h=0;h<n;h++)d|=e.get(a*n+h)?1<<n-h-1:0;s[a]=d}return s}static getGF(e){switch(e){case 4:return Ue.AZTEC_PARAM;case 6:return Ue.AZTEC_DATA_6;case 8:return Ue.AZTEC_DATA_8;case 10:return Ue.AZTEC_DATA_10;case 12:return Ue.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let i=new H,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let d=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(d|=1<<n-1-h);(d&a)===a?(i.appendBits(d&a,n),l--):(d&a)===0?(i.appendBits(d|1,n),l--):i.appendBits(d,n)}return i}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Ge.DEFAULT_EC_PERCENT=33,Ge.DEFAULT_AZTEC_LAYERS=0,Ge.MAX_NB_BITS=32,Ge.MAX_NB_BITS_COMPACT=4,Ge.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class xi{encode(e,n,i,s){return this.encodeWithHints(e,n,i,s,null)}encodeWithHints(e,n,i,s,a){let l=ao.ISO_8859_1,d=Ge.DEFAULT_EC_PERCENT,h=Ge.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Rt.CHARACTER_SET)&&(l=vs.forName(a.get(Rt.CHARACTER_SET).toString())),a.has(Rt.ERROR_CORRECTION)&&(d=$.parseInt(a.get(Rt.ERROR_CORRECTION).toString())),a.has(Rt.AZTEC_LAYERS)&&(h=$.parseInt(a.get(Rt.AZTEC_LAYERS).toString()))),xi.encodeLayers(e,n,i,s,l,d,h)}static encodeLayers(e,n,i,s,a,l,d){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=Ge.encode(fe.getBytes(e,a),l,d);return xi.renderResult(h,i,s)}static renderResult(e,n,i){let s=e.getMatrix();if(s==null)throw new Vt;let a=s.getWidth(),l=s.getHeight(),d=Math.max(n,a),h=Math.max(i,l),m=Math.min(d/a,h/l),y=(d-a*m)/2,E=(h-l*m)/2,I=new X(d,h);for(let R=0,F=E;R<l;R++,F+=m)for(let U=0,q=y;U<a;U++,q+=m)s.get(U,R)&&I.setRegion(q,F,m,m);return I}}o.AbstractExpandedDecoder=qi,o.ArgumentException=C,o.ArithmeticException=$t,o.AztecCode=Cs,o.AztecCodeReader=pr,o.AztecCodeWriter=xi,o.AztecDecoder=Je,o.AztecDetector=li,o.AztecDetectorResult=_t,o.AztecEncoder=Ge,o.AztecHighLevelEncoder=Fr,o.AztecPoint=Lt,o.BarcodeFormat=ie,o.Binarizer=k,o.BinaryBitmap=B,o.BitArray=H,o.BitMatrix=X,o.BitSource=Qi,o.BrowserAztecCodeReader=Wi,o.BrowserBarcodeReader=td,o.BrowserCodeReader=Ve,o.BrowserDatamatrixCodeReader=rd,o.BrowserMultiFormatReader=pd,o.BrowserPDF417Reader=md,o.BrowserQRCodeReader=gd,o.BrowserQRCodeSvgWriter=ir,o.CharacterSetECI=M,o.ChecksumException=O,o.Code128Reader=oe,o.Code39Reader=Re,o.DataMatrixDecodedBitStreamParser=$n,o.DataMatrixReader=Vn,o.DecodeHintType=j,o.DecoderResult=Ne,o.DefaultGridSampler=ai,o.DetectorResult=pe,o.EAN13Reader=Qn,o.EncodeHintType=Rt,o.Exception=g,o.FormatException=V,o.GenericGF=Ue,o.GenericGFPoly=Xe,o.GlobalHistogramBinarizer=K,o.GridSampler=Un,o.GridSamplerInstance=An,o.HTMLCanvasElementLuminanceSource=ge,o.HybridBinarizer=W,o.ITFReader=qe,o.IllegalArgumentException=A,o.IllegalStateException=Vt,o.InvertedLuminanceSource=he,o.LuminanceSource=ee,o.MathUtils=je,o.MultiFormatOneDReader=yr,o.MultiFormatReader=_s,o.MultiFormatWriter=yd,o.NotFoundException=D,o.OneDReader=Ie,o.PDF417DecodedBitStreamParser=te,o.PDF417DecoderErrorCorrection=ps,o.PDF417Reader=Ut,o.PDF417ResultMetadata=gs,o.PerspectiveTransform=nn,o.PlanarYUVLuminanceSource=Nn,o.QRCodeByteMatrix=mi,o.QRCodeDataMask=dn,o.QRCodeDecodedBitStreamParser=Ct,o.QRCodeDecoderErrorCorrectionLevel=ut,o.QRCodeDecoderFormatInformation=jt,o.QRCodeEncoder=dt,o.QRCodeEncoderQRCode=rr,o.QRCodeMaskUtil=It,o.QRCodeMatrixUtil=Te,o.QRCodeMode=Se,o.QRCodeReader=Zn,o.QRCodeVersion=Ee,o.QRCodeWriter=_r,o.RGBLuminanceSource=so,o.RSS14Reader=At,o.RSSExpandedReader=ce,o.ReaderException=pi,o.ReedSolomonDecoder=bn,o.ReedSolomonEncoder=oo,o.ReedSolomonException=pn,o.Result=Me,o.ResultMetadataType=Ae,o.ResultPoint=T,o.StringUtils=fe,o.UnsupportedOperationException=we,o.VideoInputDevice=de,o.WhiteRectangleDetector=vt,o.WriterException=st,o.ZXingArrays=Z,o.ZXingCharset=vs,o.ZXingInteger=$,o.ZXingStandardCharsets=ao,o.ZXingStringBuilder=ae,o.ZXingStringEncoding=le,o.ZXingSystem=P,o.createAbstractExpandedDecoder=fs,Object.defineProperty(o,"__esModule",{value:!0})}))})(Hr,Hr.exports)),Hr.exports}var ft=mw();const gw=Rc(ft),xw=Od({__proto__:null,default:gw},[ft]);var ul=(function(){function t(r,o,c){if(this.formatMap=new Map([[ve.QR_CODE,ft.BarcodeFormat.QR_CODE],[ve.AZTEC,ft.BarcodeFormat.AZTEC],[ve.CODABAR,ft.BarcodeFormat.CODABAR],[ve.CODE_39,ft.BarcodeFormat.CODE_39],[ve.CODE_93,ft.BarcodeFormat.CODE_93],[ve.CODE_128,ft.BarcodeFormat.CODE_128],[ve.DATA_MATRIX,ft.BarcodeFormat.DATA_MATRIX],[ve.MAXICODE,ft.BarcodeFormat.MAXICODE],[ve.ITF,ft.BarcodeFormat.ITF],[ve.EAN_13,ft.BarcodeFormat.EAN_13],[ve.EAN_8,ft.BarcodeFormat.EAN_8],[ve.PDF_417,ft.BarcodeFormat.PDF_417],[ve.RSS_14,ft.BarcodeFormat.RSS_14],[ve.RSS_EXPANDED,ft.BarcodeFormat.RSS_EXPANDED],[ve.UPC_A,ft.BarcodeFormat.UPC_A],[ve.UPC_E,ft.BarcodeFormat.UPC_E],[ve.UPC_EAN_EXTENSION,ft.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!xw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=o,this.logger=c;var u=this.createZXingFormats(r),f=new Map;f.set(ft.DecodeHintType.POSSIBLE_FORMATS,u),f.set(ft.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var o=this;return new Promise(function(c,u){try{c(o.decode(r))}catch(f){u(f)}})},t.prototype.decode=function(r){var o=new ft.MultiFormatReader(this.verbose,this.hints),c=new ft.HTMLCanvasElementLuminanceSource(r),u=new ft.BinaryBitmap(new ft.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:Gu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return o},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),yw=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(p){p(f)})}return new(o||(o=Promise))(function(f,p){function x(C){try{g(c.next(C))}catch(A){p(A)}}function _(C){try{g(c.throw(C))}catch(A){p(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},ww=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,p;return p={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},dl=(function(){function t(r,o,c){if(this.formatMap=new Map([[ve.QR_CODE,"qr_code"],[ve.AZTEC,"aztec"],[ve.CODABAR,"codabar"],[ve.CODE_39,"code_39"],[ve.CODE_93,"code_93"],[ve.CODE_128,"code_128"],[ve.DATA_MATRIX,"data_matrix"],[ve.ITF,"itf"],[ve.EAN_13,"ean_13"],[ve.EAN_8,"ean_8"],[ve.PDF_417,"pdf417"],[ve.UPC_A,"upc_a"],[ve.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=o,this.logger=c;var u=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(u),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return yw(this,void 0,void 0,function(){var o,c;return ww(this,function(u){switch(u.label){case 0:return[4,this.detector.detect(r)];case 1:if(o=u.sent(),!o||o.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(o),[2,{text:c.rawValue,format:Gu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var o=null,c=0,u=0,f=r;u<f.length;u++){var p=f[u],x=p.boundingBox.width*p.boundingBox.height;x>c&&(c=x,o=p)}if(!o)throw"No largest barcode found";return o},t.prototype.createBarcodeDetectorFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:o}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),fl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(p){p(f)})}return new(o||(o=Promise))(function(f,p){function x(C){try{g(c.next(C))}catch(A){p(A)}}function _(C){try{g(c.throw(C))}catch(A){p(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},hl=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,p;return p={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},_w=(function(){function t(r,o,c,u){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,o&&dl.isSupported()?(this.primaryDecoder=new dl(r,c,u),this.secondaryDecoder=new ul(r,c,u)):this.primaryDecoder=new ul(r,c,u)}return t.prototype.decodeAsync=function(r){return fl(this,void 0,void 0,function(){var o;return hl(this,function(c){switch(c.label){case 0:o=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(o),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return fl(this,void 0,void 0,function(){var o,c;return hl(this,function(u){switch(u.label){case 0:o=performance.now(),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,u.sent()];case 3:if(c=u.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(o),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var o=performance.now()-r;this.executionResults.push(o),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,o=0,c=this.executionResults;o<c.length;o++){var u=c[o];r+=u}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),ss=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),Li=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(p){p(f)})}return new(o||(o=Promise))(function(f,p){function x(C){try{g(c.next(C))}catch(A){p(A)}}function _(C){try{g(c.throw(C))}catch(A){p(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},Fi=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,p;return p={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},qu=(function(){function t(r,o){this.name=r,this.track=o}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var o={};o[this.name]=r;var c={advanced:[o]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var o=r[this.name];return o}return null},t})(),vw=(function(t){ss(r,t);function r(o,c){return t.call(this,o,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(o){var c={};c[this.name]=o;var u={advanced:[c]};return this.track.applyConstraints(u)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var o=this.track.getCapabilities(),c=o[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(qu),Cw=(function(t){ss(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(vw),bw=(function(t){ss(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(qu),Ew=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new Cw(this.track)},t.prototype.torchFeature=function(){return new bw(this.track)},t})(),Aw=(function(){function t(r,o,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=o,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var o=document.createElement("video");return o.style.width="".concat(r,"px"),o.style.display="block",o.muted=!0,o.setAttribute("muted","true"),o.playsInline=!0,o},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var o=function(){var c=r.surface.clientWidth,u=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,u),r.surface.removeEventListener("playing",o)};this.surface.addEventListener("playing",o),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,o,c,u){return Li(this,void 0,void 0,function(){var f,p;return Fi(this,function(x){switch(x.label){case 0:return f=new t(r,o,u),c.aspectRatio?(p={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(p)]):[3,2];case 1:x.sent(),x.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var o=this,c=function(){setTimeout(r,200),o.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return Li(this,void 0,void 0,function(){return Fi(this,function(o){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(o,c){var u=r.mediaStream.getVideoTracks(),f=u.length,p=0;r.mediaStream.getVideoTracks().forEach(function(x){r.mediaStream.removeTrack(x),x.stop(),++p,p>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),o())})})},t.prototype.getCapabilities=function(){return new Ew(this.getFirstTrackOrFail())},t})(),Iw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,o,c){return Li(this,void 0,void 0,function(){return Fi(this,function(u){return[2,Aw.create(r,this.mediaStream,o,c)]})})},t.create=function(r){return Li(this,void 0,void 0,function(){var o,c;return Fi(this,function(u){switch(u.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return o={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(o)];case 1:return c=u.sent(),[2,new t(c)]}})})},t})(),pl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(p){p(f)})}return new(o||(o=Promise))(function(f,p){function x(C){try{g(c.next(C))}catch(A){p(A)}}function _(C){try{g(c.throw(C))}catch(A){p(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},ml=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,p;return p={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Sw=(function(){function t(){}return t.failIfNotSupported=function(){return pl(this,void 0,void 0,function(){return ml(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return pl(this,void 0,void 0,function(){return ml(this,function(o){return[2,Iw.create(r)]})})},t})(),Tw=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(p){p(f)})}return new(o||(o=Promise))(function(f,p){function x(C){try{g(c.next(C))}catch(A){p(A)}}function _(C){try{g(c.throw(C))}catch(A){p(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},Nw=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,p;return p={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(p[Symbol.iterator]=function(){return this}),p;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;p&&(p=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Ow=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Ir.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Ir.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return Tw(this,void 0,void 0,function(){var r,o,c,u,f,p,x;return Nw(this,function(_){switch(_.label){case 0:return r=function(g){for(var C=g.getVideoTracks(),A=0,B=C;A<B.length;A++){var O=B[A];O.enabled=!1,O.stop(),g.removeTrack(O)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return o=_.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=_.sent(),u=[],f=0,p=c;f<p.length;f++)x=p[f],x.kind==="videoinput"&&u.push({id:x.deviceId,label:x.label});return r(o),[2,u]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,o){var c=function(f){for(var p=[],x=0,_=f;x<_.length;x++){var g=_[x];g.kind==="video"&&p.push({id:g.id,label:g.label})}r(p)},u=MediaStreamTrack;u.getSources(c)})},t})(),St;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(St||(St={}));var Rw=(function(){function t(){this.state=St.NOT_STARTED,this.onGoingTransactionNewState=St.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===St.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=St.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===St.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=St.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==St.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case St.UNKNOWN:throw"Transition from unknown is not allowed";case St.NOT_STARTED:this.failIfNewStateIs(r,[St.PAUSED]);break;case St.SCANNING:break;case St.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,o){for(var c=0,u=o;c<u.length;c++){var f=u[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),kw=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===St.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==St.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===St.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===St.PAUSED},t})(),Mw=(function(){function t(){}return t.create=function(){return new kw(new Rw)},t})(),Dw=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),on=(function(t){Dw(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(dw),Pw=(function(){function t(r,o){this.logger=o,this.fps=on.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=on.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Xu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Mn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),gl=(function(){function t(r,o){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof o=="boolean"?this.verbose=o===!0:o&&(c=o,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new hw(this.verbose),this.qrcode=new _w(this.getSupportedFormats(o),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Mw.create()}return t.prototype.start=function(r,o,c,u){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var p;u?p=u:p=this.verbose?this.logger.log:function(){};var x=Pw.create(o,this.logger);this.clearElement();var _=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?_=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=_,C=document.getElementById(this.elementId);C.clientWidth?C.clientWidth:on.DEFAULT_WIDTH,C.style.position="relative",this.shouldScan=!0,this.element=C;var A=this,B=this.stateManagerProxy.startTransition(St.SCANNING);return new Promise(function(O,k){var P=g?x.videoConstraints:A.createVideoConstraints(r);if(!P){B.cancel(),k("videoConstraints should be defined");return}var L={};(!g||x.aspectRatio)&&(L.aspectRatio=x.aspectRatio);var Y={onRenderSurfaceReady:function(Z,$){A.setupUi(Z,$,x),A.isScanning=!0,A.foreverScan(x,c,p)}};Sw.failIfNotSupported().then(function(Z){Z.create(P).then(function($){return $.render(f.element,L,Y).then(function(H){A.renderedCamera=H,B.execute(),O(null)}).catch(function(H){B.cancel(),k(H)})}).catch(function($){B.cancel(),k(Ir.errorGettingUserMedia($))})}).catch(function(Z){B.cancel(),k(Ir.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(St.PAUSED),this.showPausedState(),(Mn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,o=function(){r.stateManagerProxy.directTransition(St.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){o();return}this.renderedCamera.resume(function(){o()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var o=this.stateManagerProxy.startTransition(St.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(on.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},u=this;return this.renderedCamera.close().then(function(){return u.renderedCamera=null,u.element&&(u.element.removeChild(u.canvasElement),u.canvasElement=null),c(),u.qrRegion&&(u.qrRegion=null),u.context&&(u.context=null),o.execute(),u.hidePausedState(),u.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,o){return this.scanFileV2(r,o).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,o){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(Mn(o)&&(o=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(u,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var p=new Image;p.onload=function(){var x=p.width,_=p.height,g=document.getElementById(c.elementId),C=g.clientWidth?g.clientWidth:on.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:_,on.FILE_SCAN_MIN_HEIGHT),B=c.computeCanvasDrawConfig(x,_,C,A);if(o){var O=c.createCanvasElement(C,A,"qr-canvas-visible");O.style.display="inline-block",g.appendChild(O);var k=O.getContext("2d");if(!k)throw"Unable to get 2d context from canvas";k.canvas.width=C,k.canvas.height=A,k.drawImage(p,0,0,x,_,B.x,B.y,B.width,B.height)}var P=on.FILE_SCAN_HIDDEN_CANVAS_PADDING,L=Math.max(p.width,B.width),Y=Math.max(p.height,B.height),Z=L+2*P,$=Y+2*P,H=c.createCanvasElement(Z,$);g.appendChild(H);var re=H.getContext("2d");if(!re)throw"Unable to get 2d context from canvas";re.canvas.width=Z,re.canvas.height=$,re.drawImage(p,0,0,x,_,P,P,L,Y);try{c.qrcode.decodeRobustlyAsync(H).then(function(j){u(ll.createFromQrcodeResult(j))}).catch(f)}catch(j){f("QR code parse error, error = ".concat(j))}},p.onerror=f,p.onabort=f,p.onstalled=f,p.onsuspend=f,p.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Ow.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Xu.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var o=[ve.QR_CODE,ve.AZTEC,ve.CODABAR,ve.CODE_39,ve.CODE_93,ve.CODE_128,ve.DATA_MATRIX,ve.MAXICODE,ve.ITF,ve.EAN_13,ve.EAN_8,ve.PDF_417,ve.RSS_14,ve.RSS_EXPANDED,ve.UPC_A,ve.UPC_E,ve.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return o;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],u=0,f=r.formatsToSupport;u<f.length;u++){var p=f[u];uw(p)?c.push(p):this.logger.warn("Invalid format: ".concat(p," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(Mn(r))return!0;if(!Mn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Mn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Mn(o.useBarCodeDetectorIfSupported)?!0:o.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,o,c){var u=this,f=c.qrbox;this.validateQrboxConfig(f);var p=this.toQrdimensions(r,o,f),x=function(g){if(g<on.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(on.MIN_QR_BOX_SIZE,"px.")},_=function(g){return g>r&&(u.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),g=r),g};x(p.width),x(p.height),p.width=_(p.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,o,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,o)}catch(u){throw new Error("qrbox config was passed as a function but it failed with unknown error"+u)}return c},t.prototype.setupUi=function(r,o,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,o,c);var u=Mn(c.qrbox)?{width:r,height:o}:c.qrbox;this.validateQrboxConfig(u);var f=this.toQrdimensions(r,o,u);f.height>o&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var p=c.isShadedBoxEnabled()&&f.height<=o,x={x:0,y:0,width:r,height:o},_=p?this.getShadedRegionBounds(r,o,f):x,g=this.createCanvasElement(_.width,_.height),C={willReadFrequently:!0},A=g.getContext("2d",C);A.canvas.width=_.width,A.canvas.height=_.height,this.element.append(g),p&&this.possiblyInsertShadingElement(this.element,r,o,f),this.createScannerPausedUiElement(this.element),this.qrRegion=_,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var o=document.createElement("div");o.innerText=Ir.scannerPaused(),o.style.display="none",o.style.position="absolute",o.style.top="0px",o.style.zIndex="1",o.style.background="rgba(9, 9, 9, 0.46)",o.style.color="#FFECEC",o.style.textAlign="center",o.style.width="100%",r.appendChild(o),this.scannerPausedUiElement=o},t.prototype.scanContext=function(r,o){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(u){return r(u.text,ll.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Ir.codeParseError(u);return o(f,fw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,o,c){var u=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),p=f.videoWidth/f.clientWidth,x=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var _=this.qrRegion.width*p,g=this.qrRegion.height*x,C=this.qrRegion.x*p,A=this.qrRegion.y*x;this.context.drawImage(f,C,A,_,g,0,0,this.qrRegion.width,this.qrRegion.height);var B=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(O){!O&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){B()})):B()}).catch(function(O){u.logger.logError("Error happend while scanning context",O),B()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var o="facingMode",c="deviceId",u={user:!0,environment:!0},f="exact",p=function(k){if(k in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(k,"'")},x=Object.keys(r);if(x.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(x.length," keys");var _=Object.keys(r)[0];if(_!==o&&_!==c)throw"Only '".concat(o,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(_===o){var g=r.facingMode;if(typeof g=="string"){if(p(g))return{facingMode:g}}else if(typeof g=="object")if(f in g){if(p(g["".concat(f)]))return{facingMode:{exact:g["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var C=typeof g;throw"Invalid type of 'facingMode' = ".concat(C)}}else{var A=r.deviceId;if(typeof A=="string")return{deviceId:A};if(typeof A=="object"){if(f in A)return{deviceId:{exact:A["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var B=typeof A;throw"Invalid type of 'deviceId' = ".concat(B)}}}var O=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(O)},t.prototype.computeCanvasDrawConfig=function(r,o,c,u){if(r<=c&&o<=u){var f=(c-r)/2,p=(u-o)/2;return{x:f,y:p,width:r,height:o}}else{var x=r,_=o;return r>c&&(o=c/r*o,r=c),o>u&&(r=u/o*r,o=u),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(_)+" to ".concat(r,"X").concat(o,".")),this.computeCanvasDrawConfig(r,o,c,u)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(o){o.style.backgroundColor=r?on.BORDER_SHADER_MATCH_COLOR:on.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,o,c){var u=r,f=o,p=document.createElement("canvas");return p.style.width="".concat(u,"px"),p.style.height="".concat(f,"px"),p.style.display="none",p.id=Mn(c)?"qr-canvas":c,p},t.prototype.getShadedRegionBounds=function(r,o,c){if(c.width>r||c.height>o)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(o-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,o,c,u){if(!(o-u.width<1||c-u.height<1)){var f=document.createElement("div");f.style.position="absolute";var p=(o-u.width)/2,x=(c-u.height)/2;if(f.style.borderLeft="".concat(p,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(p,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(on.SHADED_REGION_ELEMENT_ID),o-u.width<11||c-u.height<11)this.hasBorderShaders=!1;else{var _=5,g=40;this.insertShaderBorders(f,g,_,-_,null,0,!0),this.insertShaderBorders(f,g,_,-_,null,0,!1),this.insertShaderBorders(f,g,_,null,-_,0,!0),this.insertShaderBorders(f,g,_,null,-_,0,!1),this.insertShaderBorders(f,_,g+_,-_,null,-_,!0),this.insertShaderBorders(f,_,g+_,null,-_,-_,!0),this.insertShaderBorders(f,_,g+_,-_,null,-_,!1),this.insertShaderBorders(f,_,g+_,null,-_,-_,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,o,c,u,f,p,x){var _=document.createElement("div");_.style.position="absolute",_.style.backgroundColor=on.BORDER_SHADER_DEFAULT_COLOR,_.style.width="".concat(o,"px"),_.style.height="".concat(c,"px"),u!==null&&(_.style.top="".concat(u,"px")),f!==null&&(_.style.bottom="".concat(f,"px")),x?_.style.left="".concat(p,"px"):_.style.right="".concat(p,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(_),r.appendChild(_)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),xl;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(xl||(xl={}));const Bw={class:"scan-code"},Lw={class:"btn"},Fw={class:"left-back"},Uw=v.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=Nd.IconScan(),u=v.reactive({html5QrCode:null}),f=v.ref(!1),p=()=>{if(!u.html5QrCode){et("摄像头无访问权限!");return}f.value=!0,u.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[ti.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const O=new URL(A).searchParams.get("sessionId");O?o("scanSuccess",O):et("无效的二维码")}catch{et("无效的二维码")}C()}).catch(A=>{console.log(A),et({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{p()})},_=()=>{C()},g=()=>gl.getCameras().then(A=>{A&&A.length&&(u.html5QrCode=new gl("reader"))}).catch(()=>{et({message:"摄像头无访问权限!",duration:3e3})}),C=()=>{u.html5QrCode&&u.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),et("停止扫码失败")}).finally(()=>{f.value=!1})};return v.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&C()}),(A,B)=>{const O=os;return v.openBlock(),v.createElementBlock("div",null,[v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(c),size:"28",svgSize:"20",onClick:B[0]||(B[0]=k=>x())},null,8,["icon"]),(v.openBlock(),v.createBlock(v.Teleport,{to:"body"},[v.withDirectives(v.createElementVNode("div",Bw,[B[1]||(B[1]=v.createElementVNode("div",{class:"container"},[v.createElementVNode("div",{class:"qrcode"},[v.createElementVNode("div",{id:"reader"})])],-1)),v.createElementVNode("div",Lw,[v.createElementVNode("div",Fw,[v.createVNode(O,{name:"arrow-left",onClick:_})])])],512),[[v.vShow,f.value]])]))])}}}),zw=Kn(Uw,[["__scopeId","data-v-2d988579"]]);function as(t,r,o){const c=v.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const C=c.value;if(C.length===0)return"";if(r){const B=typeof r=="string"?r:r.value;if(B&&C.some(O=>O.id===B))return B}const A=C.find(B=>B.isDefault);return A?A.id:C[0].id};let f,p=!1;if(r&&typeof r!="string")f=r,p=!0,(!f.value||!c.value.some(C=>C.id===f.value))&&(f.value=u());else{let C;r&&typeof r=="string"&&(C=r),f=v.ref(C&&c.value.some(A=>A.id===C)?C:u())}(!p||o)&&v.watch(f,C=>{o&&o(C)});const x=v.computed(()=>c.value.find(C=>C.id===f.value)),_=v.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:_,setSelectedModel:C=>{c.value.find(B=>B.id===C)?f.value=C:console.warn(`[useModel] Model not found: ${C}`)}}}const $w=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Vw=Object.prototype.toString,Zw=t=>Vw.call(t)==="[object Object]",Ti=()=>{};function Co(t){return Array.isArray(t)?t:[t]}function jw(t,r,o){return v.watch(t,r,{...o,immediate:!0})}const Yu=$w?window:void 0;function Gr(t){var r;const o=v.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function bo(...t){const r=(c,u,f,p)=>(c.addEventListener(u,f,p),()=>c.removeEventListener(u,f,p)),o=v.computed(()=>{const c=Co(v.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return jw(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>Gr(f)))!==null&&c!==void 0?c:[Yu].filter(f=>f!=null),Co(v.toValue(o.value?t[1]:t[0])),Co(v.unref(o.value?t[2]:t[1])),v.toValue(o.value?t[3]:t[2])]},([c,u,f,p],x,_)=>{if(!c?.length||!u?.length||!f?.length)return;const g=Zw(p)?{...p}:p,C=c.flatMap(A=>u.flatMap(B=>f.map(O=>r(A,B,O,g))));_(()=>{C.forEach(A=>A())})},{flush:"post"})}function Ww(t,r,o={}){const{window:c=Yu,ignore:u=[],capture:f=!0,detectIframe:p=!1,controls:x=!1}=o;if(!c)return x?{stop:Ti,cancel:Ti,trigger:Ti}:Ti;let _=!0;const g=L=>v.toValue(u).some(Y=>{if(typeof Y=="string")return Array.from(c.document.querySelectorAll(Y)).some(Z=>Z===L.target||L.composedPath().includes(Z));{const Z=Gr(Y);return Z&&(L.target===Z||L.composedPath().includes(Z))}});function C(L){const Y=v.toValue(L);return Y&&Y.$.subTree.shapeFlag===16}function A(L,Y){const Z=v.toValue(L),$=Z.$.subTree&&Z.$.subTree.children;return $==null||!Array.isArray($)?!1:$.some(H=>H.el===Y.target||Y.composedPath().includes(H.el))}const B=L=>{const Y=Gr(t);if(L.target!=null&&!(!(Y instanceof Element)&&C(t)&&A(t,L))&&!(!Y||Y===L.target||L.composedPath().includes(Y))){if("detail"in L&&L.detail===0&&(_=!g(L)),!_){_=!0;return}r(L)}};let O=!1;const k=[bo(c,"click",L=>{O||(O=!0,setTimeout(()=>{O=!1},0),B(L))},{passive:!0,capture:f}),bo(c,"pointerdown",L=>{const Y=Gr(t);_=!g(L)&&!!(Y&&!L.composedPath().includes(Y))},{passive:!0}),p&&bo(c,"blur",L=>{setTimeout(()=>{var Y;const Z=Gr(t);((Y=c.document.activeElement)===null||Y===void 0?void 0:Y.tagName)==="IFRAME"&&!Z?.contains(c.document.activeElement)&&r(L)},0)},{passive:!0})].filter(Boolean),P=()=>k.forEach(L=>L());return x?{stop:P,cancel:()=>{_=!1},trigger:L=>{_=!0,B(L),_=!1}}:P}const Hw=["data-active","disabled"],Gw=v.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,o)=>(v.openBlock(),v.createElementBlock("button",{class:v.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[v.renderSlot(r.$slots,"default",{},void 0,!0)],10,Hw))}}),ls=Kn(Gw,[["__scopeId","data-v-6f582cce"]]),Xw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function qw(t,r){return v.openBlock(),v.createElementBlock("svg",Xw,[...r[0]||(r[0]=[v.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),v.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const Yw={render:qw},Jw={class:"button-text"},Kw={class:"dropdown-menu__items"},Qw=["onClick"],e3=v.defineComponent({__name:"ModelSwitch",props:v.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,o=v.useModel(t,"selectedModelId"),c=r.modelConfigs?Array.isArray(r.modelConfigs)?v.shallowRef(r.modelConfigs):r.modelConfigs:void 0,{selectedModel:u,availableModels:f,setSelectedModel:p}=as(c,o),x=v.ref(!1),_=O=>{p(O),C()},g=()=>{x.value=!x.value},C=()=>{x.value=!1},A=v.ref(null),B=v.ref(null);return Ww(B,()=>{C()},{ignore:[A]}),(O,k)=>(v.openBlock(),v.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[v.createVNode(ls,{size:"small",class:"action-button",rounded:"",onClick:g},{default:v.withCtx(()=>[(v.openBlock(),v.createBlock(v.resolveDynamicComponent(v.unref(u)?.icon),{width:16,height:16,class:"selected-model__icon"})),v.createElementVNode("span",Jw,v.toDisplayString(v.unref(u)?.label),1),v.createVNode(v.unref(Yw),{width:16,height:16})]),_:1}),v.createVNode(v.Transition,{name:"dropdown"},{default:v.withCtx(()=>[x.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:B},[v.createElementVNode("div",Kw,[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(v.unref(f),P=>(v.openBlock(),v.createElementBlock("div",{key:P.id,class:v.normalizeClass(["dropdown-menu__item",{"active-menu":P.id===o.value}]),onClick:v.withModifiers(L=>_(P.id),["stop"])},[P.icon?(v.openBlock(),v.createBlock(v.resolveDynamicComponent(P.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):v.createCommentVNode("",!0),v.createElementVNode("span",null,v.toDisplayString(P.label),1)],10,Qw))),128))])],512)):v.createCommentVNode("",!0)]),_:1}),x.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:C})):v.createCommentVNode("",!0)],512))}}),t3=Kn(e3,[["__scopeId","data-v-cee7e07b"]]),n3={key:0,class:"active-count"},r3=v.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,o=v.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,u)=>(v.openBlock(),v.createBlock(ls,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:v.withCtx(()=>[v.createVNode(v.unref(Sr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=v.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(v.openBlock(),v.createElementBlock("span",n3,v.toDisplayString(o.value),1)):v.createCommentVNode("",!0)]),_:1},8,["active"]))}}),i3=Kn(r3,[["__scopeId","data-v-c2a16c66"]]),o3={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function s3(t,r){return v.openBlock(),v.createElementBlock("svg",o3,[...r[0]||(r[0]=[v.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),v.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const a3={render:s3},l3=v.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=v.useModel(t,"genuiEnabled"),o=()=>{r.value=!r.value};return(c,u)=>(v.openBlock(),v.createBlock(ls,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:v.withCtx(()=>[v.createVNode(v.unref(a3),{width:16,height:16}),u[0]||(u[0]=v.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),c3=Kn(l3,[["__scopeId","data-v-7f3b0372"]]),u3={class:"bubble-image-wrapper"},d3=["src"],f3=["src"],h3=v.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=v.ref(!1),o=v.ref(null),c=()=>{r.value=!0},u=()=>{r.value=!1};return v.watch(r,f=>{f&&v.nextTick(()=>{o.value?.focus()})}),(f,p)=>(v.openBlock(),v.createElementBlock("div",u3,[v.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,d3),(v.openBlock(),v.createBlock(v.Teleport,{to:"body"},[r.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:u,onKeydown:v.withKeys(u,["esc"])},[v.createElementVNode("button",{ref_key:"closeButtonRef",ref:o,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:u},[...p[1]||(p[1]=[v.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[v.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),v.createElementVNode("div",{class:"preview-content",onClick:p[0]||(p[0]=v.withModifiers(()=>{},["stop"]))},[v.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,f3)])],32)):v.createCommentVNode("",!0)]))]))}}),p3=Kn(h3,[["__scopeId","data-v-91c75579"]]),Zr="https://agent.opentiny.design",m3=[{id:"12306-mcp",name:"12306服务器",description:"12306购票搜索服务器",icon:"https://agent.opentiny.design/public-assets/icons/icon-12306.webp",enabled:!1,addState:"idle",tools:[],url:Zr+"/api/v1/mcp-server/12306/mcp",type:"StreamableHTTP"},{id:"markdown2pdf-mcp",name:"Markdown转PDF MCP服务器",description:"Markdown转PDF MCP服务器,可以将Markdown文件转换为PDF文件",icon:"https://agent.opentiny.design/public-assets/icons/icon-pdf.png",url:Zr+"/servers/markdown2pdf-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"docx-mcp",name:"Word文档MCP服务器",description:"Word文档MCP服务器,可以创建、编辑、保存Word文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-word.png",url:Zr+"/servers/excel-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"excel-mcp",name:"Excel文档MCP服务器",description:"Excel文档MCP服务器,可以创建、编辑、保存Excel文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-excel.png",url:Zr+"/servers/excel-mcp/mcp",type:"StreamableHTTP",enabled:!1,addState:"idle",tools:[]},{id:"doc-tools-mcp",name:"文档工具MCP服务器",description:"文档工具MCP服务器,可以创建、编辑、保存文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-doc.png",url:Zr+"/servers/doc-tools-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]}],g3=`
|
|
76
|
+
`),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<rr.NUM_MASK_PATTERNS}}rr.NUM_MASK_PATTERNS=8;class st extends g{}st.kind="WriterException";class Te{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Te.clearMatrix(a),Te.embedBasicPatterns(i,a),Te.embedTypeInfo(n,s,a),Te.maybeEmbedVersionInfo(i,a),Te.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Te.embedPositionDetectionPatternsAndSeparators(n),Te.embedDarkDotAtLeftBottomCorner(n),Te.maybeEmbedPositionAdjustmentPatterns(e,n),Te.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new W;Te.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Te.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(i.setBoolean(p,y,d),a<8){const E=i.getWidth()-a-1;i.setBoolean(E,8,d)}else{const I=i.getHeight()-7+(a-8);i.setBoolean(8,I,d)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const i=new W;Te.makeVersionInfoBits(e,i);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const d=i.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,d),n.setBoolean(n.getHeight()-11+l,a,d)}}static embedDataBits(e,n,i){let s=0,a=-1,l=i.getWidth()-1,d=i.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);d>=0&&d<i.getHeight();){for(let h=0;h<2;++h){const p=l-h;if(!Te.isEmpty(i.get(p,d)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&It.getDataMaskBit(n,p,d)&&(y=!y),i.setBoolean(p,d,y)}d+=a}a=-a,d+=a,l-=2}if(s!==e.getSize())throw new st("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-$.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const i=Te.findMSBSet(n);for(e<<=i-1;Te.findMSBSet(e)>=i;)e^=n<<Te.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!rr.isValidMaskPattern(n))throw new st("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Te.calculateBCHCode(s,Te.TYPE_INFO_POLY);i.appendBits(a,10);const l=new W;if(l.appendBits(Te.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new st("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Te.calculateBCHCode(e.getVersionNumber(),Te.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new st("should not happen but we got: "+n.getSize())}static isEmpty(e){return e===255}static embedTimingPatterns(e){for(let n=8;n<e.getWidth()-8;++n){const i=(n+1)%2;Te.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Te.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new st;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Te.isEmpty(i.get(e+s,n)))throw new st;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Te.isEmpty(i.get(e,n+s)))throw new st;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Te.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,i){for(let s=0;s<7;++s){const a=Te.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Te.POSITION_DETECTION_PATTERN[0].length;Te.embedPositionDetectionPattern(0,0,e),Te.embedPositionDetectionPattern(e.getWidth()-n,0,e),Te.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Te.embedHorizontalSeparationPattern(0,i-1,e),Te.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Te.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Te.embedVerticalSeparationPattern(s,0,e),Te.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Te.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Te.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[i];for(let a=0,l=s.length;a!==l;a++){const d=s[a];if(d>=0)for(let h=0;h!==l;h++){const p=s[h];p>=0&&Te.isEmpty(n.get(p,d))&&Te.embedPositionAdjustmentPattern(p-2,d-2,n)}}}}Te.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),Te.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),Te.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),Te.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),Te.VERSION_INFO_POLY=7973,Te.TYPE_INFO_POLY=1335,Te.TYPE_INFO_MASK_PATTERN=21522;class xd{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class dt{constructor(){}static calculateMaskPenalty(e){return It.applyMaskPenaltyRule1(e)+It.applyMaskPenaltyRule2(e)+It.applyMaskPenaltyRule3(e)+It.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=dt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Rt.CHARACTER_SET)!==void 0;a&&(s=i.get(Rt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new W;if(l===Se.BYTE&&(a||dt.DEFAULT_BYTE_MODE_ENCODING!==s)){const xe=M.getCharacterSetECIByName(s);xe!==void 0&&this.appendECI(xe,d)}this.appendModeInfo(l,d);const h=new W;this.appendBytes(e,l,h,s);let p;if(i!==null&&i.get(Rt.QR_VERSION)!==void 0){const xe=Number.parseInt(i.get(Rt.QR_VERSION).toString(),10);p=Ee.getVersionForNumber(xe);const ue=this.calculateBitsNeeded(l,d,h,p);if(!this.willFit(ue,p,n))throw new st("Data too big for requested version")}else p=this.recommendVersion(n,l,d,h);const y=new W;y.appendBitArray(d);const E=l===Se.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(E,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),R=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(R,y);const F=this.interleaveWithECBytes(y,p.getTotalCodewords(),R,I.getNumBlocks()),U=new rr;U.setECLevel(n),U.setMode(l),U.setVersion(p);const Y=p.getDimensionForVersion(),re=new mi(Y,Y),me=this.chooseMaskPattern(F,n,p,re);return U.setMaskPattern(me),Te.buildMatrix(F,n,p,me,re),U.setMatrix(re),U}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,Ee.getVersionForNumber(1)),l=this.chooseVersion(a,e),d=this.calculateBitsNeeded(n,i,s,l);return this.chooseVersion(d,e)}static calculateBitsNeeded(e,n,i,s){return n.getSize()+e.getCharacterCountBits(s)+i.getSize()}static getAlphanumericCode(e){return e<dt.ALPHANUMERIC_TABLE.length?dt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(M.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Se.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(dt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return Se.BYTE}return s?Se.ALPHANUMERIC:i?Se.NUMERIC:Se.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=ce.encode(e,M.SJIS)}catch{return!1}const i=n.length;if(i%2!==0)return!1;for(let s=0;s<i;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,i,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let d=0;d<rr.NUM_MASK_PATTERNS;d++){Te.buildMatrix(e,n,i,d,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=d)}return l}static chooseVersion(e,n){for(let i=1;i<=40;i++){const s=Ee.getVersionForNumber(i);if(dt.willFit(e,s,n))return s}throw new st("Data too big")}static willFit(e,n,i){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(i).getTotalECCodewords(),d=s-l,h=(e+7)/8;return d>=h}static terminateBits(e,n){const i=e*8;if(n.getSize()>i)throw new st("data bits cannot fit in the QR Code"+n.getSize()+" > "+i);for(let l=0;l<4&&n.getSize()<i;++l)n.appendBit(!1);const s=n.getSize()&7;if(s>0)for(let l=s;l<8;l++)n.appendBit(!1);const a=e-n.getSizeInBytes();for(let l=0;l<a;++l)n.appendBits((l&1)===0?236:17,8);if(n.getSize()!==i)throw new st("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new st("Block ID too large");const d=e%i,h=i-d,p=Math.floor(e/i),y=p+1,E=Math.floor(n/i),I=E+1,R=p-E,F=y-I;if(R!==F)throw new st("EC bytes mismatch");if(i!==h+d)throw new st("RS blocks mismatch");if(e!==(E+R)*h+(I+F)*d)throw new st("Total bytes mismatch");s<h?(a[0]=E,l[0]=R):(a[0]=I,l[0]=F)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new st("Number of bits and data bytes does not match");let a=0,l=0,d=0;const h=new Array;for(let y=0;y<s;++y){const E=new Int32Array(1),I=new Int32Array(1);dt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,y,E,I);const R=E[0],F=new Uint8Array(R);e.toBytes(8*a,F,0,R);const U=dt.generateECBytes(F,I[0]);h.push(new xd(F,U)),l=Math.max(l,R),d=Math.max(d,U.length),a+=E[0]}if(i!==a)throw new st("Data bytes does not match offset");const p=new W;for(let y=0;y<l;++y)for(const E of h){const I=E.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<d;++y)for(const E of h){const I=E.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new st("Interleaving error: "+n+" and "+p.getSizeInBytes()+" differ.");return p}static generateECBytes(e,n){const i=e.length,s=new Int32Array(i+n);for(let l=0;l<i;l++)s[l]=e[l]&255;new oo(Ue.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[i+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,i,s){const a=i.getCharacterCountBits(n);if(e>=1<<a)throw new st(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case Se.NUMERIC:dt.appendNumericBytes(e,i);break;case Se.ALPHANUMERIC:dt.appendAlphanumericBytes(e,i);break;case Se.BYTE:dt.append8BitBytes(e,i,s);break;case Se.KANJI:dt.appendKanjiBytes(e,i);break;default:throw new st("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=dt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getDigit(e.charAt(s));if(s+2<i){const l=dt.getDigit(e.charAt(s+1)),d=dt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=dt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new st;if(s+1<i){const l=dt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new st;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=ce.encode(e,i)}catch(a){throw new st(a)}for(let a=0,l=s.length;a!==l;a++){const d=s[a];n.appendBits(d,8)}}static appendKanjiBytes(e,n){let i;try{i=ce.encode(e,M.SJIS)}catch(a){throw new st(a)}const s=i.length;for(let a=0;a<s;a+=2){const l=i[a]&255,d=i[a+1]&255,h=l<<8&4294967295|d;let p=-1;if(h>=33088&&h<=40956?p=h-33088:h>=57408&&h<=60351&&(p=h-49472),p===-1)throw new st("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Se.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}dt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),dt.DEFAULT_BYTE_MODE_ENCODING=M.UTF8.getName();class ir{write(e,n,i,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||i<0)throw new A("Requested dimensions are too small: "+n+"x"+i);let a=ut.L,l=ir.QUIET_ZONE_SIZE;s!==null&&(s.get(Rt.ERROR_CORRECTION)!==void 0&&(a=ut.fromString(s.get(Rt.ERROR_CORRECTION).toString())),s.get(Rt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Rt.MARGIN).toString(),10)));const d=dt.encode(e,a,s);return this.renderResult(d,n,i,l)}writeToDom(e,n,i,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,i,s,a);e&&e.appendChild(l)}renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),R=Math.floor((y-l*I)/2),F=Math.floor((E-d*I)/2),U=this.createSVGElement(y,E);for(let Y=0,re=F;Y<d;Y++,re+=I)for(let me=0,xe=R;me<l;me++,xe+=I)if(a.get(me,Y)===1){const ue=this.createSvgRectElement(xe,re,I,I);U.appendChild(ue)}return U}createSVGElement(e,n){const i=document.createElementNS(ir.SVG_NS,"svg");return i.setAttributeNS(null,"height",e.toString()),i.setAttributeNS(null,"width",n.toString()),i}createSvgRectElement(e,n,i,s){const a=document.createElementNS(ir.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",i.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}ir.QUIET_ZONE_SIZE=4,ir.SVG_NS="http://www.w3.org/2000/svg";class _r{encode(e,n,i,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==ie.QR_CODE)throw new A("Can only encode QR_CODE, but got "+n);if(i<0||s<0)throw new A(`Requested dimensions are too small: ${i}x${s}`);let l=ut.L,d=_r.QUIET_ZONE_SIZE;a!==null&&(a.get(Rt.ERROR_CORRECTION)!==void 0&&(l=ut.fromString(a.get(Rt.ERROR_CORRECTION).toString())),a.get(Rt.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Rt.MARGIN).toString(),10)));const h=dt.encode(e,l,a);return _r.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),R=Math.floor((y-l*I)/2),F=Math.floor((E-d*I)/2),U=new q(y,E);for(let Y=0,re=F;Y<d;Y++,re+=I)for(let me=0,xe=R;me<l;me++,xe+=I)a.get(me,Y)===1&&U.setRegion(xe,re,I,I);return U}}_r.QUIET_ZONE_SIZE=4;class yd{encode(e,n,i,s,a){let l;switch(n){case ie.QR_CODE:l=new _r;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class Nn extends te{constructor(e,n,i,s,a,l,d,h){if(super(l,d),this.yuvData=e,this.dataWidth=n,this.dataHeight=i,this.left=s,this.top=a,s+l>n||a+d>i)throw new A("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,d)}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return B.arraycopy(this.yuvData,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return B.arraycopy(this.yuvData,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;B.arraycopy(this.yuvData,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new Nn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/Nn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/Nn.THUMBNAIL_SCALE_FACTOR,i=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const d=l*e;for(let h=0;h<e;h++){const p=s[a+h*Nn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|p*65793}a+=this.dataWidth*Nn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/Nn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/Nn.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const i=this.yuvData;for(let s=0,a=this.top*this.dataWidth+this.left;s<n;s++,a+=this.dataWidth){const l=a+e/2;for(let d=a,h=a+e-1;d<l;d++,h--){const p=i[d];i[d]=i[h],i[h]=p}}}invert(){return new he(this)}}Nn.THUMBNAIL_SCALE_FACTOR=2;class so extends te{constructor(e,n,i,s,a,l,d){if(super(n,i),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=d,e.BYTES_PER_ELEMENT===4){const h=n*i,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const E=e[y],I=E>>16&255,R=E>>7&510,F=E&255;p[y]=(I+R+F)/4&255}this.luminances=p}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=i),l===void 0&&(this.left=0),d===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+i>this.dataHeight)throw new A("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const i=this.getWidth();(n==null||n.length<i)&&(n=new Uint8ClampedArray(i));const s=(e+this.top)*this.dataWidth+this.left;return B.arraycopy(this.luminances,s,n,0,i),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const i=e*n,s=new Uint8ClampedArray(i);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return B.arraycopy(this.luminances,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;B.arraycopy(this.luminances,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new so(this.luminances,i,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new he(this)}}class vs extends M{static forName(e){return this.getCharacterSetECIByName(e)}}class ao{}ao.ISO_8859_1=M.ISO8859_1;class Cs{isCompact(){return this.compact}setCompact(e){this.compact=e}getSize(){return this.size}setSize(e){this.size=e}getLayers(){return this.layers}setLayers(e){this.layers=e}getCodeWords(){return this.codeWords}setCodeWords(e){this.codeWords=e}getMatrix(){return this.matrix}setMatrix(e){this.matrix=e}}class bs{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class wd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class vr extends wd{constructor(e,n,i){super(e),this.value=n,this.bitCount=i}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new vr(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new vr(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+$.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class lo extends vr{constructor(e,n,i){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=i}appendTo(e,n){for(let i=0;i<this.binaryShiftByteCount;i++)(i===0||i===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):i===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+i],8)}addBinaryShift(e,n){return new lo(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function _d(b,e,n){return new lo(b,e,n)}function Lr(b,e,n){return new vr(b,e,n)}const vd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Wn=0,gi=1,hn=2,Es=3,On=4,Cd=new vr(null,0,0),co=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])];function bd(b){for(let e of b)z.fill(e,-1);return b[Wn][On]=0,b[gi][On]=0,b[gi][Wn]=28,b[Es][On]=0,b[hn][On]=0,b[hn][Wn]=15,b}const As=bd(z.createInt32Array(6,6));class Rn{constructor(e,n,i,s){this.token=e,this.mode=n,this.binaryShiftByteCount=i,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let i=this.bitCount,s=this.token;if(e!==this.mode){let l=co[this.mode][e];s=Lr(s,l&65535,l>>16),i+=l>>16}let a=e===hn?4:5;return s=Lr(s,n,a),new Rn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===hn?4:5;return i=Lr(i,As[this.mode][e],s),i=Lr(i,n,5),new Rn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===On||this.mode===hn){let d=co[i][Wn];n=Lr(n,d&65535,d>>16),s+=d>>16,i=Wn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Rn(n,i,this.binaryShiftByteCount+1,s+a);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(e+1)),l}endBinaryShift(e){if(this.binaryShiftByteCount===0)return this;let n=this.token;return n=_d(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Rn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(co[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Rn.calculateBinaryShiftCost(e)-Rn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let i=new W;for(const s of n)s.appendTo(i,e);return i}toString(){return fe.format("%s bits=%d bytes=%d",vd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Rn.INITIAL_STATE=new Rn(Cd,Wn,0,0);function Ed(b){const e=fe.getCharCode(" "),n=fe.getCharCode("."),i=fe.getCharCode(",");b[Wn][e]=1;const s=fe.getCharCode("Z"),a=fe.getCharCode("A");for(let I=a;I<=s;I++)b[Wn][I]=I-a+2;b[gi][e]=1;const l=fe.getCharCode("z"),d=fe.getCharCode("a");for(let I=d;I<=l;I++)b[gi][I]=I-d+2;b[hn][e]=1;const h=fe.getCharCode("9"),p=fe.getCharCode("0");for(let I=p;I<=h;I++)b[hn][I]=I-p+2;b[hn][i]=12,b[hn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
|
|
77
|
+
`,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)b[Es][fe.getCharCode(y[I])]=I;const E=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<E.length;I++)fe.getCharCode(E[I])>0&&(b[On][fe.getCharCode(E[I])]=I);return b}const uo=Ed(z.createInt32Array(5,256));class Fr{constructor(e){this.text=e}encode(){const e=fe.getCharCode(" "),n=fe.getCharCode(`
|
|
78
|
+
`);let i=bs.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,d=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case fe.getCharCode("\r"):l=d===n?2:0;break;case fe.getCharCode("."):l=d===e?3:0;break;case fe.getCharCode(","):l=d===e?4:0;break;case fe.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Fr.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return bs.min(i,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const i=[];for(let s of e)this.updateStateForChar(s,n,i);return Fr.simplifyStates(i)}updateStateForChar(e,n,i){let s=this.text[n]&255,a=uo[e.getMode()][s]>0,l=null;for(let d=0;d<=On;d++){let h=uo[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===hn){const p=l.latchAndAppend(d,h);i.push(p)}if(!a&&As[e.getMode()][d]>=0){const p=l.shiftAndAppend(d,h);i.push(p)}}}if(e.getBinaryShiftByteCount()>0||uo[e.getMode()][s]===0){let d=e.addBinaryShiftChar(n);i.push(d)}}static updateStateListForPair(e,n,i){const s=[];for(let a of e)this.updateStateForPair(a,n,i,s);return this.simplifyStates(s)}static updateStateForPair(e,n,i,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(On,i)),e.getMode()!==On&&s.push(a.shiftAndAppend(On,i)),i===3||i===4){let l=a.latchAndAppend(hn,16-i).latchAndAppend(hn,1);s.push(l)}if(e.getBinaryShiftByteCount()>0){let l=e.addBinaryShiftChar(n).addBinaryShiftChar(n+1);s.push(l)}}static simplifyStates(e){let n=[];for(const i of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(i)){s=!1;break}i.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(i)}return n}}class Ge{constructor(){}static encodeBytes(e){return Ge.encode(e,Ge.DEFAULT_EC_PERCENT,Ge.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Fr(e).encode(),a=$.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,p,y,E;if(i!==Ge.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?Ge.MAX_NB_BITS_COMPACT:Ge.MAX_NB_BITS))throw new A(fe.format("Illegal value %s for layers",i));p=Ge.totalBitsInLayer(h,d),y=Ge.WORD_SIZE[h];let ue=p-p%y;if(E=Ge.stuffBits(s,y),E.getSize()+a>ue)throw new A("Data to large for user specified layer");if(d&&E.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,E=null;for(let ue=0;;ue++){if(ue>Ge.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(d=ue<=3,h=d?ue+1:ue,p=Ge.totalBitsInLayer(h,d),l>p)continue;(E==null||y!==Ge.WORD_SIZE[h])&&(y=Ge.WORD_SIZE[h],E=Ge.stuffBits(s,y));let We=p-p%y;if(!(d&&E.getSize()>y*64)&&E.getSize()+a<=We)break}}let I=Ge.generateCheckWords(E,p,y),R=E.getSize()/y,F=Ge.generateModeMessage(d,h,R),U=(d?11:14)+h*4,Y=new Int32Array(U),re;if(d){re=U;for(let ue=0;ue<Y.length;ue++)Y[ue]=ue}else{re=U+1+2*$.truncDivision($.truncDivision(U,2)-1,15);let ue=$.truncDivision(U,2),We=$.truncDivision(re,2);for(let Be=0;Be<ue;Be++){let Qt=Be+$.truncDivision(Be,15);Y[ue-Be-1]=We-Qt-1,Y[ue+Be]=We+Qt+1}}let me=new q(re);for(let ue=0,We=0;ue<h;ue++){let Be=(h-ue)*4+(d?9:12);for(let Qt=0;Qt<Be;Qt++){let gn=Qt*2;for(let en=0;en<2;en++)I.get(We+gn+en)&&me.set(Y[ue*2+en],Y[ue*2+Qt]),I.get(We+Be*2+gn+en)&&me.set(Y[ue*2+Qt],Y[U-1-ue*2-en]),I.get(We+Be*4+gn+en)&&me.set(Y[U-1-ue*2-en],Y[U-1-ue*2-Qt]),I.get(We+Be*6+gn+en)&&me.set(Y[U-1-ue*2-Qt],Y[ue*2+en])}We+=Be*8}if(Ge.drawModeMessage(me,d,re,F),d)Ge.drawBullsEye(me,$.truncDivision(re,2),5);else{Ge.drawBullsEye(me,$.truncDivision(re,2),7);for(let ue=0,We=0;ue<$.truncDivision(U,2)-1;ue+=15,We+=16)for(let Be=$.truncDivision(re,2)&1;Be<re;Be+=2)me.set($.truncDivision(re,2)-We,Be),me.set($.truncDivision(re,2)+We,Be),me.set(Be,$.truncDivision(re,2)-We),me.set(Be,$.truncDivision(re,2)+We)}let xe=new Cs;return xe.setCompact(d),xe.setSize(re),xe.setLayers(h),xe.setCodeWords(R),xe.setMatrix(me),xe}static drawBullsEye(e,n,i){for(let s=0;s<i;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-i,n-i),e.set(n-i+1,n-i),e.set(n-i,n-i+1),e.set(n+i,n-i),e.set(n+i,n-i+1),e.set(n+i,n+i-1)}static generateModeMessage(e,n,i){let s=new W;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=Ge.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=Ge.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=$.truncDivision(i,2);if(n)for(let l=0;l<7;l++){let d=a-3+l;s.get(l)&&e.set(d,a-5),s.get(l+7)&&e.set(a+5,d),s.get(20-l)&&e.set(d,a+5),s.get(27-l)&&e.set(a-5,d)}else for(let l=0;l<10;l++){let d=a-5+l+$.truncDivision(l,5);s.get(l)&&e.set(d,a-7),s.get(l+10)&&e.set(a+7,d),s.get(29-l)&&e.set(d,a+7),s.get(39-l)&&e.set(a-7,d)}}static generateCheckWords(e,n,i){let s=e.getSize()/i,a=new oo(Ge.getGF(i)),l=$.truncDivision(n,i),d=Ge.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,p=new W;p.appendBits(0,h);for(const y of Array.from(d))p.appendBits(y,i);return p}static bitsToWords(e,n,i){let s=new Int32Array(i),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let d=0;for(let h=0;h<n;h++)d|=e.get(a*n+h)?1<<n-h-1:0;s[a]=d}return s}static getGF(e){switch(e){case 4:return Ue.AZTEC_PARAM;case 6:return Ue.AZTEC_DATA_6;case 8:return Ue.AZTEC_DATA_8;case 10:return Ue.AZTEC_DATA_10;case 12:return Ue.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let i=new W,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let d=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(d|=1<<n-1-h);(d&a)===a?(i.appendBits(d&a,n),l--):(d&a)===0?(i.appendBits(d|1,n),l--):i.appendBits(d,n)}return i}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Ge.DEFAULT_EC_PERCENT=33,Ge.DEFAULT_AZTEC_LAYERS=0,Ge.MAX_NB_BITS=32,Ge.MAX_NB_BITS_COMPACT=4,Ge.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class xi{encode(e,n,i,s){return this.encodeWithHints(e,n,i,s,null)}encodeWithHints(e,n,i,s,a){let l=ao.ISO_8859_1,d=Ge.DEFAULT_EC_PERCENT,h=Ge.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Rt.CHARACTER_SET)&&(l=vs.forName(a.get(Rt.CHARACTER_SET).toString())),a.has(Rt.ERROR_CORRECTION)&&(d=$.parseInt(a.get(Rt.ERROR_CORRECTION).toString())),a.has(Rt.AZTEC_LAYERS)&&(h=$.parseInt(a.get(Rt.AZTEC_LAYERS).toString()))),xi.encodeLayers(e,n,i,s,l,d,h)}static encodeLayers(e,n,i,s,a,l,d){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=Ge.encode(fe.getBytes(e,a),l,d);return xi.renderResult(h,i,s)}static renderResult(e,n,i){let s=e.getMatrix();if(s==null)throw new Vt;let a=s.getWidth(),l=s.getHeight(),d=Math.max(n,a),h=Math.max(i,l),p=Math.min(d/a,h/l),y=(d-a*p)/2,E=(h-l*p)/2,I=new q(d,h);for(let R=0,F=E;R<l;R++,F+=p)for(let U=0,Y=y;U<a;U++,Y+=p)s.get(U,R)&&I.setRegion(Y,F,p,p);return I}}o.AbstractExpandedDecoder=qi,o.ArgumentException=C,o.ArithmeticException=$t,o.AztecCode=Cs,o.AztecCodeReader=pr,o.AztecCodeWriter=xi,o.AztecDecoder=Je,o.AztecDetector=li,o.AztecDetectorResult=_t,o.AztecEncoder=Ge,o.AztecHighLevelEncoder=Fr,o.AztecPoint=Lt,o.BarcodeFormat=ie,o.Binarizer=k,o.BinaryBitmap=P,o.BitArray=W,o.BitMatrix=q,o.BitSource=Qi,o.BrowserAztecCodeReader=Wi,o.BrowserBarcodeReader=td,o.BrowserCodeReader=Ve,o.BrowserDatamatrixCodeReader=rd,o.BrowserMultiFormatReader=pd,o.BrowserPDF417Reader=md,o.BrowserQRCodeReader=gd,o.BrowserQRCodeSvgWriter=ir,o.CharacterSetECI=M,o.ChecksumException=O,o.Code128Reader=oe,o.Code39Reader=Re,o.DataMatrixDecodedBitStreamParser=$n,o.DataMatrixReader=Vn,o.DecodeHintType=H,o.DecoderResult=Ne,o.DefaultGridSampler=ai,o.DetectorResult=pe,o.EAN13Reader=Qn,o.EncodeHintType=Rt,o.Exception=g,o.FormatException=V,o.GenericGF=Ue,o.GenericGFPoly=Xe,o.GlobalHistogramBinarizer=Q,o.GridSampler=Un,o.GridSamplerInstance=An,o.HTMLCanvasElementLuminanceSource=ge,o.HybridBinarizer=j,o.ITFReader=qe,o.IllegalArgumentException=A,o.IllegalStateException=Vt,o.InvertedLuminanceSource=he,o.LuminanceSource=te,o.MathUtils=je,o.MultiFormatOneDReader=yr,o.MultiFormatReader=_s,o.MultiFormatWriter=yd,o.NotFoundException=D,o.OneDReader=Ie,o.PDF417DecodedBitStreamParser=ne,o.PDF417DecoderErrorCorrection=ps,o.PDF417Reader=Ut,o.PDF417ResultMetadata=gs,o.PerspectiveTransform=nn,o.PlanarYUVLuminanceSource=Nn,o.QRCodeByteMatrix=mi,o.QRCodeDataMask=dn,o.QRCodeDecodedBitStreamParser=Ct,o.QRCodeDecoderErrorCorrectionLevel=ut,o.QRCodeDecoderFormatInformation=jt,o.QRCodeEncoder=dt,o.QRCodeEncoderQRCode=rr,o.QRCodeMaskUtil=It,o.QRCodeMatrixUtil=Te,o.QRCodeMode=Se,o.QRCodeReader=Zn,o.QRCodeVersion=Ee,o.QRCodeWriter=_r,o.RGBLuminanceSource=so,o.RSS14Reader=At,o.RSSExpandedReader=le,o.ReaderException=pi,o.ReedSolomonDecoder=bn,o.ReedSolomonEncoder=oo,o.ReedSolomonException=pn,o.Result=Me,o.ResultMetadataType=Ae,o.ResultPoint=T,o.StringUtils=fe,o.UnsupportedOperationException=we,o.VideoInputDevice=de,o.WhiteRectangleDetector=vt,o.WriterException=st,o.ZXingArrays=z,o.ZXingCharset=vs,o.ZXingInteger=$,o.ZXingStandardCharsets=ao,o.ZXingStringBuilder=ae,o.ZXingStringEncoding=ce,o.ZXingSystem=B,o.createAbstractExpandedDecoder=fs,Object.defineProperty(o,"__esModule",{value:!0})}))})(Hr,Hr.exports)),Hr.exports}var ft=mw();const gw=Rc(ft),xw=Od({__proto__:null,default:gw},[ft]);var ul=(function(){function t(r,o,c){if(this.formatMap=new Map([[ve.QR_CODE,ft.BarcodeFormat.QR_CODE],[ve.AZTEC,ft.BarcodeFormat.AZTEC],[ve.CODABAR,ft.BarcodeFormat.CODABAR],[ve.CODE_39,ft.BarcodeFormat.CODE_39],[ve.CODE_93,ft.BarcodeFormat.CODE_93],[ve.CODE_128,ft.BarcodeFormat.CODE_128],[ve.DATA_MATRIX,ft.BarcodeFormat.DATA_MATRIX],[ve.MAXICODE,ft.BarcodeFormat.MAXICODE],[ve.ITF,ft.BarcodeFormat.ITF],[ve.EAN_13,ft.BarcodeFormat.EAN_13],[ve.EAN_8,ft.BarcodeFormat.EAN_8],[ve.PDF_417,ft.BarcodeFormat.PDF_417],[ve.RSS_14,ft.BarcodeFormat.RSS_14],[ve.RSS_EXPANDED,ft.BarcodeFormat.RSS_EXPANDED],[ve.UPC_A,ft.BarcodeFormat.UPC_A],[ve.UPC_E,ft.BarcodeFormat.UPC_E],[ve.UPC_EAN_EXTENSION,ft.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!xw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=o,this.logger=c;var u=this.createZXingFormats(r),f=new Map;f.set(ft.DecodeHintType.POSSIBLE_FORMATS,u),f.set(ft.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var o=this;return new Promise(function(c,u){try{c(o.decode(r))}catch(f){u(f)}})},t.prototype.decode=function(r){var o=new ft.MultiFormatReader(this.verbose,this.hints),c=new ft.HTMLCanvasElementLuminanceSource(r),u=new ft.BinaryBitmap(new ft.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:Gu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createZXingFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return o},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),yw=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function x(C){try{g(c.next(C))}catch(A){m(A)}}function _(C){try{g(c.throw(C))}catch(A){m(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},ww=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},dl=(function(){function t(r,o,c){if(this.formatMap=new Map([[ve.QR_CODE,"qr_code"],[ve.AZTEC,"aztec"],[ve.CODABAR,"codabar"],[ve.CODE_39,"code_39"],[ve.CODE_93,"code_93"],[ve.CODE_128,"code_128"],[ve.DATA_MATRIX,"data_matrix"],[ve.ITF,"itf"],[ve.EAN_13,"ean_13"],[ve.EAN_8,"ean_8"],[ve.PDF_417,"pdf417"],[ve.UPC_A,"upc_a"],[ve.UPC_E,"upc_e"]]),this.reverseFormatMap=this.createReverseFormatMap(),!t.isSupported())throw"Use html5qrcode.min.js without edit, Use BarcodeDetectorDelegate only if it isSupported();";this.verbose=o,this.logger=c;var u=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(u),!this.detector)throw"BarcodeDetector detector not supported"}return t.isSupported=function(){if(!("BarcodeDetector"in window))return!1;var r=new BarcodeDetector({formats:["qr_code"]});return typeof r<"u"},t.prototype.decodeAsync=function(r){return yw(this,void 0,void 0,function(){var o,c;return ww(this,function(u){switch(u.label){case 0:return[4,this.detector.detect(r)];case 1:if(o=u.sent(),!o||o.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(o),[2,{text:c.rawValue,format:Gu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var o=null,c=0,u=0,f=r;u<f.length;u++){var m=f[u],x=m.boundingBox.width*m.boundingBox.height;x>c&&(c=x,o=m)}if(!o)throw"No largest barcode found";return o},t.prototype.createBarcodeDetectorFormats=function(r){for(var o=[],c=0,u=r;c<u.length;c++){var f=u[c];this.formatMap.has(f)?o.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:o}},t.prototype.toHtml5QrcodeSupportedFormats=function(r){if(!this.reverseFormatMap.has(r))throw"reverseFormatMap doesn't have ".concat(r);return this.reverseFormatMap.get(r)},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(o,c,u){r.set(o,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),fl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function x(C){try{g(c.next(C))}catch(A){m(A)}}function _(C){try{g(c.throw(C))}catch(A){m(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},hl=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},_w=(function(){function t(r,o,c,u){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,o&&dl.isSupported()?(this.primaryDecoder=new dl(r,c,u),this.secondaryDecoder=new ul(r,c,u)):this.primaryDecoder=new ul(r,c,u)}return t.prototype.decodeAsync=function(r){return fl(this,void 0,void 0,function(){var o;return hl(this,function(c){switch(c.label){case 0:o=performance.now(),c.label=1;case 1:return c.trys.push([1,,3,4]),[4,this.getDecoder().decodeAsync(r)];case 2:return[2,c.sent()];case 3:return this.possiblyLogPerformance(o),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return fl(this,void 0,void 0,function(){var o,c;return hl(this,function(u){switch(u.label){case 0:o=performance.now(),u.label=1;case 1:return u.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,u.sent()];case 3:if(c=u.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(o),[7];case 5:return[2]}})})},t.prototype.getDecoder=function(){return this.secondaryDecoder?this.wasPrimaryDecoderUsedInLastDecode===!1?(this.wasPrimaryDecoderUsedInLastDecode=!0,this.primaryDecoder):(this.wasPrimaryDecoderUsedInLastDecode=!1,this.secondaryDecoder):this.primaryDecoder},t.prototype.possiblyLogPerformance=function(r){if(this.verbose){var o=performance.now()-r;this.executionResults.push(o),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,o=0,c=this.executionResults;o<c.length;o++){var u=c[o];r+=u}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),ss=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),Li=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function x(C){try{g(c.next(C))}catch(A){m(A)}}function _(C){try{g(c.throw(C))}catch(A){m(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},Fi=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},qu=(function(){function t(r,o){this.name=r,this.track=o}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var o={};o[this.name]=r;var c={advanced:[o]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var o=r[this.name];return o}return null},t})(),vw=(function(t){ss(r,t);function r(o,c){return t.call(this,o,c)||this}return r.prototype.min=function(){return this.getCapabilities().min},r.prototype.max=function(){return this.getCapabilities().max},r.prototype.step=function(){return this.getCapabilities().step},r.prototype.apply=function(o){var c={};c[this.name]=o;var u={advanced:[c]};return this.track.applyConstraints(u)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var o=this.track.getCapabilities(),c=o[this.name];return{min:c.min,max:c.max,step:c.step}},r.prototype.failIfNotSupported=function(){if(!this.isSupported())throw new Error("".concat(this.name," capability not supported"))},r})(qu),Cw=(function(t){ss(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(vw),bw=(function(t){ss(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(qu),Ew=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new Cw(this.track)},t.prototype.torchFeature=function(){return new bw(this.track)},t})(),Aw=(function(){function t(r,o,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=o,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var o=document.createElement("video");return o.style.width="".concat(r,"px"),o.style.display="block",o.muted=!0,o.setAttribute("muted","true"),o.playsInline=!0,o},t.prototype.setupSurface=function(){var r=this;this.surface.onabort=function(){throw"RenderedCameraImpl video surface onabort() called"},this.surface.onerror=function(){throw"RenderedCameraImpl video surface onerror() called"};var o=function(){var c=r.surface.clientWidth,u=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,u),r.surface.removeEventListener("playing",o)};this.surface.addEventListener("playing",o),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,o,c,u){return Li(this,void 0,void 0,function(){var f,m;return Fi(this,function(x){switch(x.label){case 0:return f=new t(r,o,u),c.aspectRatio?(m={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(m)]):[3,2];case 1:x.sent(),x.label=2;case 2:return f.setupSurface(),[2,f]}})})},t.prototype.failIfClosed=function(){if(this.isClosed)throw"The RenderedCamera has already been closed."},t.prototype.getFirstTrackOrFail=function(){if(this.failIfClosed(),this.mediaStream.getVideoTracks().length===0)throw"No video tracks found";return this.mediaStream.getVideoTracks()[0]},t.prototype.pause=function(){this.failIfClosed(),this.surface.pause()},t.prototype.resume=function(r){this.failIfClosed();var o=this,c=function(){setTimeout(r,200),o.surface.removeEventListener("playing",c)};this.surface.addEventListener("playing",c),this.surface.play()},t.prototype.isPaused=function(){return this.failIfClosed(),this.surface.paused},t.prototype.getSurface=function(){return this.failIfClosed(),this.surface},t.prototype.getRunningTrackCapabilities=function(){return this.getFirstTrackOrFail().getCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getFirstTrackOrFail().getSettings()},t.prototype.applyVideoConstraints=function(r){return Li(this,void 0,void 0,function(){return Fi(this,function(o){if("aspectRatio"in r)throw"Changing 'aspectRatio' in run-time is not yet supported.";return[2,this.getFirstTrackOrFail().applyConstraints(r)]})})},t.prototype.close=function(){if(this.isClosed)return Promise.resolve();var r=this;return new Promise(function(o,c){var u=r.mediaStream.getVideoTracks(),f=u.length,m=0;r.mediaStream.getVideoTracks().forEach(function(x){r.mediaStream.removeTrack(x),x.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),o())})})},t.prototype.getCapabilities=function(){return new Ew(this.getFirstTrackOrFail())},t})(),Iw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,o,c){return Li(this,void 0,void 0,function(){return Fi(this,function(u){return[2,Aw.create(r,this.mediaStream,o,c)]})})},t.create=function(r){return Li(this,void 0,void 0,function(){var o,c;return Fi(this,function(u){switch(u.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return o={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(o)];case 1:return c=u.sent(),[2,new t(c)]}})})},t})(),pl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function x(C){try{g(c.next(C))}catch(A){m(A)}}function _(C){try{g(c.throw(C))}catch(A){m(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},ml=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Sw=(function(){function t(){}return t.failIfNotSupported=function(){return pl(this,void 0,void 0,function(){return ml(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return pl(this,void 0,void 0,function(){return ml(this,function(o){return[2,Iw.create(r)]})})},t})(),Tw=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(m){m(f)})}return new(o||(o=Promise))(function(f,m){function x(C){try{g(c.next(C))}catch(A){m(A)}}function _(C){try{g(c.throw(C))}catch(A){m(A)}}function g(C){C.done?f(C.value):u(C.value).then(x,_)}g((c=c.apply(t,r||[])).next())})},Nw=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,m;return m={next:x(0),throw:x(1),return:x(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function x(g){return function(C){return _([g,C])}}function _(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(o=0)),o;)try{if(c=1,u&&(f=g[0]&2?u.return:g[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,g[1])).done)return f;switch(u=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return o.label++,{value:g[1],done:!1};case 5:o.label++,u=g[1],g=[0];continue;case 7:g=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){o=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){o.label=g[1];break}if(g[0]===6&&o.label<f[1]){o.label=f[1],f=g;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(g);break}f[2]&&o.ops.pop(),o.trys.pop();continue}g=r.call(t,o)}catch(C){g=[6,C],u=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Ow=(function(){function t(){}return t.retrieve=function(){if(navigator.mediaDevices)return t.getCamerasFromMediaDevices();var r=MediaStreamTrack;return MediaStreamTrack&&r.getSources?t.getCamerasFromMediaStreamTrack():t.rejectWithError()},t.rejectWithError=function(){var r=Ir.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Ir.insecureContextCameraQueryError()),Promise.reject(r)},t.isHttpsOrLocalhost=function(){if(location.protocol==="https:")return!0;var r=location.host.split(":")[0];return r==="127.0.0.1"||r==="localhost"},t.getCamerasFromMediaDevices=function(){return Tw(this,void 0,void 0,function(){var r,o,c,u,f,m,x;return Nw(this,function(_){switch(_.label){case 0:return r=function(g){for(var C=g.getVideoTracks(),A=0,P=C;A<P.length;A++){var O=P[A];O.enabled=!1,O.stop(),g.removeTrack(O)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return o=_.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=_.sent(),u=[],f=0,m=c;f<m.length;f++)x=m[f],x.kind==="videoinput"&&u.push({id:x.deviceId,label:x.label});return r(o),[2,u]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,o){var c=function(f){for(var m=[],x=0,_=f;x<_.length;x++){var g=_[x];g.kind==="video"&&m.push({id:g.id,label:g.label})}r(m)},u=MediaStreamTrack;u.getSources(c)})},t})(),St;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(St||(St={}));var Rw=(function(){function t(){this.state=St.NOT_STARTED,this.onGoingTransactionNewState=St.UNKNOWN}return t.prototype.directTransition=function(r){this.failIfTransitionOngoing(),this.validateTransition(r),this.state=r},t.prototype.startTransition=function(r){return this.failIfTransitionOngoing(),this.validateTransition(r),this.onGoingTransactionNewState=r,this},t.prototype.execute=function(){if(this.onGoingTransactionNewState===St.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=St.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===St.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=St.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==St.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case St.UNKNOWN:throw"Transition from unknown is not allowed";case St.NOT_STARTED:this.failIfNewStateIs(r,[St.PAUSED]);break;case St.SCANNING:break;case St.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,o){for(var c=0,u=o;c<u.length;c++){var f=u[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),kw=(function(){function t(r){this.stateManager=r}return t.prototype.startTransition=function(r){return this.stateManager.startTransition(r)},t.prototype.directTransition=function(r){this.stateManager.directTransition(r)},t.prototype.getState=function(){return this.stateManager.getState()},t.prototype.canScanFile=function(){return this.stateManager.getState()===St.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==St.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===St.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===St.PAUSED},t})(),Mw=(function(){function t(){}return t.create=function(){return new kw(new Rw)},t})(),Dw=(function(){var t=function(r,o){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,u){c.__proto__=u}||function(c,u){for(var f in u)Object.prototype.hasOwnProperty.call(u,f)&&(c[f]=u[f])},t(r,o)};return function(r,o){if(typeof o!="function"&&o!==null)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");t(r,o);function c(){this.constructor=r}r.prototype=o===null?Object.create(o):(c.prototype=o.prototype,new c)}})(),on=(function(t){Dw(r,t);function r(){return t!==null&&t.apply(this,arguments)||this}return r.DEFAULT_WIDTH=300,r.DEFAULT_WIDTH_OFFSET=2,r.FILE_SCAN_MIN_HEIGHT=300,r.FILE_SCAN_HIDDEN_CANVAS_PADDING=100,r.MIN_QR_BOX_SIZE=50,r.SHADED_LEFT=1,r.SHADED_RIGHT=2,r.SHADED_TOP=3,r.SHADED_BOTTOM=4,r.SHADED_REGION_ELEMENT_ID="qr-shaded-region",r.VERBOSE=!1,r.BORDER_SHADER_DEFAULT_COLOR="#ffffff",r.BORDER_SHADER_MATCH_COLOR="rgb(90, 193, 56)",r})(dw),Pw=(function(){function t(r,o){this.logger=o,this.fps=on.SCAN_DEFAULT_FPS,r?(r.fps&&(this.fps=r.fps),this.disableFlip=r.disableFlip===!0,this.qrbox=r.qrbox,this.aspectRatio=r.aspectRatio,this.videoConstraints=r.videoConstraints):this.disableFlip=on.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Xu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Mn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),gl=(function(){function t(r,o){if(this.element=null,this.canvasElement=null,this.scannerPausedUiElement=null,this.hasBorderShaders=null,this.borderShaders=null,this.qrMatch=null,this.renderedCamera=null,this.qrRegion=null,this.context=null,this.lastScanImageFile=null,this.isScanning=!1,!document.getElementById(r))throw"HTML Element with id=".concat(r," not found");this.elementId=r,this.verbose=!1;var c;typeof o=="boolean"?this.verbose=o===!0:o&&(c=o,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new hw(this.verbose),this.qrcode=new _w(this.getSupportedFormats(o),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Mw.create()}return t.prototype.start=function(r,o,c,u){var f=this;if(!r)throw"cameraIdOrConfig is required";if(!c||typeof c!="function")throw"qrCodeSuccessCallback is required and should be a function.";var m;u?m=u:m=this.verbose?this.logger.log:function(){};var x=Pw.create(o,this.logger);this.clearElement();var _=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?_=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=_,C=document.getElementById(this.elementId);C.clientWidth?C.clientWidth:on.DEFAULT_WIDTH,C.style.position="relative",this.shouldScan=!0,this.element=C;var A=this,P=this.stateManagerProxy.startTransition(St.SCANNING);return new Promise(function(O,k){var B=g?x.videoConstraints:A.createVideoConstraints(r);if(!B){P.cancel(),k("videoConstraints should be defined");return}var L={};(!g||x.aspectRatio)&&(L.aspectRatio=x.aspectRatio);var K={onRenderSurfaceReady:function(z,$){A.setupUi(z,$,x),A.isScanning=!0,A.foreverScan(x,c,m)}};Sw.failIfNotSupported().then(function(z){z.create(B).then(function($){return $.render(f.element,L,K).then(function(W){A.renderedCamera=W,P.execute(),O(null)}).catch(function(W){P.cancel(),k(W)})}).catch(function($){P.cancel(),k(Ir.errorGettingUserMedia($))})}).catch(function(z){P.cancel(),k(Ir.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(St.PAUSED),this.showPausedState(),(Mn(r)||r!==!0)&&(r=!1),r&&this.renderedCamera&&this.renderedCamera.pause()},t.prototype.resume=function(){if(!this.stateManagerProxy.isPaused())throw"Cannot result, scanner is not paused.";if(!this.renderedCamera)throw"renderedCamera doesn't exist while trying resume()";var r=this,o=function(){r.stateManagerProxy.directTransition(St.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){o();return}this.renderedCamera.resume(function(){o()})},t.prototype.getState=function(){return this.stateManagerProxy.getState()},t.prototype.stop=function(){var r=this;if(!this.stateManagerProxy.isScanning())throw"Cannot stop, scanner is not running or paused.";var o=this.stateManagerProxy.startTransition(St.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(on.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},u=this;return this.renderedCamera.close().then(function(){return u.renderedCamera=null,u.element&&(u.element.removeChild(u.canvasElement),u.canvasElement=null),c(),u.qrRegion&&(u.qrRegion=null),u.context&&(u.context=null),o.execute(),u.hidePausedState(),u.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,o){return this.scanFileV2(r,o).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,o){var c=this;if(!r||!(r instanceof File))throw"imageFile argument is mandatory and should be instance of File. Use 'event.target.files[0]'.";if(Mn(o)&&(o=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(u,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var x=m.width,_=m.height,g=document.getElementById(c.elementId),C=g.clientWidth?g.clientWidth:on.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:_,on.FILE_SCAN_MIN_HEIGHT),P=c.computeCanvasDrawConfig(x,_,C,A);if(o){var O=c.createCanvasElement(C,A,"qr-canvas-visible");O.style.display="inline-block",g.appendChild(O);var k=O.getContext("2d");if(!k)throw"Unable to get 2d context from canvas";k.canvas.width=C,k.canvas.height=A,k.drawImage(m,0,0,x,_,P.x,P.y,P.width,P.height)}var B=on.FILE_SCAN_HIDDEN_CANVAS_PADDING,L=Math.max(m.width,P.width),K=Math.max(m.height,P.height),z=L+2*B,$=K+2*B,W=c.createCanvasElement(z,$);g.appendChild(W);var X=W.getContext("2d");if(!X)throw"Unable to get 2d context from canvas";X.canvas.width=z,X.canvas.height=$,X.drawImage(m,0,0,x,_,B,B,L,K);try{c.qrcode.decodeRobustlyAsync(W).then(function(H){u(ll.createFromQrcodeResult(H))}).catch(f)}catch(H){f("QR code parse error, error = ".concat(H))}},m.onerror=f,m.onabort=f,m.onstalled=f,m.onsuspend=f,m.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Ow.retrieve()},t.prototype.getRunningTrackCapabilities=function(){return this.getRenderedCameraOrFail().getRunningTrackCapabilities()},t.prototype.getRunningTrackSettings=function(){return this.getRenderedCameraOrFail().getRunningTrackSettings()},t.prototype.getRunningTrackCameraCapabilities=function(){return this.getRenderedCameraOrFail().getCapabilities()},t.prototype.applyVideoConstraints=function(r){if(r){if(!Xu.isMediaStreamConstraintsValid(r,this.logger))throw"invalid videoConstaints passed, check logs for more details"}else throw"videoConstaints is required argument.";return this.getRenderedCameraOrFail().applyVideoConstraints(r)},t.prototype.getRenderedCameraOrFail=function(){if(this.renderedCamera==null)throw"Scanning is not in running state, call this API only when QR code scanning using camera is in running state.";return this.renderedCamera},t.prototype.getSupportedFormats=function(r){var o=[ve.QR_CODE,ve.AZTEC,ve.CODABAR,ve.CODE_39,ve.CODE_93,ve.CODE_128,ve.DATA_MATRIX,ve.MAXICODE,ve.ITF,ve.EAN_13,ve.EAN_8,ve.PDF_417,ve.RSS_14,ve.RSS_EXPANDED,ve.UPC_A,ve.UPC_E,ve.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return o;if(!Array.isArray(r.formatsToSupport))throw"configOrVerbosityFlag.formatsToSupport should be undefined or an array.";if(r.formatsToSupport.length===0)throw"Atleast 1 formatsToSupport is needed.";for(var c=[],u=0,f=r.formatsToSupport;u<f.length;u++){var m=f[u];uw(m)?c.push(m):this.logger.warn("Invalid format: ".concat(m," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(Mn(r))return!0;if(!Mn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Mn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Mn(o.useBarCodeDetectorIfSupported)?!0:o.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,o,c){var u=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,o,f),x=function(g){if(g<on.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(on.MIN_QR_BOX_SIZE,"px.")},_=function(g){return g>r&&(u.logger.warn("`qrbox.width` or `qrbox` is larger than the width of the root element. The width will be truncated to the width of root element."),g=r),g};x(m.width),x(m.height),m.width=_(m.width)},t.prototype.validateQrboxConfig=function(r){if(typeof r!="number"&&typeof r!="function"&&(r.width===void 0||r.height===void 0))throw"Invalid instance of QrDimensions passed for 'config.qrbox'. Both 'width' and 'height' should be set."},t.prototype.toQrdimensions=function(r,o,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,o)}catch(u){throw new Error("qrbox config was passed as a function but it failed with unknown error"+u)}return c},t.prototype.setupUi=function(r,o,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,o,c);var u=Mn(c.qrbox)?{width:r,height:o}:c.qrbox;this.validateQrboxConfig(u);var f=this.toQrdimensions(r,o,u);f.height>o&&this.logger.warn("[Html5Qrcode] config.qrbox has height that isgreater than the height of the video stream. Shading will be ignored");var m=c.isShadedBoxEnabled()&&f.height<=o,x={x:0,y:0,width:r,height:o},_=m?this.getShadedRegionBounds(r,o,f):x,g=this.createCanvasElement(_.width,_.height),C={willReadFrequently:!0},A=g.getContext("2d",C);A.canvas.width=_.width,A.canvas.height=_.height,this.element.append(g),m&&this.possiblyInsertShadingElement(this.element,r,o,f),this.createScannerPausedUiElement(this.element),this.qrRegion=_,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var o=document.createElement("div");o.innerText=Ir.scannerPaused(),o.style.display="none",o.style.position="absolute",o.style.top="0px",o.style.zIndex="1",o.style.background="rgba(9, 9, 9, 0.46)",o.style.color="#FFECEC",o.style.textAlign="center",o.style.width="100%",r.appendChild(o),this.scannerPausedUiElement=o},t.prototype.scanContext=function(r,o){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(u){return r(u.text,ll.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Ir.codeParseError(u);return o(f,fw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,o,c){var u=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),m=f.videoWidth/f.clientWidth,x=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var _=this.qrRegion.width*m,g=this.qrRegion.height*x,C=this.qrRegion.x*m,A=this.qrRegion.y*x;this.context.drawImage(f,C,A,_,g,0,0,this.qrRegion.width,this.qrRegion.height);var P=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(O){!O&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){P()})):P()}).catch(function(O){u.logger.logError("Error happend while scanning context",O),P()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var o="facingMode",c="deviceId",u={user:!0,environment:!0},f="exact",m=function(k){if(k in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(k,"'")},x=Object.keys(r);if(x.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(x.length," keys");var _=Object.keys(r)[0];if(_!==o&&_!==c)throw"Only '".concat(o,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(_===o){var g=r.facingMode;if(typeof g=="string"){if(m(g))return{facingMode:g}}else if(typeof g=="object")if(f in g){if(m(g["".concat(f)]))return{facingMode:{exact:g["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var C=typeof g;throw"Invalid type of 'facingMode' = ".concat(C)}}else{var A=r.deviceId;if(typeof A=="string")return{deviceId:A};if(typeof A=="object"){if(f in A)return{deviceId:{exact:A["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var P=typeof A;throw"Invalid type of 'deviceId' = ".concat(P)}}}var O=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(O)},t.prototype.computeCanvasDrawConfig=function(r,o,c,u){if(r<=c&&o<=u){var f=(c-r)/2,m=(u-o)/2;return{x:f,y:m,width:r,height:o}}else{var x=r,_=o;return r>c&&(o=c/r*o,r=c),o>u&&(r=u/o*r,o=u),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(_)+" to ".concat(r,"X").concat(o,".")),this.computeCanvasDrawConfig(r,o,c,u)}},t.prototype.clearElement=function(){if(this.stateManagerProxy.isScanning())throw"Cannot clear while scan is ongoing, close it first.";var r=document.getElementById(this.elementId);r&&(r.innerHTML="")},t.prototype.possiblyUpdateShaders=function(r){this.qrMatch!==r&&(this.hasBorderShaders&&this.borderShaders&&this.borderShaders.length&&this.borderShaders.forEach(function(o){o.style.backgroundColor=r?on.BORDER_SHADER_MATCH_COLOR:on.BORDER_SHADER_DEFAULT_COLOR}),this.qrMatch=r)},t.prototype.possiblyCloseLastScanImageFile=function(){this.lastScanImageFile&&(URL.revokeObjectURL(this.lastScanImageFile),this.lastScanImageFile=null)},t.prototype.createCanvasElement=function(r,o,c){var u=r,f=o,m=document.createElement("canvas");return m.style.width="".concat(u,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=Mn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,o,c){if(c.width>r||c.height>o)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(o-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,o,c,u){if(!(o-u.width<1||c-u.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(o-u.width)/2,x=(c-u.height)/2;if(f.style.borderLeft="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(x,"px solid rgba(0, 0, 0, 0.48)"),f.style.boxSizing="border-box",f.style.top="0px",f.style.bottom="0px",f.style.left="0px",f.style.right="0px",f.id="".concat(on.SHADED_REGION_ELEMENT_ID),o-u.width<11||c-u.height<11)this.hasBorderShaders=!1;else{var _=5,g=40;this.insertShaderBorders(f,g,_,-_,null,0,!0),this.insertShaderBorders(f,g,_,-_,null,0,!1),this.insertShaderBorders(f,g,_,null,-_,0,!0),this.insertShaderBorders(f,g,_,null,-_,0,!1),this.insertShaderBorders(f,_,g+_,-_,null,-_,!0),this.insertShaderBorders(f,_,g+_,null,-_,-_,!0),this.insertShaderBorders(f,_,g+_,-_,null,-_,!1),this.insertShaderBorders(f,_,g+_,null,-_,-_,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,o,c,u,f,m,x){var _=document.createElement("div");_.style.position="absolute",_.style.backgroundColor=on.BORDER_SHADER_DEFAULT_COLOR,_.style.width="".concat(o,"px"),_.style.height="".concat(c,"px"),u!==null&&(_.style.top="".concat(u,"px")),f!==null&&(_.style.bottom="".concat(f,"px")),x?_.style.left="".concat(m,"px"):_.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(_),r.appendChild(_)},t.prototype.showPausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="block"},t.prototype.hidePausedState=function(){if(!this.scannerPausedUiElement)throw"[internal error] scanner paused UI element not found";this.scannerPausedUiElement.style.display="none"},t.prototype.getTimeoutFps=function(r){return 1e3/r},t})(),xl;(function(t){t[t.STATUS_DEFAULT=0]="STATUS_DEFAULT",t[t.STATUS_SUCCESS=1]="STATUS_SUCCESS",t[t.STATUS_WARNING=2]="STATUS_WARNING",t[t.STATUS_REQUESTING_PERMISSION=3]="STATUS_REQUESTING_PERMISSION"})(xl||(xl={}));const Bw={class:"scan-code"},Lw={class:"btn"},Fw={class:"left-back"},Uw=v.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=Nd.IconScan(),u=v.reactive({html5QrCode:null}),f=v.ref(!1),m=()=>{if(!u.html5QrCode){et("摄像头无访问权限!");return}f.value=!0,u.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[ti.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const O=new URL(A).searchParams.get("sessionId");O?o("scanSuccess",O):et("无效的二维码")}catch{et("无效的二维码")}C()}).catch(A=>{console.log(A),et({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},_=()=>{C()},g=()=>gl.getCameras().then(A=>{A&&A.length&&(u.html5QrCode=new gl("reader"))}).catch(()=>{et({message:"摄像头无访问权限!",duration:3e3})}),C=()=>{u.html5QrCode&&u.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),et("停止扫码失败")}).finally(()=>{f.value=!1})};return v.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&C()}),(A,P)=>{const O=os;return v.openBlock(),v.createElementBlock("div",null,[v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(c),size:"28",svgSize:"20",onClick:P[0]||(P[0]=k=>x())},null,8,["icon"]),(v.openBlock(),v.createBlock(v.Teleport,{to:"body"},[v.withDirectives(v.createElementVNode("div",Bw,[P[1]||(P[1]=v.createElementVNode("div",{class:"container"},[v.createElementVNode("div",{class:"qrcode"},[v.createElementVNode("div",{id:"reader"})])],-1)),v.createElementVNode("div",Lw,[v.createElementVNode("div",Fw,[v.createVNode(O,{name:"arrow-left",onClick:_})])])],512),[[v.vShow,f.value]])]))])}}}),zw=Kn(Uw,[["__scopeId","data-v-2d988579"]]);function as(t,r,o){const c=v.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const C=c.value;if(C.length===0)return"";if(r){const P=typeof r=="string"?r:r.value;if(P&&C.some(O=>O.id===P))return P}const A=C.find(P=>P.isDefault);return A?A.id:C[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(C=>C.id===f.value))&&(f.value=u());else{let C;r&&typeof r=="string"&&(C=r),f=v.ref(C&&c.value.some(A=>A.id===C)?C:u())}(!m||o)&&v.watch(f,C=>{o&&o(C)});const x=v.computed(()=>c.value.find(C=>C.id===f.value)),_=v.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:_,setSelectedModel:C=>{c.value.find(P=>P.id===C)?f.value=C:console.warn(`[useModel] Model not found: ${C}`)}}}const $w=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Vw=Object.prototype.toString,Zw=t=>Vw.call(t)==="[object Object]",Ti=()=>{};function Co(t){return Array.isArray(t)?t:[t]}function jw(t,r,o){return v.watch(t,r,{...o,immediate:!0})}const Yu=$w?window:void 0;function Gr(t){var r;const o=v.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function bo(...t){const r=(c,u,f,m)=>(c.addEventListener(u,f,m),()=>c.removeEventListener(u,f,m)),o=v.computed(()=>{const c=Co(v.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return jw(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>Gr(f)))!==null&&c!==void 0?c:[Yu].filter(f=>f!=null),Co(v.toValue(o.value?t[1]:t[0])),Co(v.unref(o.value?t[2]:t[1])),v.toValue(o.value?t[3]:t[2])]},([c,u,f,m],x,_)=>{if(!c?.length||!u?.length||!f?.length)return;const g=Zw(m)?{...m}:m,C=c.flatMap(A=>u.flatMap(P=>f.map(O=>r(A,P,O,g))));_(()=>{C.forEach(A=>A())})},{flush:"post"})}function Ww(t,r,o={}){const{window:c=Yu,ignore:u=[],capture:f=!0,detectIframe:m=!1,controls:x=!1}=o;if(!c)return x?{stop:Ti,cancel:Ti,trigger:Ti}:Ti;let _=!0;const g=L=>v.toValue(u).some(K=>{if(typeof K=="string")return Array.from(c.document.querySelectorAll(K)).some(z=>z===L.target||L.composedPath().includes(z));{const z=Gr(K);return z&&(L.target===z||L.composedPath().includes(z))}});function C(L){const K=v.toValue(L);return K&&K.$.subTree.shapeFlag===16}function A(L,K){const z=v.toValue(L),$=z.$.subTree&&z.$.subTree.children;return $==null||!Array.isArray($)?!1:$.some(W=>W.el===K.target||K.composedPath().includes(W.el))}const P=L=>{const K=Gr(t);if(L.target!=null&&!(!(K instanceof Element)&&C(t)&&A(t,L))&&!(!K||K===L.target||L.composedPath().includes(K))){if("detail"in L&&L.detail===0&&(_=!g(L)),!_){_=!0;return}r(L)}};let O=!1;const k=[bo(c,"click",L=>{O||(O=!0,setTimeout(()=>{O=!1},0),P(L))},{passive:!0,capture:f}),bo(c,"pointerdown",L=>{const K=Gr(t);_=!g(L)&&!!(K&&!L.composedPath().includes(K))},{passive:!0}),m&&bo(c,"blur",L=>{setTimeout(()=>{var K;const z=Gr(t);((K=c.document.activeElement)===null||K===void 0?void 0:K.tagName)==="IFRAME"&&!z?.contains(c.document.activeElement)&&r(L)},0)},{passive:!0})].filter(Boolean),B=()=>k.forEach(L=>L());return x?{stop:B,cancel:()=>{_=!1},trigger:L=>{_=!0,P(L),_=!1}}:B}const Hw=["data-active","disabled"],Gw=v.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,o)=>(v.openBlock(),v.createElementBlock("button",{class:v.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[v.renderSlot(r.$slots,"default",{},void 0,!0)],10,Hw))}}),ls=Kn(Gw,[["__scopeId","data-v-6f582cce"]]),Xw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function qw(t,r){return v.openBlock(),v.createElementBlock("svg",Xw,[...r[0]||(r[0]=[v.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),v.createElementVNode("path",{id:"矢量 90",d:"M13.683 2.26904C12.5753 1.16177 10.344 1.47577 8.02582 2.86527C5.70758 1.47576 3.47637 1.16179 2.36913 2.26904C1.2619 3.37646 1.57573 5.60771 2.96524 7.92589C1.57573 10.2441 1.2619 12.4754 2.36913 13.5827C3.47637 14.6901 5.7078 14.3762 8.02599 12.9867C10.344 14.3762 12.5752 14.6901 13.6825 13.5827C14.7901 12.4754 14.4761 10.2441 13.0866 7.92594C14.4761 5.60775 14.7902 3.37646 13.683 2.26904ZM10.8544 5.09764C11.4667 5.70995 12.0076 6.34819 12.4699 6.99044C12.7244 6.52061 12.9268 6.06037 13.077 5.60959C13.2948 4.95652 13.3832 4.38597 13.3426 3.89769C13.3089 3.49437 13.1869 3.18725 12.9754 2.97631C12.7645 2.76513 12.4574 2.64282 12.0541 2.60912C11.5658 2.56835 10.9955 2.65698 10.3422 2.87475C9.89153 3.02497 9.43121 3.22735 8.96135 3.48197C9.60365 3.94428 10.242 4.48527 10.8544 5.09764ZM5.70991 2.87475C6.16049 3.02494 6.62073 3.22729 7.09051 3.48185C6.44826 3.94412 5.81002 4.48507 5.19771 5.09739C4.58523 5.70982 4.04417 6.34819 3.58181 6.99055C3.32716 6.52071 3.1248 6.06037 2.97459 5.60959C2.75682 4.95677 2.66844 4.38597 2.70897 3.89769C2.74266 3.49437 2.86522 3.18725 3.07615 2.97631C3.28709 2.76513 3.59421 2.64282 3.99753 2.60912C4.4858 2.5686 5.0566 2.65698 5.70991 2.87475ZM5.90473 5.80466Q4.89236 6.81738 4.14938 7.92595C4.64428 8.66515 5.2294 9.3722 5.90473 10.0473C6.57966 10.7222 7.28696 11.3074 8.02584 11.8027C8.76507 11.3074 9.47197 10.7222 10.1474 10.0473C10.8222 9.37218 11.4074 8.66511 11.9027 7.92588Q11.1597 6.81736 10.1474 5.80466C9.47203 5.12956 8.7652 4.54447 8.02604 4.04937C7.28683 4.54447 6.5796 5.12956 5.90473 5.80466ZM7.99992 6.90011C7.44768 6.90011 6.99993 7.34787 6.99993 7.90011C6.99993 8.45235 7.44768 8.9001 7.99992 8.9001C8.55216 8.9001 8.99991 8.45235 8.99991 7.90011C8.99991 7.34787 8.55216 6.90011 7.99992 6.90011ZM10.3422 12.9772C9.89161 12.827 9.43138 12.6246 8.96148 12.37C9.60377 11.9077 10.242 11.3667 10.8544 10.7543C11.4667 10.142 12.0077 9.50369 12.4699 8.8614C12.7245 9.33127 12.9268 9.79154 13.077 10.2421C13.2948 10.8952 13.3832 11.4658 13.3426 11.954C13.3089 12.3574 13.1864 12.6647 12.9754 12.8757C12.7645 13.0866 12.4574 13.2089 12.0541 13.2426C11.5658 13.2834 10.995 13.195 10.3422 12.9772ZM2.97459 10.2421C3.12478 9.7914 3.32733 9.3312 3.58196 8.86141C4.04428 9.50369 4.5853 10.142 5.19771 10.7543C5.81003 11.3667 6.44827 11.9077 7.09052 12.37C6.62074 12.6246 6.16049 12.827 5.70991 12.9772C5.0566 13.195 4.48629 13.2834 3.99802 13.2426C3.5947 13.2089 3.28709 13.0866 3.07615 12.8757C2.86522 12.6647 2.74315 12.3574 2.70946 11.954C2.66844 11.4658 2.75682 10.8952 2.97459 10.2421Z",fill:"rgb(89,89,89)","fill-rule":"evenodd"},null,-1)])])}const Yw={render:qw},Jw={class:"button-text"},Kw={class:"dropdown-menu__items"},Qw=["onClick"],e3=v.defineComponent({__name:"ModelSwitch",props:v.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,o=v.useModel(t,"selectedModelId"),c=r.modelConfigs?Array.isArray(r.modelConfigs)?v.shallowRef(r.modelConfigs):r.modelConfigs:void 0,{selectedModel:u,availableModels:f,setSelectedModel:m}=as(c,o),x=v.ref(!1),_=O=>{m(O),C()},g=()=>{x.value=!x.value},C=()=>{x.value=!1},A=v.ref(null),P=v.ref(null);return Ww(P,()=>{C()},{ignore:[A]}),(O,k)=>(v.openBlock(),v.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[v.createVNode(ls,{size:"small",class:"action-button",rounded:"",onClick:g},{default:v.withCtx(()=>[(v.openBlock(),v.createBlock(v.resolveDynamicComponent(v.unref(u)?.icon),{width:16,height:16,class:"selected-model__icon"})),v.createElementVNode("span",Jw,v.toDisplayString(v.unref(u)?.label),1),v.createVNode(v.unref(Yw),{width:16,height:16})]),_:1}),v.createVNode(v.Transition,{name:"dropdown"},{default:v.withCtx(()=>[x.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:P},[v.createElementVNode("div",Kw,[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(v.unref(f),B=>(v.openBlock(),v.createElementBlock("div",{key:B.id,class:v.normalizeClass(["dropdown-menu__item",{"active-menu":B.id===o.value}]),onClick:v.withModifiers(L=>_(B.id),["stop"])},[B.icon?(v.openBlock(),v.createBlock(v.resolveDynamicComponent(B.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):v.createCommentVNode("",!0),v.createElementVNode("span",null,v.toDisplayString(B.label),1)],10,Qw))),128))])],512)):v.createCommentVNode("",!0)]),_:1}),x.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:C})):v.createCommentVNode("",!0)],512))}}),t3=Kn(e3,[["__scopeId","data-v-cee7e07b"]]),n3={key:0,class:"active-count"},r3=v.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,o=v.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,u)=>(v.openBlock(),v.createBlock(ls,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:v.withCtx(()=>[v.createVNode(v.unref(Sr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=v.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(v.openBlock(),v.createElementBlock("span",n3,v.toDisplayString(o.value),1)):v.createCommentVNode("",!0)]),_:1},8,["active"]))}}),i3=Kn(r3,[["__scopeId","data-v-c2a16c66"]]),o3={"data-v-99394ae9":"",viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",width:"16.000000",height:"16.000000",fill:"none",customFrame:"#000000",size:"16"};function s3(t,r){return v.openBlock(),v.createElementBlock("svg",o3,[...r[0]||(r[0]=[v.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),v.createElementVNode("path",{id:"矢量 154",d:"M7.41014 2.09741L7.67112 2.70606C7.68333 2.73438 7.70579 2.75684 7.73411 2.76905L8.34275 3.02979C8.43968 3.0713 8.43968 3.20875 8.34275 3.25025L7.73411 3.51124C7.70579 3.52345 7.68333 3.54591 7.67112 3.57423L7.41014 4.18288C7.36863 4.2798 7.23118 4.2798 7.18968 4.18288L6.92894 3.57423C6.91673 3.54591 6.89427 3.52345 6.86595 3.51124L6.25731 3.25025C6.16039 3.20875 6.16039 3.0713 6.25731 3.02979L6.86595 2.76905C6.89427 2.75684 6.91673 2.73438 6.92894 2.70606L7.18968 2.09741C7.23118 2.00049 7.36863 2.00049 7.41014 2.09741ZM4.57006 11.9625L7.27611 8.09746L9.69944 4.63674L10.592 3.36207C10.6899 3.22218 10.8017 3.09864 10.9272 2.99122C11.0529 2.88404 11.1926 2.79297 11.3459 2.71802C11.4992 2.64332 11.657 2.58936 11.8191 2.5564C11.9809 2.52369 12.1472 2.51172 12.3176 2.52051C12.5315 2.53174 12.7336 2.57373 12.9238 2.64649C13.0678 2.70118 13.205 2.77369 13.3354 2.86353C13.4651 2.95289 13.5813 3.05445 13.6836 3.16822C13.8064 3.3047 13.9094 3.45851 13.9929 3.6299C14.0766 3.80128 14.1342 3.97731 14.1662 4.15773C14.1928 4.30861 14.2014 4.46267 14.1919 4.61989C14.1823 4.7781 14.1547 4.93069 14.1096 5.07791C14.0495 5.27249 13.958 5.45755 13.8352 5.63309L7.81321 14.2335Q7.66985 14.4382 7.48649 14.5965Q7.4825 14.6 7.4785 14.6034Q7.29063 14.7641 7.06102 14.8766C6.90794 14.9513 6.75072 15.0052 6.5891 15.0384C6.42748 15.0714 6.2617 15.0836 6.09154 15.0751C5.87743 15.0643 5.67504 15.0226 5.48436 14.9503C5.34008 14.8956 5.20287 14.8233 5.07201 14.7335C4.94213 14.6444 4.82592 14.5428 4.72313 14.4291C4.60033 14.2928 4.49682 14.1388 4.41308 13.9674C4.32934 13.7958 4.27123 13.6197 4.23925 13.4391C4.21239 13.2882 4.20385 13.1339 4.21313 12.9767C4.22265 12.8184 4.24999 12.6656 4.2954 12.5184C4.35546 12.3233 4.44701 12.138 4.57006 11.9625ZM4.7185 4.67361L4.18383 3.42579C4.11449 3.26441 3.88549 3.26441 3.81616 3.42579L3.28149 4.67361C3.26123 4.72073 3.22363 4.75832 3.17651 4.77859L1.92871 5.31326C1.76733 5.3826 1.76733 5.6116 1.92871 5.68094L3.17651 6.21561C3.22363 6.23587 3.26123 6.27347 3.28149 6.32059L3.81616 7.56841C3.88549 7.73003 4.11449 7.73003 4.18383 7.56841L4.7185 6.32059C4.73876 6.27347 4.77636 6.23587 4.82348 6.21561L6.07128 5.68094C6.23265 5.6116 6.23265 5.3826 6.07128 5.31326L4.82348 4.77859C4.77636 4.75832 4.73876 4.72073 4.7185 4.67361ZM5.38915 12.536C5.32006 12.6346 5.27099 12.7384 5.24169 12.8475C5.22533 12.9088 5.21532 12.9718 5.21141 13.0362C5.20726 13.1063 5.21044 13.1751 5.22094 13.2428C5.23583 13.3402 5.2661 13.4354 5.31151 13.5282C5.35692 13.6209 5.41332 13.7032 5.48095 13.775C5.52806 13.8248 5.58031 13.8695 5.63817 13.9093C5.69139 13.9459 5.7473 13.9764 5.80565 14.0011C5.9099 14.0453 6.02196 14.0702 6.14208 14.0763C6.2263 14.0807 6.30834 14.0746 6.38841 14.0582C6.46825 14.0418 6.54613 14.015 6.62181 13.9781C6.69749 13.941 6.76634 13.8961 6.8286 13.8429C6.89061 13.7899 6.94578 13.7289 6.99412 13.6598L11.9415 6.59405L10.3381 5.46789L5.38915 12.536ZM10.9168 4.6415L12.5202 5.76762L13.0161 5.05935C13.0849 4.96096 13.134 4.85745 13.1633 4.74831C13.1797 4.68703 13.1897 4.62429 13.1936 4.55959C13.198 4.48977 13.1948 4.42092 13.1843 4.35329C13.1694 4.25588 13.1394 4.16091 13.0942 4.06813C13.0488 3.97536 12.9926 3.89308 12.925 3.8213C12.8781 3.7715 12.8259 3.72682 12.7683 3.68703C12.7148 3.6504 12.6591 3.61964 12.6008 3.59474C12.4968 3.55079 12.385 3.5254 12.2651 3.5193C12.1806 3.51466 12.0984 3.52076 12.0183 3.53688C11.9382 3.55324 11.8601 3.57985 11.7841 3.61696C11.7082 3.65407 11.6391 3.69899 11.5771 3.75221C11.5149 3.80519 11.4594 3.86647 11.4111 3.93556L10.9168 4.6415Z",fill:"currentColor","fill-rule":"evenodd"},null,-1)])])}const a3={render:s3},l3=v.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=v.useModel(t,"genuiEnabled"),o=()=>{r.value=!r.value};return(c,u)=>(v.openBlock(),v.createBlock(ls,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:v.withCtx(()=>[v.createVNode(v.unref(a3),{width:16,height:16}),u[0]||(u[0]=v.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),c3=Kn(l3,[["__scopeId","data-v-7f3b0372"]]),u3={class:"bubble-image-wrapper"},d3=["src"],f3=["src"],h3=v.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=v.ref(!1),o=v.ref(null),c=()=>{r.value=!0},u=()=>{r.value=!1};return v.watch(r,f=>{f&&v.nextTick(()=>{o.value?.focus()})}),(f,m)=>(v.openBlock(),v.createElementBlock("div",u3,[v.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,d3),(v.openBlock(),v.createBlock(v.Teleport,{to:"body"},[r.value?(v.openBlock(),v.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:u,onKeydown:v.withKeys(u,["esc"])},[v.createElementVNode("button",{ref_key:"closeButtonRef",ref:o,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:u},[...m[1]||(m[1]=[v.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[v.createElementVNode("path",{d:"M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z",fill:"currentColor"})],-1)])],512),v.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=v.withModifiers(()=>{},["stop"]))},[v.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,f3)])],32)):v.createCommentVNode("",!0)]))]))}}),p3=Kn(h3,[["__scopeId","data-v-91c75579"]]),Zr="https://agent.opentiny.design",m3=[{id:"12306-mcp",name:"12306服务器",description:"12306购票搜索服务器",icon:"https://agent.opentiny.design/public-assets/icons/icon-12306.webp",enabled:!1,addState:"idle",tools:[],url:Zr+"/api/v1/mcp-server/12306/mcp",type:"StreamableHTTP"},{id:"markdown2pdf-mcp",name:"Markdown转PDF MCP服务器",description:"Markdown转PDF MCP服务器,可以将Markdown文件转换为PDF文件",icon:"https://agent.opentiny.design/public-assets/icons/icon-pdf.png",url:Zr+"/servers/markdown2pdf-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"docx-mcp",name:"Word文档MCP服务器",description:"Word文档MCP服务器,可以创建、编辑、保存Word文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-word.png",url:Zr+"/servers/excel-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"excel-mcp",name:"Excel文档MCP服务器",description:"Excel文档MCP服务器,可以创建、编辑、保存Excel文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-excel.png",url:Zr+"/servers/excel-mcp/mcp",type:"StreamableHTTP",enabled:!1,addState:"idle",tools:[]},{id:"doc-tools-mcp",name:"文档工具MCP服务器",description:"文档工具MCP服务器,可以创建、编辑、保存文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-doc.png",url:Zr+"/servers/doc-tools-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]}],g3=`
|
|
79
79
|
<svg width="1em" height="1em" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
|
|
80
80
|
<defs>
|
|
81
81
|
<clipPath id="clip657_188316">
|
|
@@ -88,4 +88,4 @@ ${this.tempPrompt}
|
|
|
88
88
|
<path id="path" d="M1.25 9.97C1.25 9.63 1.53 9.35 1.87 9.35L4.37 9.35C4.72 9.35 5 9.63 5 9.97C5 10.32 4.72 10.6 4.37 10.6L1.87 10.6C1.53 10.6 1.25 10.32 1.25 9.97ZM12.5 6.25C12.5 5.9 12.78 5.62 13.12 5.62L17.46 5.62C17.8 5.62 18.08 5.9 18.08 6.25C18.08 6.59 17.8 6.87 17.46 6.87L13.12 6.87C12.78 6.87 12.5 6.59 12.5 6.25ZM12.5 13.73C12.5 13.39 12.78 13.11 13.12 13.11L17.46 13.11C17.8 13.11 18.08 13.39 18.08 13.73C18.08 14.08 17.8 14.36 17.46 14.36L13.12 14.36C12.78 14.36 12.5 14.08 12.5 13.73Z" fill="currentColor" fill-opacity="1" fill-rule="nonzero"></path>
|
|
89
89
|
</g>
|
|
90
90
|
</svg>
|
|
91
|
-
`,x3=btoa(g3),yl=`data:image/svg+xml;base64,${x3}`,Eo=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},y3=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},o=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(Eo)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(Eo)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(Eo)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:v.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:v.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:v.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:o,promptItems:c}},wl={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},w3=t=>{console.log("message",t);const r=Object.keys(wl),o=r.findIndex(u=>t.includes(u));return(o!==-1?wl[r[o]]:t)||t},_3={class:"tr-container__title"},v3={style:{flex:"1"}},C3={class:"chat-input"},b3={class:"chat-input-pills"},E3={class:"attachments-container"},A3={class:"action-buttons"},I3=v.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:v.mergeModels({sessionId:{type:String,default:void 0},agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},remoteUrl:{type:String},menuItems:{type:Array},qrCodeUrl:{type:String},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:v.h(Sr.IconUser,{style:{fontSize:"32px"}}),assistant:v.h(Hu,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},pageToolsOnDemand:{type:Boolean,default:!1}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"],setup(t,{expose:r}){const o=t,c=v.useModel(t,"fullscreen"),u=v.useModel(t,"show"),f=v.useModel(t,"selectedModelId"),p=v.useModel(t,"genUiAble"),x=v.useModel(t,"enabledTools"),_=o.llmConfigs?v.toRef(o,"llmConfigs"):void 0,{selectedModel:g}=as(_,f),C=v.computed(()=>{const Ie=_?.value?.length?g.value:o.llmConfig;return Ie?!!(Ie.baseURL&&Ie.genuiUrl):!1}),{hasMultimodalSupport:A,attachments:B,onFilesSelected:O,checkCanSendAttachments:k,processAttachments:P,cleanupAttachments:L}=cw({selectedModel:g,selectedModelId:f}),{agent:Y,customAgentProvider:Z,conversationState:$,messages:H,messageState:re,inputMessage:j,abortRequest:V,senderRef:z,sendMessage:M,handleSendMessage:we,addMessage:le,send:fe,createConversation:ae,switchConversation:X,deleteConversation:D,getCurrentConversation:K}=Sx({systemPrompt:o.systemPrompt||"",llmConfig:o.llmConfig});v.watch(()=>o.systemPrompt,Ie=>{Z.promptManager.setStatic(Ie)}),Z.isGenuiEnabled=p,Z.debugStream=o.debugStream,v.watch(()=>o.pageToolsOnDemand,Ie=>{Z.pageToolsOnDemand=Ie},{immediate:!0});const W=v.toRef(o,"skills"),{processSkillMentions:ee}=qy({skillsRef:W,customAgentProvider:Z}),he=async(Ie,oe)=>we(Ie,oe,ee),{welcomeIcon:ge,roles:de}=tw({props:o,messages:H,messageState:re,inputMessage:j,handleSendMessage:he}),{showHistory:Ce,handleCreateConversation:Ve,handleHistorySelect:Me,handleHistoryUpdateTitle:Ye,handleHistoryDelete:ie}=nw({createConversation:ae,switchConversation:X,deleteConversation:D,getCurrentConversation:K,abortRequest:V,conversationState:$,customAgentProvider:Z}),ke=()=>{if(g.value){const Ie=g.value;Z.updateLLMConfig({model:Ie.model||"",baseURL:Ie.baseURL||"",genuiUrl:Ie.genuiUrl||"",apiKey:Ie.apiKey||"",providerType:Ie.providerType,useReActMode:Ie.useReActMode,llm:Ie.llm,providerOptions:Ie.providerOptions,headers:Ie.headers})}else Z.updateLLMConfig(Z.llmConfig)};o.llmConfigs&&v.watch(g,ke,{immediate:!0}),v.watch(p,ke,{immediate:!0});const Ae={markdown:new Pt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ie=>v.h(Sd.GenuiRenderer,{...Ie,customActions:{continueChat:{execute:(oe,Re)=>{const qe=typeof oe=="string"?oe:oe.message,pt=`${qe},相关参数为:${JSON.stringify(Re?.state||{})}`;le({role:"user",content:pt,uiContent:[{type:"markdown",content:qe}]}),fe()}}},generating:Hn.GeneratingStatus.includes(re.status),customComponents:o.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:p3},{installedPlugins:Ne,marketPlugins:ot,pluginVisible:Xe,loadMcpServerToPlugin:$t,togglePlugin:Ue,toggleTool:pn,deletePlugin:Vt,addPluginCore:bn,addPluginFromMarket:wt,addPluginFromScan:Je,handleClientDisconnected:je,searchPlugin:En}=Xy(Y,x,yl);Xm({enabled:v.toRef(o,"pageToolsOnDemand"),agent:Y,installedPlugins:Ne,customAgentProvider:Z}),ot.value=[...m3,...o.customMarketMcpServers];const T=v.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),{lang:pe,pillItems:_t,promptItems:vt}=y3(o),{handleScanSuccess:Un,handleSessionIdInput:nn,initialize:ai}=rw({sessionId:v.toRef(o,"sessionId"),agentRoot:o.agentRoot,mode:o.mode,qrCodeUrl:o.qrCodeUrl,remoteUrl:o.remoteUrl,menuItems:o.menuItems,AILogoUrl:o.AILogoUrl,show:u,addPluginFromScan:Je,inputMessage:j}),An=async Ie=>{if(await nn(j.value)||!k())return;const Re=await P();try{await he(Ie,Re),L()}catch(qe){console.error("发送消息失败:",qe)}},Lt=v.computed(()=>Hn.GeneratingStatus.includes(re.status)?pe[o.locale].thinking:pe[o.locale].placeholder),li=v.computed(()=>Hn.GeneratingStatus.includes(re.status)),pr=Ie=>{j.value=Ie.inputMessage};ai(),v.onMounted(async()=>{Ve(),Y.onError=oe=>{oe&&et(w3(oe))};const Ie=ot.value.filter(oe=>oe.addState==="added"&&oe.enabled);for(const oe of Ie)await wt(oe);if(o.mcpServers)for(const[oe,Re]of Object.entries(o.mcpServers))await $t(oe,Re)});const{handleCustomAdd:Wi}=Gy(Y,Ne,yl);return r({agent:Y,welcomeIcon:ge,messages:H,messageState:re,roles:de,inputMessage:j,senderRef:z,abortRequest:V,sendMessage:M,loadMcpServerToPlugin:$t,handleClientDisconnected:je,addMessage:le,installedPlugins:Ne,addPluginCore:bn,deletePlugin:Vt}),(Ie,oe)=>(v.openBlock(),v.createBlock(v.unref(Pt.TrContainer),{show:u.value,"onUpdate:show":oe[11]||(oe[11]=Re=>u.value=Re),fullscreen:c.value,"onUpdate:fullscreen":oe[12]||(oe[12]=Re=>c.value=Re),style:v.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:v.withCtx(()=>[v.createElementVNode("h3",_3,v.toDisplayString(t.title),1)]),operations:v.withCtx(()=>[v.renderSlot(Ie.$slots,"operations",{},()=>[v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(Sr.IconNewSession),size:"28",svgSize:"20",onClick:oe[0]||(oe[0]=Re=>v.unref(Ve)())},null,8,["icon"]),v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(Sr.IconHistory),size:"28",svgSize:"20",onClick:oe[1]||(oe[1]=Re=>Ce.value=!v.unref(Ce))},null,8,["icon"]),v.createVNode(zw,{onScanSuccess:v.unref(Un)},null,8,["onScanSuccess"]),v.createVNode(v.Transition,{name:"drawer-slide",appear:""},{default:v.withCtx(()=>[v.unref(Ce)?(v.openBlock(),v.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:oe[4]||(oe[4]=Re=>Ce.value=!1)},[v.createElementVNode("div",{class:"drawer-container",onClick:oe[3]||(oe[3]=v.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[oe[13]||(oe[13]=v.createElementVNode("h4",null,"历史会话",-1)),v.createVNode(v.unref(Pt.TrHistory),{class:"tr-history-demo",selected:v.unref($).currentId,data:v.unref($).conversations,showRenameControls:!0,onClose:oe[2]||(oe[2]=Re=>Ce.value=!1),onItemClick:v.unref(Me),onItemTitleChange:v.unref(Ye),onItemAction:v.unref(ie)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):v.createCommentVNode("",!0)]),_:1})],!0)]),footer:v.withCtx(()=>[v.createElementVNode("div",C3,[v.renderSlot(Ie.$slots,"suggestions",{},()=>[v.createElementVNode("div",b3,[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(v.unref(_t),Re=>(v.openBlock(),v.createBlock(v.unref(Pt.TrDropdownMenu),{key:Re.id,items:Re.menus,onItemClick:pr,trigger:"click"},{trigger:v.withCtx(()=>[v.createVNode(v.unref(Pt.TrSuggestionPillButton),null,{default:v.withCtx(()=>[v.createTextVNode(v.toDisplayString(Re.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),v.createVNode(v.unref(Pt.TrSender),{ref_key:"senderRef",ref:z,mode:"multiple",modelValue:v.unref(j),"onUpdate:modelValue":oe[9]||(oe[9]=Re=>v.isRef(j)?j.value=Re:null),placeholder:Lt.value,clearable:!!v.unref(j),loading:li.value,showWordLimit:!0,maxLength:2e4,onSubmit:An,onCancel:v.unref(V)},v.createSlots({footer:v.withCtx(()=>[v.createElementVNode("div",A3,[v.createVNode(i3,{"installed-plugins":v.unref(Ne),onClick:oe[6]||(oe[6]=Re=>Xe.value=!v.unref(Xe))},null,8,["installed-plugins"]),v.unref(_)&&v.unref(_).length>0?(v.openBlock(),v.createBlock(t3,{key:0,"model-configs":v.unref(_),"selected-model-id":f.value,"onUpdate:selectedModelId":oe[7]||(oe[7]=Re=>f.value=Re)},null,8,["model-configs","selected-model-id"])):v.createCommentVNode("",!0),C.value?(v.openBlock(),v.createBlock(c3,{key:1,"genui-enabled":p.value,"onUpdate:genuiEnabled":oe[8]||(oe[8]=Re=>p.value=Re)},null,8,["genui-enabled"])):v.createCommentVNode("",!0),v.unref(A)?(v.openBlock(),v.createBlock(v.unref(Pt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:v.unref(O)},null,8,["onSelect"])):v.createCommentVNode("",!0)])]),_:2},[v.unref(B).length>0?{name:"header",fn:v.withCtx(()=>[v.createElementVNode("div",E3,[v.createVNode(v.unref(Pt.TrAttachments),{items:v.unref(B),"onUpdate:items":oe[5]||(oe[5]=Re=>v.isRef(B)?B.value=Re:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),v.createVNode(v.unref(Pt.TrMcpServerPicker),{visible:v.unref(Xe),"onUpdate:visible":oe[10]||(oe[10]=Re=>v.isRef(Xe)?Xe.value=Re:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:v.unref(Ne),marketPlugins:v.unref(ot),"market-category-options":T.value,"installed-search-fn":v.unref(En),"market-search-fn":v.unref(En),onPluginToggle:v.unref(Ue),onPluginAdd:v.unref(wt),onPluginDelete:v.unref(Vt),onToolToggle:v.unref(pn),onPluginCreate:v.unref(Wi)},{"header-actions":v.withCtx(()=>[v.renderSlot(Ie.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:v.withCtx(()=>[v.createVNode(v.unref(Pt.TrBubbleProvider),{"content-renderers":Ae},{default:v.withCtx(()=>[v.unref(H).length===0?v.renderSlot(Ie.$slots,"welcome",{key:0},()=>[v.createElementVNode("div",v3,[v.createVNode(v.unref(Pt.TrWelcome),{title:v.unref(pe)[t.locale].title,description:v.unref(pe)[t.locale].description,icon:v.unref(ge)},null,8,["title","description","icon"]),v.createVNode(v.unref(Pt.TrPrompts),{items:v.unref(vt),wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(v.openBlock(),v.createBlock(v.unref(Pt.TrBubbleList),{key:1,style:{flex:"1"},items:v.unref(H),roles:v.unref(de),"auto-scroll":"",loading:v.unref(re).status===v.unref(Hn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),zo=Kn(I3,[["__scopeId","data-v-51187b4b"]]);function S3(t){const r=t.sessionId?_l(t.sessionId,t.agentRoot):[],o=new Ht.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=v.ref("ready"),u=v.ref([]),f=v.ref("");let p=null;async function x(){const A=f.value;if(!A)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(A)){C(A.slice(1));return}c.value="submitted",p=new AbortController;const B=await o.chatStream({message:A,model:t.model,system:t.systemPrompt||"",abortSignal:p.signal,maxSteps:t.maxSteps||5,onFinish:async()=>{await o.closeAll(),c.value="ready"},onError:()=>c.value="error",onAbort:()=>c.value="ready"});if(f.value="",t.processStream&&typeof t.processStream=="function"){t.processStream(B.fullStream,u,A);return}t.ui==="matechat"?T3(B.fullStream,u,A):t.ui==="antx"?N3(B.fullStream,u,A):t.ui==="elplusx"?O3(B.fullStream,u,A):t.ui==="tdchat"?R3(B.fullStream,u,A):console.warn("暂时未实现")}function _(){p&&p.abort()}function g(){u.value=[],o.responseMessages=[]}async function C(A){const O=(await fetch(`${t.agentRoot}client?sessionId=${A}`).then(k=>k.json()))?.data?.sessionId||"";if(O){const k=_l(O,t.agentRoot);Object.assign(o.mcpServers,k)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:x,stopChat:_,newConversation:g,addSessionId:C}}function _l(t,r){if(!t)return{};const o=t.includes(",")?t.split(",").map(u=>u.trim()):[t],c={};return o.forEach(u=>{c[`mcp-server-${u}`]={type:"streamableHttp",url:`${r}mcp?sessionId=${u}`}}),c}async function T3(t,r,o){r.value.push({from:"user",content:o,avatarConfig:{name:"user"}});let c={from:"model",content:"",avatarConfig:{name:"model"},id:Date.now().toString()};r.value.push(c),c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function N3(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function O3(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function R3(t,r,o){r.value.push({role:"user",content:o,avatar:"https://tdesign.gtimg.com/site/avatar.jpg"}),r.value.push({role:"assistant",content:"",avatar:"https://tdesign.gtimg.com/site/chat-avatar.png"});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}zo.install=function(t){t.component("tiny-remoter",zo)};exports.TinyRemoter=zo;exports.useModel=as;exports.useNextAgent=S3;
|
|
91
|
+
`,x3=btoa(g3),yl=`data:image/svg+xml;base64,${x3}`,Eo=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},y3=t=>{const r={"zh-CN":{title:"OpenTiny NEXT",description:"我是你的私人智能助手",placeholder:"请输入您的问题",thinking:"正在思考中..."},"en-US":{title:"OpenTiny NEXT",description:"I am your private AI assistant",placeholder:"Please enter your question",thinking:"Thinking..."}},o=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(Eo)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(Eo)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(Eo)}],c=[{label:t.locale==="zh-CN"?"企业办公助手":"Enterprise Office Assistant",description:t.locale==="zh-CN"?"需要我帮你处理邮件、安排会议、整理文档,还是优化工作流程?":"Need help with emails, meeting scheduling, document organization, or workflow optimization?",icon:v.h("span",{style:{fontSize:"18px"}},"🧠"),badge:"NEW"},{label:t.locale==="zh-CN"?"开发技术支持":"Development Support",description:t.locale==="zh-CN"?"遇到代码问题?需要架构建议?还是想了解最新的技术趋势?":"Facing code issues? Need architecture advice? Or want to learn about latest tech trends?",icon:v.h("span",{style:{fontSize:"18px"}},"💻")},{label:t.locale==="zh-CN"?"项目管理协作":"Project Management",description:t.locale==="zh-CN"?"需要项目规划、任务分配、进度跟踪,还是团队协作建议?":"Need project planning, task assignment, progress tracking, or team collaboration advice?",icon:v.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:o,promptItems:c}},wl={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},w3=t=>{console.log("message",t);const r=Object.keys(wl),o=r.findIndex(u=>t.includes(u));return(o!==-1?wl[r[o]]:t)||t},_3={class:"tr-container__title"},v3={style:{flex:"1"}},C3={class:"chat-input"},b3={class:"chat-input-pills"},E3={class:"attachments-container"},A3={class:"action-buttons"},I3=v.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:v.mergeModels({sessionId:{type:String,default:void 0},agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},remoteUrl:{type:String},menuItems:{type:Array},qrCodeUrl:{type:String},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:v.h(Sr.IconUser,{style:{fontSize:"32px"}}),assistant:v.h(Hu,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},pageToolsOnDemand:{type:Boolean,default:!1}},{fullscreen:{type:Boolean,default:!1},fullscreenModifiers:{},show:{type:Boolean,default:!1},showModifiers:{},selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{},genUiAble:{type:Boolean,default:!1,required:!1},genUiAbleModifiers:{},enabledTools:{type:Object,default:void 0,required:!1},enabledToolsModifiers:{}}),emits:["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"],setup(t,{expose:r}){const o=t,c=v.useModel(t,"fullscreen"),u=v.useModel(t,"show"),f=v.useModel(t,"selectedModelId"),m=v.useModel(t,"genUiAble"),x=v.useModel(t,"enabledTools"),_=o.llmConfigs?v.toRef(o,"llmConfigs"):void 0,{selectedModel:g}=as(_,f),C=v.computed(()=>{const Ie=_?.value?.length?g.value:o.llmConfig;return Ie?!!(Ie.baseURL&&Ie.genuiUrl):!1}),{hasMultimodalSupport:A,attachments:P,onFilesSelected:O,checkCanSendAttachments:k,processAttachments:B,cleanupAttachments:L}=cw({selectedModel:g,selectedModelId:f}),{agent:K,customAgentProvider:z,conversationState:$,messages:W,messageState:X,inputMessage:H,abortRequest:V,senderRef:Z,sendMessage:M,handleSendMessage:we,addMessage:ce,send:fe,createConversation:ae,switchConversation:q,deleteConversation:D,getCurrentConversation:Q}=Sx({systemPrompt:o.systemPrompt||"",llmConfig:o.llmConfig});v.watch(()=>o.systemPrompt,Ie=>{z.promptManager.setStatic(Ie)}),z.isGenuiEnabled=m,z.debugStream=o.debugStream,v.watch(()=>o.pageToolsOnDemand,Ie=>{z.pageToolsOnDemand=Ie},{immediate:!0});const j=v.toRef(o,"skills"),{processSkillMentions:te}=qy({skillsRef:j,customAgentProvider:z}),he=async(Ie,oe)=>we(Ie,oe,te),{welcomeIcon:ge,roles:de}=tw({props:o,messages:W,messageState:X,inputMessage:H,handleSendMessage:he}),{showHistory:Ce,handleCreateConversation:Ve,handleHistorySelect:Me,handleHistoryUpdateTitle:Ye,handleHistoryDelete:ie}=nw({createConversation:ae,switchConversation:q,deleteConversation:D,getCurrentConversation:Q,abortRequest:V,conversationState:$,customAgentProvider:z}),ke=()=>{if(g.value){const Ie=g.value;z.updateLLMConfig({model:Ie.model||"",baseURL:Ie.baseURL||"",genuiUrl:Ie.genuiUrl||"",apiKey:Ie.apiKey||"",providerType:Ie.providerType,useReActMode:Ie.useReActMode,llm:Ie.llm,providerOptions:Ie.providerOptions,headers:Ie.headers})}else z.updateLLMConfig(z.llmConfig)};o.llmConfigs&&v.watch(g,ke,{immediate:!0}),v.watch(m,ke,{immediate:!0});const Ae={markdown:new Pt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ie=>v.h(Sd.GenuiRenderer,{...Ie,customActions:{continueChat:{execute:(oe,Re)=>{const qe=typeof oe=="string"?oe:oe.message,pt=`${qe},相关参数为:${JSON.stringify(Re?.state||{})}`;ce({role:"user",content:pt,uiContent:[{type:"markdown",content:qe}]}),fe()}}},generating:Hn.GeneratingStatus.includes(X.status),customComponents:o.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:p3},{installedPlugins:Ne,marketPlugins:ot,pluginVisible:Xe,loadMcpServerToPlugin:$t,togglePlugin:Ue,toggleTool:pn,deletePlugin:Vt,addPluginCore:bn,addPluginFromMarket:wt,addPluginFromScan:Je,handleClientDisconnected:je,searchPlugin:En}=Xy(K,x,yl);Xm({enabled:v.toRef(o,"pageToolsOnDemand"),installedPlugins:Ne,customAgentProvider:z}),ot.value=[...m3,...o.customMarketMcpServers];const T=v.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),{lang:pe,pillItems:_t,promptItems:vt}=y3(o),{handleScanSuccess:Un,handleSessionIdInput:nn,initialize:ai}=rw({sessionId:v.toRef(o,"sessionId"),agentRoot:o.agentRoot,mode:o.mode,qrCodeUrl:o.qrCodeUrl,remoteUrl:o.remoteUrl,menuItems:o.menuItems,AILogoUrl:o.AILogoUrl,show:u,addPluginFromScan:Je,inputMessage:H}),An=async Ie=>{if(await nn(H.value)||!k())return;const Re=await B();try{await he(Ie,Re),L()}catch(qe){console.error("发送消息失败:",qe)}},Lt=v.computed(()=>Hn.GeneratingStatus.includes(X.status)?pe[o.locale].thinking:pe[o.locale].placeholder),li=v.computed(()=>Hn.GeneratingStatus.includes(X.status)),pr=Ie=>{H.value=Ie.inputMessage};ai(),v.onMounted(async()=>{Ve(),K.onError=oe=>{oe&&et(w3(oe))};const Ie=ot.value.filter(oe=>oe.addState==="added"&&oe.enabled);for(const oe of Ie)await wt(oe);if(o.mcpServers)for(const[oe,Re]of Object.entries(o.mcpServers))await $t(oe,Re)});const{handleCustomAdd:Wi}=Gy(K,Ne,yl);return r({agent:K,welcomeIcon:ge,messages:W,messageState:X,roles:de,inputMessage:H,senderRef:Z,abortRequest:V,sendMessage:M,loadMcpServerToPlugin:$t,handleClientDisconnected:je,addMessage:ce,installedPlugins:Ne,addPluginCore:bn,deletePlugin:Vt}),(Ie,oe)=>(v.openBlock(),v.createBlock(v.unref(Pt.TrContainer),{show:u.value,"onUpdate:show":oe[11]||(oe[11]=Re=>u.value=Re),fullscreen:c.value,"onUpdate:fullscreen":oe[12]||(oe[12]=Re=>c.value=Re),style:v.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:v.withCtx(()=>[v.createElementVNode("h3",_3,v.toDisplayString(t.title),1)]),operations:v.withCtx(()=>[v.renderSlot(Ie.$slots,"operations",{},()=>[v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(Sr.IconNewSession),size:"28",svgSize:"20",onClick:oe[0]||(oe[0]=Re=>v.unref(Ve)())},null,8,["icon"]),v.createVNode(v.unref(Pt.TrIconButton),{icon:v.unref(Sr.IconHistory),size:"28",svgSize:"20",onClick:oe[1]||(oe[1]=Re=>Ce.value=!v.unref(Ce))},null,8,["icon"]),v.createVNode(zw,{onScanSuccess:v.unref(Un)},null,8,["onScanSuccess"]),v.createVNode(v.Transition,{name:"drawer-slide",appear:""},{default:v.withCtx(()=>[v.unref(Ce)?(v.openBlock(),v.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:oe[4]||(oe[4]=Re=>Ce.value=!1)},[v.createElementVNode("div",{class:"drawer-container",onClick:oe[3]||(oe[3]=v.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[oe[13]||(oe[13]=v.createElementVNode("h4",null,"历史会话",-1)),v.createVNode(v.unref(Pt.TrHistory),{class:"tr-history-demo",selected:v.unref($).currentId,data:v.unref($).conversations,showRenameControls:!0,onClose:oe[2]||(oe[2]=Re=>Ce.value=!1),onItemClick:v.unref(Me),onItemTitleChange:v.unref(Ye),onItemAction:v.unref(ie)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):v.createCommentVNode("",!0)]),_:1})],!0)]),footer:v.withCtx(()=>[v.createElementVNode("div",C3,[v.renderSlot(Ie.$slots,"suggestions",{},()=>[v.createElementVNode("div",b3,[(v.openBlock(!0),v.createElementBlock(v.Fragment,null,v.renderList(v.unref(_t),Re=>(v.openBlock(),v.createBlock(v.unref(Pt.TrDropdownMenu),{key:Re.id,items:Re.menus,onItemClick:pr,trigger:"click"},{trigger:v.withCtx(()=>[v.createVNode(v.unref(Pt.TrSuggestionPillButton),null,{default:v.withCtx(()=>[v.createTextVNode(v.toDisplayString(Re.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),v.createVNode(v.unref(Pt.TrSender),{ref_key:"senderRef",ref:Z,mode:"multiple",modelValue:v.unref(H),"onUpdate:modelValue":oe[9]||(oe[9]=Re=>v.isRef(H)?H.value=Re:null),placeholder:Lt.value,clearable:!!v.unref(H),loading:li.value,showWordLimit:!0,maxLength:2e4,onSubmit:An,onCancel:v.unref(V)},v.createSlots({footer:v.withCtx(()=>[v.createElementVNode("div",A3,[v.createVNode(i3,{"installed-plugins":v.unref(Ne),onClick:oe[6]||(oe[6]=Re=>Xe.value=!v.unref(Xe))},null,8,["installed-plugins"]),v.unref(_)&&v.unref(_).length>0?(v.openBlock(),v.createBlock(t3,{key:0,"model-configs":v.unref(_),"selected-model-id":f.value,"onUpdate:selectedModelId":oe[7]||(oe[7]=Re=>f.value=Re)},null,8,["model-configs","selected-model-id"])):v.createCommentVNode("",!0),C.value?(v.openBlock(),v.createBlock(c3,{key:1,"genui-enabled":m.value,"onUpdate:genuiEnabled":oe[8]||(oe[8]=Re=>m.value=Re)},null,8,["genui-enabled"])):v.createCommentVNode("",!0),v.unref(A)?(v.openBlock(),v.createBlock(v.unref(Pt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:v.unref(O)},null,8,["onSelect"])):v.createCommentVNode("",!0)])]),_:2},[v.unref(P).length>0?{name:"header",fn:v.withCtx(()=>[v.createElementVNode("div",E3,[v.createVNode(v.unref(Pt.TrAttachments),{items:v.unref(P),"onUpdate:items":oe[5]||(oe[5]=Re=>v.isRef(P)?P.value=Re:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),v.createVNode(v.unref(Pt.TrMcpServerPicker),{visible:v.unref(Xe),"onUpdate:visible":oe[10]||(oe[10]=Re=>v.isRef(Xe)?Xe.value=Re:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:v.unref(Ne),marketPlugins:v.unref(ot),"market-category-options":T.value,"installed-search-fn":v.unref(En),"market-search-fn":v.unref(En),onPluginToggle:v.unref(Ue),onPluginAdd:v.unref(wt),onPluginDelete:v.unref(Vt),onToolToggle:v.unref(pn),onPluginCreate:v.unref(Wi)},{"header-actions":v.withCtx(()=>[v.renderSlot(Ie.$slots,"header-actions",{},void 0,!0)]),_:3},8,["visible","installedPlugins","marketPlugins","market-category-options","installed-search-fn","market-search-fn","onPluginToggle","onPluginAdd","onPluginDelete","onToolToggle","onPluginCreate"])])]),default:v.withCtx(()=>[v.createVNode(v.unref(Pt.TrBubbleProvider),{"content-renderers":Ae},{default:v.withCtx(()=>[v.unref(W).length===0?v.renderSlot(Ie.$slots,"welcome",{key:0},()=>[v.createElementVNode("div",v3,[v.createVNode(v.unref(Pt.TrWelcome),{title:v.unref(pe)[t.locale].title,description:v.unref(pe)[t.locale].description,icon:v.unref(ge)},null,8,["title","description","icon"]),v.createVNode(v.unref(Pt.TrPrompts),{items:v.unref(vt),wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(v.openBlock(),v.createBlock(v.unref(Pt.TrBubbleList),{key:1,style:{flex:"1"},items:v.unref(W),roles:v.unref(de),"auto-scroll":"",loading:v.unref(X).status===v.unref(Hn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),zo=Kn(I3,[["__scopeId","data-v-51187b4b"]]);function S3(t){const r=t.sessionId?_l(t.sessionId,t.agentRoot):[],o=new Ht.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=v.ref("ready"),u=v.ref([]),f=v.ref("");let m=null;async function x(){const A=f.value;if(!A)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(A)){C(A.slice(1));return}c.value="submitted",m=new AbortController;const P=await o.chatStream({message:A,model:t.model,system:t.systemPrompt||"",abortSignal:m.signal,maxSteps:t.maxSteps||5,onFinish:async()=>{await o.closeAll(),c.value="ready"},onError:()=>c.value="error",onAbort:()=>c.value="ready"});if(f.value="",t.processStream&&typeof t.processStream=="function"){t.processStream(P.fullStream,u,A);return}t.ui==="matechat"?T3(P.fullStream,u,A):t.ui==="antx"?N3(P.fullStream,u,A):t.ui==="elplusx"?O3(P.fullStream,u,A):t.ui==="tdchat"?R3(P.fullStream,u,A):console.warn("暂时未实现")}function _(){m&&m.abort()}function g(){u.value=[],o.responseMessages=[]}async function C(A){const O=(await fetch(`${t.agentRoot}client?sessionId=${A}`).then(k=>k.json()))?.data?.sessionId||"";if(O){const k=_l(O,t.agentRoot);Object.assign(o.mcpServers,k)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:x,stopChat:_,newConversation:g,addSessionId:C}}function _l(t,r){if(!t)return{};const o=t.includes(",")?t.split(",").map(u=>u.trim()):[t],c={};return o.forEach(u=>{c[`mcp-server-${u}`]={type:"streamableHttp",url:`${r}mcp?sessionId=${u}`}}),c}async function T3(t,r,o){r.value.push({from:"user",content:o,avatarConfig:{name:"user"}});let c={from:"model",content:"",avatarConfig:{name:"model"},id:Date.now().toString()};r.value.push(c),c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function N3(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function O3(t,r,o){r.value.push({from:"user",content:o}),r.value.push({from:"model",content:""});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}async function R3(t,r,o){r.value.push({role:"user",content:o,avatar:"https://tdesign.gtimg.com/site/avatar.jpg"}),r.value.push({role:"assistant",content:"",avatar:"https://tdesign.gtimg.com/site/chat-avatar.png"});const c=r.value[r.value.length-1];for await(const u of t)u.type.startsWith("text-")?u.text&&(c.content+=u.text):u.type.startsWith("tool-")?u.delta&&(c.content+=u.delta):u.type.startsWith("reasoning-")&&u.text&&(c.content+=u.text)}zo.install=function(t){t.component("tiny-remoter",zo)};exports.TinyRemoter=zo;exports.useModel=as;exports.useNextAgent=S3;
|