@opentiny/next-remoter 0.4.0 → 0.4.1

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.
@@ -1,73 +1,73 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),$t=require("@opentiny/tiny-robot"),wd=require("@opentiny/genui-sdk-vue"),Qn=require("@opentiny/tiny-robot-kit"),kr=require("@opentiny/tiny-robot-svgs"),$n=require("@opentiny/next-sdk"),_d=require("@opentiny/vue-tooltip"),vd=require("@opentiny/vue-icon");function Cd(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 gl="vercel.ai.error",bd=Symbol.for(gl),xl,Ad=class yl extends Error{constructor({name:r,message:o,cause:c}){super(o),this[xl]=!0,this.name=r,this.cause=c}static isInstance(r){return yl.hasMarker(r,gl)}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}};xl=bd;var jt=Ad,wl="AI_APICallError",_l=`vercel.ai.error.${wl}`,Ed=Symbol.for(_l),vl,Zn=class extends jt{constructor({message:r,url:o,requestBodyValues:c,statusCode:u,responseHeaders:f,responseBody:m,cause:g,isRetryable:v=u!=null&&(u===408||u===409||u===429||u>=500),data:x}){super({name:wl,message:r,cause:g}),this[vl]=!0,this.url=o,this.requestBodyValues=c,this.statusCode=u,this.responseHeaders=f,this.responseBody=m,this.isRetryable=v,this.data=x}static isInstance(r){return jt.hasMarker(r,_l)}};vl=Ed;var Cl="AI_EmptyResponseBodyError",bl=`vercel.ai.error.${Cl}`,Id=Symbol.for(bl),Al,Sd=class extends jt{constructor({message:r="Empty response body"}={}){super({name:Cl,message:r}),this[Al]=!0}static isInstance(r){return jt.hasMarker(r,bl)}};Al=Id;function El(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Il="AI_InvalidArgumentError",Sl=`vercel.ai.error.${Il}`,Td=Symbol.for(Sl),Tl,Nl=class extends jt{constructor({message:r,cause:o,argument:c}){super({name:Il,message:r,cause:o}),this[Tl]=!0,this.argument=c}static isInstance(r){return jt.hasMarker(r,Sl)}};Tl=Td;var Ol="AI_InvalidResponseDataError",kl=`vercel.ai.error.${Ol}`,Nd=Symbol.for(kl),Rl,_s=class extends jt{constructor({data:r,message:o=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Ol,message:o}),this[Rl]=!0,this.data=r}static isInstance(r){return jt.hasMarker(r,kl)}};Rl=Nd;var Ml="AI_JSONParseError",Dl=`vercel.ai.error.${Ml}`,Od=Symbol.for(Dl),Pl,Ii=class extends jt{constructor({text:r,cause:o}){super({name:Ml,message:`JSON parsing failed: Text: ${r}.
2
- Error message: ${El(o)}`,cause:o}),this[Pl]=!0,this.text=r}static isInstance(r){return jt.hasMarker(r,Dl)}};Pl=Od;var Bl="AI_LoadAPIKeyError",Ll=`vercel.ai.error.${Bl}`,kd=Symbol.for(Ll),Fl,mi=class extends jt{constructor({message:r}){super({name:Bl,message:r}),this[Fl]=!0}static isInstance(r){return jt.hasMarker(r,Ll)}};Fl=kd;var Ul="AI_NoSuchModelError",zl=`vercel.ai.error.${Ul}`,Rd=Symbol.for(zl),Vl,vs=class extends jt{constructor({errorName:t=Ul,modelId:r,modelType:o,message:c=`No such ${o}: ${r}`}){super({name:t,message:c}),this[Vl]=!0,this.modelId=r,this.modelType=o}static isInstance(t){return jt.hasMarker(t,zl)}};Vl=Rd;var Zl="AI_TypeValidationError",$l=`vercel.ai.error.${Zl}`,Md=Symbol.for($l),jl,Dd=class wo extends jt{constructor({value:r,cause:o}){super({name:Zl,message:`Type validation failed: Value: ${JSON.stringify(r)}.
3
- Error message: ${El(o)}`,cause:o}),this[jl]=!0,this.value=r}static isInstance(r){return jt.hasMarker(r,$l)}static wrap({value:r,cause:o}){return wo.isInstance(o)&&o.value===r?o:new wo({value:r,cause:o})}};jl=Md;var qr=Dd,Hl="AI_UnsupportedFunctionalityError",Wl=`vercel.ai.error.${Hl}`,Pd=Symbol.for(Wl),Gl,Xl=class extends jt{constructor({functionality:r,message:o=`'${r}' functionality not supported.`}){super({name:Hl,message:o}),this[Gl]=!0,this.functionality=r}static isInstance(r){return jt.hasMarker(r,Wl)}};Gl=Pd;class ro 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}}const Cs=10,Bd=13,ur=32;function io(t){}function Ld(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:r=io,onError:o=io,onRetry:c=io,onComment:u,maxBufferSize:f}=t,m=[];let g=0,v=!0,x,E="",A=0,M,T=!1;function S($){if(T)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(v&&(v=!1,$.charCodeAt(0)===239&&$.charCodeAt(1)===187&&$.charCodeAt(2)===191&&($=$.slice(3))),m.length===0){const G=D($);G!==""&&(m.push(G),g=G.length),B();return}if($.indexOf(`
4
- `)===-1&&$.indexOf("\r")===-1){m.push($),g+=$.length,B();return}m.push($);const P=m.join("");m.length=0,g=0;const L=D(P);L!==""&&(m.push(L),g=L.length),B()}function B(){f!==void 0&&(g+E.length<=f||(T=!0,m.length=0,g=0,x=void 0,E="",A=0,M=void 0,o(new ro(`Buffered data exceeded max buffer size of ${f} characters`,{type:"max-buffer-size-exceeded"}))))}function D($){let P=0;if($.indexOf("\r")===-1){let L=$.indexOf(`
5
- `,P);for(;L!==-1;){if(P===L){A>0&&r({id:x,event:M,data:E}),x=void 0,E="",A=0,M=void 0,P=L+1,L=$.indexOf(`
6
- `,P);continue}const G=$.charCodeAt(P);if(bs($,P,G)){const U=$.charCodeAt(P+5)===ur?P+6:P+5,ee=$.slice(U,L);if(A===0&&$.charCodeAt(L+1)===Cs){r({id:x,event:M,data:ee}),x=void 0,E="",M=void 0,P=L+2,L=$.indexOf(`
7
- `,P);continue}E=A===0?ee:`${E}
8
- ${ee}`,A++}else As($,P,G)?M=$.slice($.charCodeAt(P+6)===ur?P+7:P+6,L)||void 0:ne($,P,L);P=L+1,L=$.indexOf(`
9
- `,P)}return $.slice(P)}for(;P<$.length;){const L=$.indexOf("\r",P),G=$.indexOf(`
10
- `,P);let U=-1;if(L!==-1&&G!==-1?U=L<G?L:G:L!==-1?L===$.length-1?U=-1:U=L:G!==-1&&(U=G),U===-1)break;ne($,P,U),P=U+1,$.charCodeAt(P-1)===Bd&&$.charCodeAt(P)===Cs&&P++}return $.slice(P)}function ne($,P,L){if(P===L){Z();return}const G=$.charCodeAt(P);if(bs($,P,G)){const Te=$.charCodeAt(P+5)===ur?P+6:P+5,H=$.slice(Te,L);E=A===0?H:`${E}
11
- ${H}`,A++;return}if(As($,P,G)){M=$.slice($.charCodeAt(P+6)===ur?P+7:P+6,L)||void 0;return}if(G===105&&$.charCodeAt(P+1)===100&&$.charCodeAt(P+2)===58){const Te=$.slice($.charCodeAt(P+3)===ur?P+4:P+3,L);x=Te.includes("\0")?void 0:Te;return}if(G===58){if(u){const Te=$.slice(P,L);u(Te.slice($.charCodeAt(P+1)===ur?2:1))}return}const U=$.slice(P,L),ee=U.indexOf(":");if(ee===-1){z(U,"",U);return}const Y=U.slice(0,ee),ue=U.charCodeAt(ee+1)===ur?2:1,ge=U.slice(ee+ue);z(Y,ge,U)}function z($,P,L){switch($){case"event":M=P||void 0;break;case"data":E=A===0?P:`${E}
12
- ${P}`,A++;break;case"id":x=P.includes("\0")?void 0:P;break;case"retry":/^\d+$/.test(P)?c(parseInt(P,10)):o(new ro(`Invalid \`retry\` value: "${P}"`,{type:"invalid-retry",value:P,line:L}));break;default:o(new ro(`Unknown field "${$.length>20?`${$.slice(0,20)}…`:$}"`,{type:"unknown-field",field:$,value:P,line:L}));break}}function Z(){A>0&&r({id:x,event:M,data:E}),x=void 0,E="",A=0,M=void 0}function re($={}){if($.consume&&m.length>0){const P=m.join("");ne(P,0,P.length)}v=!0,x=void 0,E="",A=0,M=void 0,m.length=0,g=0,T=!1}return{feed:S,reset:re}}function bs(t,r,o){return o===100&&t.charCodeAt(r+1)===97&&t.charCodeAt(r+2)===116&&t.charCodeAt(r+3)===97&&t.charCodeAt(r+4)===58}function As(t,r,o){return o===101&&t.charCodeAt(r+1)===118&&t.charCodeAt(r+2)===101&&t.charCodeAt(r+3)===110&&t.charCodeAt(r+4)===116&&t.charCodeAt(r+5)===58}class ql extends TransformStream{constructor({onError:r,onRetry:o,onComment:c,maxBufferSize:u}={}){let f;super({start(m){f=Ld({onEvent:g=>{m.enqueue(g)},onError(g){typeof r=="function"&&r(g),(r==="terminate"||g.type==="max-buffer-size-exceeded")&&m.error(g)},onRetry:o,onComment:c,maxBufferSize:u})},transform(m){f.feed(m)}})}}function ie(t,r,o){function c(g,v){var x;Object.defineProperty(g,"_zod",{value:g._zod??{},enumerable:!1}),(x=g._zod).traits??(x.traits=new Set),g._zod.traits.add(t),r(g,v);for(const E in m.prototype)E in g||Object.defineProperty(g,E,{value:m.prototype[E].bind(g)});g._zod.constr=m,g._zod.def=v}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function m(g){var v;const x=o?.Parent?new f:this;c(x,g),(v=x._zod).deferred??(v.deferred=[]);for(const E of x._zod.deferred)E();return x}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:g=>o?.Parent&&g instanceof o.Parent?!0:g?._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 Yl={};function er(t){return Yl}function Kl(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 Fd(t,r){return typeof r=="bigint"?r.toString():r}function Bo(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function Lo(t){return t==null}function Fo(t){const r=t.startsWith("^")?1:0,o=t.endsWith("$")?t.length-1:t.length;return t.slice(r,o)}function Ud(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 st(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 Uo(t,r,o){Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0})}function zr(t){return JSON.stringify(t)}const Jl=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Si(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const zd=Bo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ti(t){if(Si(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const o=r.prototype;return!(Si(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}const Vd=new Set(["string","number","symbol"]);function ni(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function Ne(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 Zd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const $d={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 gr(t,{...t._zod.def,shape:o,checks:[]})}function Hd(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 gr(t,{...t._zod.def,shape:o,checks:[]})}function Wd(t,r){if(!Ti(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 Uo(this,"shape",c),c},checks:[]};return gr(t,o)}function Gd(t,r){return gr(t,{...t._zod.def,get shape(){const o={...t._zod.def.shape,...r._zod.def.shape};return Uo(this,"shape",o),o},catchall:r._zod.def.catchall,checks:[]})}function Xd(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 gr(r,{...r._zod.def,shape:u,checks:[]})}function qd(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 gr(r,{...r._zod.def,shape:u,checks:[]})}function Gr(t,r=0){for(let o=r;o<t.issues.length;o++)if(t.issues[o]?.continue!==!0)return!0;return!1}function hr(t,r){return r.map(o=>{var c;return(c=o).path??(c.path=[]),o.path.unshift(t),o})}function gi(t){return typeof t=="string"?t:t?.message}function tr(t,r,o){const c={...t,path:t.path??[]};if(!t.message){const u=gi(t.inst?._zod.def?.error?.(t))??gi(r?.error?.(t))??gi(o.customError?.(t))??gi(o.localeError?.(t))??"Invalid input";c.message=u}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function zo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Kr(...t){const[r,o,c]=t;return typeof r=="string"?{message:r,code:"custom",input:o,inst:c}:{...r}}const Ql=(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,Fd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ec=ie("$ZodError",Ql),tc=ie("$ZodError",Ql,{Parent:Error});function Yd(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 Kd(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(g=>u({issues:g}));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 g=c,v=0;for(;v<m.path.length;){const x=m.path[v];v===m.path.length-1?(g[x]=g[x]||{_errors:[]},g[x]._errors.push(o(m))):g[x]=g[x]||{_errors:[]},g=g[x],v++}}};return u(t),c}const Jd=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 g=new(u?.Err??t)(m.issues.map(v=>tr(v,f,er())));throw Jl(g,u?.callee),g}return m.value},Qd=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 g=new(u?.Err??t)(m.issues.map(v=>tr(v,f,er())));throw Jl(g,u?.callee),g}return m.value},nc=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??ec)(f.issues.map(m=>tr(m,u,er())))}:{success:!0,data:f.value}},e1=nc(tc),rc=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=>tr(m,u,er())))}:{success:!0,data:f.value}},t1=rc(tc),n1=/^[cC][^\s-]{8,}$/,r1=/^[0-9a-z]+$/,i1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,o1=/^[0-9a-vA-V]{20}$/,s1=/^[A-Za-z0-9]{27}$/,a1=/^[a-zA-Z0-9_-]{21}$/,l1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,c1=/^([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})$/,Es=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)$/,u1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,d1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function f1(){return new RegExp(d1,"u")}const h1=/^(?:(?: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])$/,p1=/^(([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})$/,m1=/^((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])$/,g1=/^(([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])$/,x1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ic=/^[A-Za-z0-9_-]*$/,y1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,w1=/^\+(?:[0-9]){6,14}[0-9]$/,oc="(?:(?:\\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])))",_1=new RegExp(`^${oc}$`);function sc(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 v1(t){return new RegExp(`^${sc(t)}$`)}function C1(t){const r=sc({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(`^${oc}T(?:${c})$`)}const b1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},A1=/^\d+$/,E1=/^-?\d+(?:\.\d+)?/i,I1=/true|false/i,S1=/null/i,T1=/^[^A-Z]*$/,N1=/^[^a-z]*$/,an=ie("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),ac={number:"number",bigint:"bigint",object:"date"},lc=ie("$ZodCheckLessThan",(t,r)=>{an.init(t,r);const o=ac[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})}}),cc=ie("$ZodCheckGreaterThan",(t,r)=>{an.init(t,r);const o=ac[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})}}),O1=ie("$ZodCheckMultipleOf",(t,r)=>{an.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):Ud(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})}}),k1=ie("$ZodCheckNumberFormat",(t,r)=>{an.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=$d[r.format];t._zod.onattach.push(m=>{const g=m._zod.bag;g.format=r.format,g.minimum=u,g.maximum=f,o&&(g.pattern=A1)}),t._zod.check=m=>{const g=m.value;if(o){if(!Number.isInteger(g)){m.issues.push({expected:c,format:r.format,code:"invalid_type",input:g,inst:t});return}if(!Number.isSafeInteger(g)){g>0?m.issues.push({input:g,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:g,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}}g<u&&m.issues.push({origin:"number",input:g,code:"too_small",minimum:u,inclusive:!0,inst:t,continue:!r.abort}),g>f&&m.issues.push({origin:"number",input:g,code:"too_big",maximum:f,inst:t})}}),R1=ie("$ZodCheckMaxLength",(t,r)=>{var o;an.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Lo(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=zo(u);c.issues.push({origin:m,code:"too_big",maximum:r.maximum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),M1=ie("$ZodCheckMinLength",(t,r)=>{var o;an.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Lo(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=zo(u);c.issues.push({origin:m,code:"too_small",minimum:r.minimum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),D1=ie("$ZodCheckLengthEquals",(t,r)=>{var o;an.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Lo(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=zo(u),g=f>r.length;c.issues.push({origin:m,...g?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Di=ie("$ZodCheckStringFormat",(t,r)=>{var o,c;an.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=()=>{})}),P1=ie("$ZodCheckRegex",(t,r)=>{Di.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})}}),B1=ie("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=T1),Di.init(t,r)}),L1=ie("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=N1),Di.init(t,r)}),F1=ie("$ZodCheckIncludes",(t,r)=>{an.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})}}),U1=ie("$ZodCheckStartsWith",(t,r)=>{an.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})}}),z1=ie("$ZodCheckEndsWith",(t,r)=>{an.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})}}),V1=ie("$ZodCheckOverwrite",(t,r)=>{an.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class Z1{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(`
13
- `).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(`
14
- `))}}const $1={major:4,minor:0,patch:0},ft=ie("$ZodType",(t,r)=>{var o;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=$1;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,g)=>{let v=Gr(f),x;for(const E of m){if(E._zod.def.when){if(!E._zod.def.when(f))continue}else if(v)continue;const A=f.issues.length,M=E._zod.check(f);if(M instanceof Promise&&g?.async===!1)throw new Yr;if(x||M instanceof Promise)x=(x??Promise.resolve()).then(async()=>{await M,f.issues.length!==A&&(v||(v=Gr(f,A)))});else{if(f.issues.length===A)continue;v||(v=Gr(f,A))}}return x?x.then(()=>f):f};t._zod.run=(f,m)=>{const g=t._zod.parse(f,m);if(g instanceof Promise){if(m.async===!1)throw new Yr;return g.then(v=>u(v,c,m))}return u(g,c,m)}}t["~standard"]={validate:u=>{try{const f=e1(t,u);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return t1(t,u).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),Vo=ie("$ZodString",(t,r)=>{ft.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??b1(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}}),Ct=ie("$ZodStringFormat",(t,r)=>{Di.init(t,r),Vo.init(t,r)}),j1=ie("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=c1),Ct.init(t,r)}),H1=ie("$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=Es(c))}else r.pattern??(r.pattern=Es());Ct.init(t,r)}),W1=ie("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=u1),Ct.init(t,r)}),G1=ie("$ZodURL",(t,r)=>{Ct.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:y1.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})}}}),X1=ie("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=f1()),Ct.init(t,r)}),q1=ie("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=a1),Ct.init(t,r)}),Y1=ie("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=n1),Ct.init(t,r)}),K1=ie("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=r1),Ct.init(t,r)}),J1=ie("$ZodULID",(t,r)=>{r.pattern??(r.pattern=i1),Ct.init(t,r)}),Q1=ie("$ZodXID",(t,r)=>{r.pattern??(r.pattern=o1),Ct.init(t,r)}),e0=ie("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=s1),Ct.init(t,r)}),t0=ie("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=C1(r)),Ct.init(t,r)}),n0=ie("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=_1),Ct.init(t,r)}),r0=ie("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=v1(r)),Ct.init(t,r)}),i0=ie("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=l1),Ct.init(t,r)}),o0=ie("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=h1),Ct.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv4"})}),s0=ie("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=p1),Ct.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})}}}),a0=ie("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=m1),Ct.init(t,r)}),l0=ie("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=g1),Ct.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 uc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const c0=ie("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=x1),Ct.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64"}),t._zod.check=o=>{uc(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:t,continue:!r.abort})}});function u0(t){if(!ic.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),o=r.padEnd(Math.ceil(r.length/4)*4,"=");return uc(o)}const d0=ie("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=ic),Ct.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64url"}),t._zod.check=o=>{u0(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:t,continue:!r.abort})}}),f0=ie("$ZodE164",(t,r)=>{r.pattern??(r.pattern=w1),Ct.init(t,r)});function h0(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 p0=ie("$ZodJWT",(t,r)=>{Ct.init(t,r),t._zod.check=o=>{h0(o.value,r.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:t,continue:!r.abort})}}),dc=ie("$ZodNumber",(t,r)=>{ft.init(t,r),t._zod.pattern=t._zod.bag.pattern??E1,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}}),m0=ie("$ZodNumber",(t,r)=>{k1.init(t,r),dc.init(t,r)}),g0=ie("$ZodBoolean",(t,r)=>{ft.init(t,r),t._zod.pattern=I1,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}}),x0=ie("$ZodNull",(t,r)=>{ft.init(t,r),t._zod.pattern=S1,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}}),y0=ie("$ZodAny",(t,r)=>{ft.init(t,r),t._zod.parse=o=>o}),w0=ie("$ZodUnknown",(t,r)=>{ft.init(t,r),t._zod.parse=o=>o}),_0=ie("$ZodNever",(t,r)=>{ft.init(t,r),t._zod.parse=(o,c)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:t}),o)});function Is(t,r,o){t.issues.length&&r.issues.push(...hr(o,t.issues)),r.value[o]=t.value}const v0=ie("$ZodArray",(t,r)=>{ft.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 g=u[m],v=r.element._zod.run({value:g,issues:[]},c);v instanceof Promise?f.push(v.then(x=>Is(x,o,m))):Is(v,o,m)}return f.length?Promise.all(f).then(()=>o):o}});function xi(t,r,o){t.issues.length&&r.issues.push(...hr(o,t.issues)),r.value[o]=t.value}function Ss(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(...hr(o,t.issues)):t.value===void 0?o in c&&(r.value[o]=void 0):r.value[o]=t.value}const C0=ie("$ZodObject",(t,r)=>{ft.init(t,r);const o=Bo(()=>{const A=Object.keys(r.shape);for(const T of A)if(!(r.shape[T]instanceof ft))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const M=Zd(r.shape);return{shape:r.shape,keys:A,keySet:new Set(A),numKeys:A.length,optionalKeys:new Set(M)}});st(t._zod,"propValues",()=>{const A=r.shape,M={};for(const T in A){const S=A[T]._zod;if(S.values){M[T]??(M[T]=new Set);for(const B of S.values)M[T].add(B)}}return M});const c=A=>{const M=new Z1(["shape","payload","ctx"]),T=o.value,S=z=>{const Z=zr(z);return`shape[${Z}]._zod.run({ value: input[${Z}], issues: [] }, ctx)`};M.write("const input = payload.value;");const B=Object.create(null);let D=0;for(const z of T.keys)B[z]=`key_${D++}`;M.write("const newResult = {}");for(const z of T.keys)if(T.optionalKeys.has(z)){const Z=B[z];M.write(`const ${Z} = ${S(z)};`);const re=zr(z);M.write(`
15
- if (${Z}.issues.length) {
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),Vt=require("@opentiny/tiny-robot"),Ed=require("@opentiny/genui-sdk-vue"),Kn=require("@opentiny/tiny-robot-kit"),Mr=require("@opentiny/tiny-robot-svgs"),Jn=require("@opentiny/next-sdk"),Id=require("@opentiny/vue-tooltip"),Sd=require("@opentiny/vue-icon");function Td(t,r){for(var i=0;i<r.length;i++){const c=r[i];if(typeof c!="string"&&!Array.isArray(c)){for(const d in c)if(d!=="default"&&!(d in t)){const f=Object.getOwnPropertyDescriptor(c,d);f&&Object.defineProperty(t,d,f.get?f:{enumerable:!0,get:()=>c[d]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var vl="vercel.ai.error",Nd=Symbol.for(vl),Cl,Od=class bl extends Error{constructor({name:r,message:i,cause:c}){super(i),this[Cl]=!0,this.name=r,this.cause=c}static isInstance(r){return bl.hasMarker(r,vl)}static hasMarker(r,i){const c=Symbol.for(i);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}};Cl=Nd;var Zt=Od,Al="AI_APICallError",El=`vercel.ai.error.${Al}`,kd=Symbol.for(El),Il,Vn=class extends Zt{constructor({message:r,url:i,requestBodyValues:c,statusCode:d,responseHeaders:f,responseBody:m,cause:x,isRetryable:v=d!=null&&(d===408||d===409||d===429||d>=500),data:g}){super({name:Al,message:r,cause:x}),this[Il]=!0,this.url=i,this.requestBodyValues=c,this.statusCode=d,this.responseHeaders=f,this.responseBody=m,this.isRetryable=v,this.data=g}static isInstance(r){return Zt.hasMarker(r,El)}};Il=kd;var Sl="AI_EmptyResponseBodyError",Tl=`vercel.ai.error.${Sl}`,Rd=Symbol.for(Tl),Nl,Md=class extends Zt{constructor({message:r="Empty response body"}={}){super({name:Sl,message:r}),this[Nl]=!0}static isInstance(r){return Zt.hasMarker(r,Tl)}};Nl=Rd;function Ol(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var kl="AI_InvalidArgumentError",Rl=`vercel.ai.error.${kl}`,Dd=Symbol.for(Rl),Ml,Dl=class extends Zt{constructor({message:r,cause:i,argument:c}){super({name:kl,message:r,cause:i}),this[Ml]=!0,this.argument=c}static isInstance(r){return Zt.hasMarker(r,Rl)}};Ml=Dd;var Pl="AI_InvalidResponseDataError",Bl=`vercel.ai.error.${Pl}`,Pd=Symbol.for(Bl),Ll,bs=class extends Zt{constructor({data:r,message:i=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Pl,message:i}),this[Ll]=!0,this.data=r}static isInstance(r){return Zt.hasMarker(r,Bl)}};Ll=Pd;var Fl="AI_JSONParseError",Ul=`vercel.ai.error.${Fl}`,Bd=Symbol.for(Ul),zl,Oo=class extends Zt{constructor({text:r,cause:i}){super({name:Fl,message:`JSON parsing failed: Text: ${r}.
2
+ Error message: ${Ol(i)}`,cause:i}),this[zl]=!0,this.text=r}static isInstance(r){return Zt.hasMarker(r,Ul)}};zl=Bd;var Vl="AI_LoadAPIKeyError",Zl=`vercel.ai.error.${Vl}`,Ld=Symbol.for(Zl),$l,wo=class extends Zt{constructor({message:r}){super({name:Vl,message:r}),this[$l]=!0}static isInstance(r){return Zt.hasMarker(r,Zl)}};$l=Ld;var jl="AI_NoSuchModelError",Hl=`vercel.ai.error.${jl}`,Fd=Symbol.for(Hl),Wl,As=class extends Zt{constructor({errorName:t=jl,modelId:r,modelType:i,message:c=`No such ${i}: ${r}`}){super({name:t,message:c}),this[Wl]=!0,this.modelId=r,this.modelType=i}static isInstance(t){return Zt.hasMarker(t,Hl)}};Wl=Fd;var Gl="AI_TypeValidationError",ql=`vercel.ai.error.${Gl}`,Ud=Symbol.for(ql),Xl,zd=class Ci extends Zt{constructor({value:r,cause:i}){super({name:Gl,message:`Type validation failed: Value: ${JSON.stringify(r)}.
3
+ Error message: ${Ol(i)}`,cause:i}),this[Xl]=!0,this.value=r}static isInstance(r){return Zt.hasMarker(r,ql)}static wrap({value:r,cause:i}){return Ci.isInstance(i)&&i.value===r?i:new Ci({value:r,cause:i})}};Xl=Ud;var Jr=zd,Yl="AI_UnsupportedFunctionalityError",Kl=`vercel.ai.error.${Yl}`,Vd=Symbol.for(Kl),Jl,Ql=class extends Zt{constructor({functionality:r,message:i=`'${r}' functionality not supported.`}){super({name:Yl,message:i}),this[Jl]=!0,this.functionality=r}static isInstance(r){return Zt.hasMarker(r,Kl)}};Jl=Vd;class ai extends Error{constructor(r,i){super(r),this.name="ParseError",this.type=i.type,this.field=i.field,this.value=i.value,this.line=i.line}}const Es=10,Zd=13,ur=32;function li(t){}function $d(t){if(typeof t=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:r=li,onError:i=li,onRetry:c=li,onComment:d,maxBufferSize:f}=t,m=[];let x=0,v=!0,g,E="",A=0,D,T=!1;function S(Z){if(T)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(v&&(v=!1,Z.charCodeAt(0)===239&&Z.charCodeAt(1)===187&&Z.charCodeAt(2)===191&&(Z=Z.slice(3))),m.length===0){const W=M(Z);W!==""&&(m.push(W),x=W.length),P();return}if(Z.indexOf(`
4
+ `)===-1&&Z.indexOf("\r")===-1){m.push(Z),x+=Z.length,P();return}m.push(Z);const B=m.join("");m.length=0,x=0;const L=M(B);L!==""&&(m.push(L),x=L.length),P()}function P(){f!==void 0&&(x+E.length<=f||(T=!0,m.length=0,x=0,g=void 0,E="",A=0,D=void 0,i(new ai(`Buffered data exceeded max buffer size of ${f} characters`,{type:"max-buffer-size-exceeded"}))))}function M(Z){let B=0;if(Z.indexOf("\r")===-1){let L=Z.indexOf(`
5
+ `,B);for(;L!==-1;){if(B===L){A>0&&r({id:g,event:D,data:E}),g=void 0,E="",A=0,D=void 0,B=L+1,L=Z.indexOf(`
6
+ `,B);continue}const W=Z.charCodeAt(B);if(Is(Z,B,W)){const z=Z.charCodeAt(B+5)===ur?B+6:B+5,we=Z.slice(z,L);if(A===0&&Z.charCodeAt(L+1)===Es){r({id:g,event:D,data:we}),g=void 0,E="",D=void 0,B=L+2,L=Z.indexOf(`
7
+ `,B);continue}E=A===0?we:`${E}
8
+ ${we}`,A++}else Ss(Z,B,W)?D=Z.slice(Z.charCodeAt(B+6)===ur?B+7:B+6,L)||void 0:ee(Z,B,L);B=L+1,L=Z.indexOf(`
9
+ `,B)}return Z.slice(B)}for(;B<Z.length;){const L=Z.indexOf("\r",B),W=Z.indexOf(`
10
+ `,B);let z=-1;if(L!==-1&&W!==-1?z=L<W?L:W:L!==-1?L===Z.length-1?z=-1:z=L:W!==-1&&(z=W),z===-1)break;ee(Z,B,z),B=z+1,Z.charCodeAt(B-1)===Zd&&Z.charCodeAt(B)===Es&&B++}return Z.slice(B)}function ee(Z,B,L){if(B===L){F();return}const W=Z.charCodeAt(B);if(Is(Z,B,W)){const te=Z.charCodeAt(B+5)===ur?B+6:B+5,q=Z.slice(te,L);E=A===0?q:`${E}
11
+ ${q}`,A++;return}if(Ss(Z,B,W)){D=Z.slice(Z.charCodeAt(B+6)===ur?B+7:B+6,L)||void 0;return}if(W===105&&Z.charCodeAt(B+1)===100&&Z.charCodeAt(B+2)===58){const te=Z.slice(Z.charCodeAt(B+3)===ur?B+4:B+3,L);g=te.includes("\0")?void 0:te;return}if(W===58){if(d){const te=Z.slice(B,L);d(te.slice(Z.charCodeAt(B+1)===ur?2:1))}return}const z=Z.slice(B,L),we=z.indexOf(":");if(we===-1){$(z,"",z);return}const G=z.slice(0,we),me=z.charCodeAt(we+1)===ur?2:1,fe=z.slice(we+me);$(G,fe,z)}function $(Z,B,L){switch(Z){case"event":D=B||void 0;break;case"data":E=A===0?B:`${E}
12
+ ${B}`,A++;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?c(parseInt(B,10)):i(new ai(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:L}));break;default:i(new ai(`Unknown field "${Z.length>20?`${Z.slice(0,20)}…`:Z}"`,{type:"unknown-field",field:Z,value:B,line:L}));break}}function F(){A>0&&r({id:g,event:D,data:E}),g=void 0,E="",A=0,D=void 0}function re(Z={}){if(Z.consume&&m.length>0){const B=m.join("");ee(B,0,B.length)}v=!0,g=void 0,E="",A=0,D=void 0,m.length=0,x=0,T=!1}return{feed:S,reset:re}}function Is(t,r,i){return i===100&&t.charCodeAt(r+1)===97&&t.charCodeAt(r+2)===116&&t.charCodeAt(r+3)===97&&t.charCodeAt(r+4)===58}function Ss(t,r,i){return i===101&&t.charCodeAt(r+1)===118&&t.charCodeAt(r+2)===101&&t.charCodeAt(r+3)===110&&t.charCodeAt(r+4)===116&&t.charCodeAt(r+5)===58}class ec extends TransformStream{constructor({onError:r,onRetry:i,onComment:c,maxBufferSize:d}={}){let f;super({start(m){f=$d({onEvent:x=>{m.enqueue(x)},onError(x){typeof r=="function"&&r(x),(r==="terminate"||x.type==="max-buffer-size-exceeded")&&m.error(x)},onRetry:i,onComment:c,maxBufferSize:d})},transform(m){f.feed(m)}})}}function oe(t,r,i){function c(x,v){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,v);for(const E in m.prototype)E in x||Object.defineProperty(x,E,{value:m.prototype[E].bind(x)});x._zod.constr=m,x._zod.def=v}const d=i?.Parent??Object;class f extends d{}Object.defineProperty(f,"name",{value:t});function m(x){var v;const g=i?.Parent?new f:this;c(g,x),(v=g._zod).deferred??(v.deferred=[]);for(const E of g._zod.deferred)E();return g}return Object.defineProperty(m,"init",{value:c}),Object.defineProperty(m,Symbol.hasInstance,{value:x=>i?.Parent&&x instanceof i.Parent?!0:x?._zod?.traits?.has(t)}),Object.defineProperty(m,"name",{value:t}),m}class Qr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const tc={};function Qn(t){return tc}function nc(t){const r=Object.values(t).filter(c=>typeof c=="number");return Object.entries(t).filter(([c,d])=>r.indexOf(+c)===-1).map(([c,d])=>d)}function jd(t,r){return typeof r=="bigint"?r.toString():r}function Ui(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function zi(t){return t==null}function Vi(t){const r=t.startsWith("^")?1:0,i=t.endsWith("$")?t.length-1:t.length;return t.slice(r,i)}function Hd(t,r){const i=(t.toString().split(".")[1]||"").length,c=(r.toString().split(".")[1]||"").length,d=i>c?i:c,f=Number.parseInt(t.toFixed(d).replace(".","")),m=Number.parseInt(r.toFixed(d).replace(".",""));return f%m/10**d}function lt(t,r,i){Object.defineProperty(t,r,{get(){{const c=i();return t[r]=c,c}},set(c){Object.defineProperty(t,r,{value:c})},configurable:!0})}function Zi(t,r,i){Object.defineProperty(t,r,{value:i,writable:!0,enumerable:!0,configurable:!0})}function Zr(t){return JSON.stringify(t)}const rc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Wd=Ui(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Ro(t){if(ko(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const i=r.prototype;return!(ko(i)===!1||Object.prototype.hasOwnProperty.call(i,"isPrototypeOf")===!1)}const Gd=new Set(["string","number","symbol"]);function io(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function gr(t,r,i){const c=new t._zod.constr(r??t._zod.def);return(!r||i?.parent)&&(c._zod.parent=t),c}function Ie(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 Xd={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 Yd(t,r){const i={},c=t._zod.def;for(const d in r){if(!(d in c.shape))throw new Error(`Unrecognized key: "${d}"`);r[d]&&(i[d]=c.shape[d])}return gr(t,{...t._zod.def,shape:i,checks:[]})}function Kd(t,r){const i={...t._zod.def.shape},c=t._zod.def;for(const d in r){if(!(d in c.shape))throw new Error(`Unrecognized key: "${d}"`);r[d]&&delete i[d]}return gr(t,{...t._zod.def,shape:i,checks:[]})}function Jd(t,r){if(!Ro(r))throw new Error("Invalid input to extend: expected a plain object");const i={...t._zod.def,get shape(){const c={...t._zod.def.shape,...r};return Zi(this,"shape",c),c},checks:[]};return gr(t,i)}function Qd(t,r){return gr(t,{...t._zod.def,get shape(){const i={...t._zod.def.shape,...r._zod.def.shape};return Zi(this,"shape",i),i},catchall:r._zod.def.catchall,checks:[]})}function e1(t,r,i){const c=r._zod.def.shape,d={...c};if(i)for(const f in i){if(!(f in c))throw new Error(`Unrecognized key: "${f}"`);i[f]&&(d[f]=t?new t({type:"optional",innerType:c[f]}):c[f])}else for(const f in c)d[f]=t?new t({type:"optional",innerType:c[f]}):c[f];return gr(r,{...r._zod.def,shape:d,checks:[]})}function t1(t,r,i){const c=r._zod.def.shape,d={...c};if(i)for(const f in i){if(!(f in d))throw new Error(`Unrecognized key: "${f}"`);i[f]&&(d[f]=new t({type:"nonoptional",innerType:c[f]}))}else for(const f in c)d[f]=new t({type:"nonoptional",innerType:c[f]});return gr(r,{...r._zod.def,shape:d,checks:[]})}function Yr(t,r=0){for(let i=r;i<t.issues.length;i++)if(t.issues[i]?.continue!==!0)return!0;return!1}function hr(t,r){return r.map(i=>{var c;return(c=i).path??(c.path=[]),i.path.unshift(t),i})}function _o(t){return typeof t=="string"?t:t?.message}function er(t,r,i){const c={...t,path:t.path??[]};if(!t.message){const d=_o(t.inst?._zod.def?.error?.(t))??_o(r?.error?.(t))??_o(i.customError?.(t))??_o(i.localeError?.(t))??"Invalid input";c.message=d}return delete c.inst,delete c.continue,r?.reportInput||delete c.input,c}function $i(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function eo(...t){const[r,i,c]=t;return typeof r=="string"?{message:r,code:"custom",input:i,inst:c}:{...r}}const oc=(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,jd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ic=oe("$ZodError",oc),sc=oe("$ZodError",oc,{Parent:Error});function n1(t,r=i=>i.message){const i={},c=[];for(const d of t.issues)d.path.length>0?(i[d.path[0]]=i[d.path[0]]||[],i[d.path[0]].push(r(d))):c.push(r(d));return{formErrors:c,fieldErrors:i}}function r1(t,r){const i=r||function(f){return f.message},c={_errors:[]},d=f=>{for(const m of f.issues)if(m.code==="invalid_union"&&m.errors.length)m.errors.map(x=>d({issues:x}));else if(m.code==="invalid_key")d({issues:m.issues});else if(m.code==="invalid_element")d({issues:m.issues});else if(m.path.length===0)c._errors.push(i(m));else{let x=c,v=0;for(;v<m.path.length;){const g=m.path[v];v===m.path.length-1?(x[g]=x[g]||{_errors:[]},x[g]._errors.push(i(m))):x[g]=x[g]||{_errors:[]},x=x[g],v++}}};return d(t),c}const o1=t=>(r,i,c,d)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},m=r._zod.run({value:i,issues:[]},f);if(m instanceof Promise)throw new Qr;if(m.issues.length){const x=new(d?.Err??t)(m.issues.map(v=>er(v,f,Qn())));throw rc(x,d?.callee),x}return m.value},i1=t=>async(r,i,c,d)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let m=r._zod.run({value:i,issues:[]},f);if(m instanceof Promise&&(m=await m),m.issues.length){const x=new(d?.Err??t)(m.issues.map(v=>er(v,f,Qn())));throw rc(x,d?.callee),x}return m.value},ac=t=>(r,i,c)=>{const d=c?{...c,async:!1}:{async:!1},f=r._zod.run({value:i,issues:[]},d);if(f instanceof Promise)throw new Qr;return f.issues.length?{success:!1,error:new(t??ic)(f.issues.map(m=>er(m,d,Qn())))}:{success:!0,data:f.value}},s1=ac(sc),lc=t=>async(r,i,c)=>{const d=c?Object.assign(c,{async:!0}):{async:!0};let f=r._zod.run({value:i,issues:[]},d);return f instanceof Promise&&(f=await f),f.issues.length?{success:!1,error:new t(f.issues.map(m=>er(m,d,Qn())))}:{success:!0,data:f.value}},a1=lc(sc),l1=/^[cC][^\s-]{8,}$/,c1=/^[0-9a-z]+$/,u1=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,d1=/^[0-9a-vA-V]{20}$/,f1=/^[A-Za-z0-9]{27}$/,h1=/^[a-zA-Z0-9_-]{21}$/,p1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,m1=/^([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})$/,Ts=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)$/,g1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,x1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function y1(){return new RegExp(x1,"u")}const w1=/^(?:(?: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])$/,_1=/^(([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})$/,v1=/^((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])$/,C1=/^(([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])$/,b1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cc=/^[A-Za-z0-9_-]*$/,A1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,E1=/^\+(?:[0-9]){6,14}[0-9]$/,uc="(?:(?:\\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])))",I1=new RegExp(`^${uc}$`);function dc(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 S1(t){return new RegExp(`^${dc(t)}$`)}function T1(t){const r=dc({precision:t.precision}),i=["Z"];t.local&&i.push(""),t.offset&&i.push("([+-]\\d{2}:\\d{2})");const c=`${r}(?:${i.join("|")})`;return new RegExp(`^${uc}T(?:${c})$`)}const N1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},O1=/^\d+$/,k1=/^-?\d+(?:\.\d+)?/i,R1=/true|false/i,M1=/null/i,D1=/^[^A-Z]*$/,P1=/^[^a-z]*$/,on=oe("$ZodCheck",(t,r)=>{var i;t._zod??(t._zod={}),t._zod.def=r,(i=t._zod).onattach??(i.onattach=[])}),fc={number:"number",bigint:"bigint",object:"date"},hc=oe("$ZodCheckLessThan",(t,r)=>{on.init(t,r);const i=fc[typeof r.value];t._zod.onattach.push(c=>{const d=c._zod.bag,f=(r.inclusive?d.maximum:d.exclusiveMaximum)??Number.POSITIVE_INFINITY;r.value<f&&(r.inclusive?d.maximum=r.value:d.exclusiveMaximum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value<=r.value:c.value<r.value)||c.issues.push({origin:i,code:"too_big",maximum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),pc=oe("$ZodCheckGreaterThan",(t,r)=>{on.init(t,r);const i=fc[typeof r.value];t._zod.onattach.push(c=>{const d=c._zod.bag,f=(r.inclusive?d.minimum:d.exclusiveMinimum)??Number.NEGATIVE_INFINITY;r.value>f&&(r.inclusive?d.minimum=r.value:d.exclusiveMinimum=r.value)}),t._zod.check=c=>{(r.inclusive?c.value>=r.value:c.value>r.value)||c.issues.push({origin:i,code:"too_small",minimum:r.value,input:c.value,inclusive:r.inclusive,inst:t,continue:!r.abort})}}),B1=oe("$ZodCheckMultipleOf",(t,r)=>{on.init(t,r),t._zod.onattach.push(i=>{var c;(c=i._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=i=>{if(typeof i.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof i.value=="bigint"?i.value%r.value===BigInt(0):Hd(i.value,r.value)===0)||i.issues.push({origin:typeof i.value,code:"not_multiple_of",divisor:r.value,input:i.value,inst:t,continue:!r.abort})}}),L1=oe("$ZodCheckNumberFormat",(t,r)=>{on.init(t,r),r.format=r.format||"float64";const i=r.format?.includes("int"),c=i?"int":"number",[d,f]=Xd[r.format];t._zod.onattach.push(m=>{const x=m._zod.bag;x.format=r.format,x.minimum=d,x.maximum=f,i&&(x.pattern=O1)}),t._zod.check=m=>{const x=m.value;if(i){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<d&&m.issues.push({origin:"number",input:x,code:"too_small",minimum:d,inclusive:!0,inst:t,continue:!r.abort}),x>f&&m.issues.push({origin:"number",input:x,code:"too_big",maximum:f,inst:t})}}),F1=oe("$ZodCheckMaxLength",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag.maximum??Number.POSITIVE_INFINITY;r.maximum<d&&(c._zod.bag.maximum=r.maximum)}),t._zod.check=c=>{const d=c.value;if(d.length<=r.maximum)return;const m=$i(d);c.issues.push({origin:m,code:"too_big",maximum:r.maximum,inclusive:!0,input:d,inst:t,continue:!r.abort})}}),U1=oe("$ZodCheckMinLength",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag.minimum??Number.NEGATIVE_INFINITY;r.minimum>d&&(c._zod.bag.minimum=r.minimum)}),t._zod.check=c=>{const d=c.value;if(d.length>=r.minimum)return;const m=$i(d);c.issues.push({origin:m,code:"too_small",minimum:r.minimum,inclusive:!0,input:d,inst:t,continue:!r.abort})}}),z1=oe("$ZodCheckLengthEquals",(t,r)=>{var i;on.init(t,r),(i=t._zod.def).when??(i.when=c=>{const d=c.value;return!zi(d)&&d.length!==void 0}),t._zod.onattach.push(c=>{const d=c._zod.bag;d.minimum=r.length,d.maximum=r.length,d.length=r.length}),t._zod.check=c=>{const d=c.value,f=d.length;if(f===r.length)return;const m=$i(d),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})}}),Fo=oe("$ZodCheckStringFormat",(t,r)=>{var i,c;on.init(t,r),t._zod.onattach.push(d=>{const f=d._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(i=t._zod).check??(i.check=d=>{r.pattern.lastIndex=0,!r.pattern.test(d.value)&&d.issues.push({origin:"string",code:"invalid_format",format:r.format,input:d.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),V1=oe("$ZodCheckRegex",(t,r)=>{Fo.init(t,r),t._zod.check=i=>{r.pattern.lastIndex=0,!r.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:"regex",input:i.value,pattern:r.pattern.toString(),inst:t,continue:!r.abort})}}),Z1=oe("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=D1),Fo.init(t,r)}),$1=oe("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=P1),Fo.init(t,r)}),j1=oe("$ZodCheckIncludes",(t,r)=>{on.init(t,r);const i=io(r.includes),c=new RegExp(typeof r.position=="number"?`^.{${r.position}}${i}`:i);r.pattern=c,t._zod.onattach.push(d=>{const f=d._zod.bag;f.patterns??(f.patterns=new Set),f.patterns.add(c)}),t._zod.check=d=>{d.value.includes(r.includes,r.position)||d.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:r.includes,input:d.value,inst:t,continue:!r.abort})}}),H1=oe("$ZodCheckStartsWith",(t,r)=>{on.init(t,r);const i=new RegExp(`^${io(r.prefix)}.*`);r.pattern??(r.pattern=i),t._zod.onattach.push(c=>{const d=c._zod.bag;d.patterns??(d.patterns=new Set),d.patterns.add(i)}),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})}}),W1=oe("$ZodCheckEndsWith",(t,r)=>{on.init(t,r);const i=new RegExp(`.*${io(r.suffix)}$`);r.pattern??(r.pattern=i),t._zod.onattach.push(c=>{const d=c._zod.bag;d.patterns??(d.patterns=new Set),d.patterns.add(i)}),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})}}),G1=oe("$ZodCheckOverwrite",(t,r)=>{on.init(t,r),t._zod.check=i=>{i.value=r.tx(i.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(`
13
+ `).filter(m=>m),d=Math.min(...c.map(m=>m.length-m.trimStart().length)),f=c.map(m=>m.slice(d)).map(m=>" ".repeat(this.indent*2)+m);for(const m of f)this.content.push(m)}compile(){const r=Function,i=this?.args,d=[...(this?.content??[""]).map(f=>` ${f}`)];return new r(...i,d.join(`
14
+ `))}}const X1={major:4,minor:0,patch:0},ht=oe("$ZodType",(t,r)=>{var i;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=X1;const c=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&c.unshift(t);for(const d of c)for(const f of d._zod.onattach)f(t);if(c.length===0)(i=t._zod).deferred??(i.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const d=(f,m,x)=>{let v=Yr(f),g;for(const E of m){if(E._zod.def.when){if(!E._zod.def.when(f))continue}else if(v)continue;const A=f.issues.length,D=E._zod.check(f);if(D instanceof Promise&&x?.async===!1)throw new Qr;if(g||D instanceof Promise)g=(g??Promise.resolve()).then(async()=>{await D,f.issues.length!==A&&(v||(v=Yr(f,A)))});else{if(f.issues.length===A)continue;v||(v=Yr(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 Qr;return x.then(v=>d(v,c,m))}return d(x,c,m)}}t["~standard"]={validate:d=>{try{const f=s1(t,d);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return a1(t,d).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),ji=oe("$ZodString",(t,r)=>{ht.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??N1(t._zod.bag),t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=String(i.value)}catch{}return typeof i.value=="string"||i.issues.push({expected:"string",code:"invalid_type",input:i.value,inst:t}),i}}),bt=oe("$ZodStringFormat",(t,r)=>{Fo.init(t,r),ji.init(t,r)}),Y1=oe("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=m1),bt.init(t,r)}),K1=oe("$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=Ts(c))}else r.pattern??(r.pattern=Ts());bt.init(t,r)}),J1=oe("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=g1),bt.init(t,r)}),Q1=oe("$ZodURL",(t,r)=>{bt.init(t,r),t._zod.check=i=>{try{const c=i.value,d=new URL(c),f=d.href;r.hostname&&(r.hostname.lastIndex=0,r.hostname.test(d.hostname)||i.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:A1.source,input:i.value,inst:t,continue:!r.abort})),r.protocol&&(r.protocol.lastIndex=0,r.protocol.test(d.protocol.endsWith(":")?d.protocol.slice(0,-1):d.protocol)||i.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:r.protocol.source,input:i.value,inst:t,continue:!r.abort})),!c.endsWith("/")&&f.endsWith("/")?i.value=f.slice(0,-1):i.value=f;return}catch{i.issues.push({code:"invalid_format",format:"url",input:i.value,inst:t,continue:!r.abort})}}}),e0=oe("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=y1()),bt.init(t,r)}),t0=oe("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=h1),bt.init(t,r)}),n0=oe("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=l1),bt.init(t,r)}),r0=oe("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=c1),bt.init(t,r)}),o0=oe("$ZodULID",(t,r)=>{r.pattern??(r.pattern=u1),bt.init(t,r)}),i0=oe("$ZodXID",(t,r)=>{r.pattern??(r.pattern=d1),bt.init(t,r)}),s0=oe("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=f1),bt.init(t,r)}),a0=oe("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=T1(r)),bt.init(t,r)}),l0=oe("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=I1),bt.init(t,r)}),c0=oe("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=S1(r)),bt.init(t,r)}),u0=oe("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=p1),bt.init(t,r)}),d0=oe("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=w1),bt.init(t,r),t._zod.onattach.push(i=>{const c=i._zod.bag;c.format="ipv4"})}),f0=oe("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=_1),bt.init(t,r),t._zod.onattach.push(i=>{const c=i._zod.bag;c.format="ipv6"}),t._zod.check=i=>{try{new URL(`http://[${i.value}]`)}catch{i.issues.push({code:"invalid_format",format:"ipv6",input:i.value,inst:t,continue:!r.abort})}}}),h0=oe("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=v1),bt.init(t,r)}),p0=oe("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=C1),bt.init(t,r),t._zod.check=i=>{const[c,d]=i.value.split("/");try{if(!d)throw new Error;const f=Number(d);if(`${f}`!==d)throw new Error;if(f<0||f>128)throw new Error;new URL(`http://[${c}]`)}catch{i.issues.push({code:"invalid_format",format:"cidrv6",input:i.value,inst:t,continue:!r.abort})}}});function mc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const m0=oe("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=b1),bt.init(t,r),t._zod.onattach.push(i=>{i._zod.bag.contentEncoding="base64"}),t._zod.check=i=>{mc(i.value)||i.issues.push({code:"invalid_format",format:"base64",input:i.value,inst:t,continue:!r.abort})}});function g0(t){if(!cc.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),i=r.padEnd(Math.ceil(r.length/4)*4,"=");return mc(i)}const x0=oe("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=cc),bt.init(t,r),t._zod.onattach.push(i=>{i._zod.bag.contentEncoding="base64url"}),t._zod.check=i=>{g0(i.value)||i.issues.push({code:"invalid_format",format:"base64url",input:i.value,inst:t,continue:!r.abort})}}),y0=oe("$ZodE164",(t,r)=>{r.pattern??(r.pattern=E1),bt.init(t,r)});function w0(t,r=null){try{const i=t.split(".");if(i.length!==3)return!1;const[c]=i;if(!c)return!1;const d=JSON.parse(atob(c));return!("typ"in d&&d?.typ!=="JWT"||!d.alg||r&&(!("alg"in d)||d.alg!==r))}catch{return!1}}const _0=oe("$ZodJWT",(t,r)=>{bt.init(t,r),t._zod.check=i=>{w0(i.value,r.alg)||i.issues.push({code:"invalid_format",format:"jwt",input:i.value,inst:t,continue:!r.abort})}}),gc=oe("$ZodNumber",(t,r)=>{ht.init(t,r),t._zod.pattern=t._zod.bag.pattern??k1,t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=Number(i.value)}catch{}const d=i.value;if(typeof d=="number"&&!Number.isNaN(d)&&Number.isFinite(d))return i;const f=typeof d=="number"?Number.isNaN(d)?"NaN":Number.isFinite(d)?void 0:"Infinity":void 0;return i.issues.push({expected:"number",code:"invalid_type",input:d,inst:t,...f?{received:f}:{}}),i}}),v0=oe("$ZodNumber",(t,r)=>{L1.init(t,r),gc.init(t,r)}),C0=oe("$ZodBoolean",(t,r)=>{ht.init(t,r),t._zod.pattern=R1,t._zod.parse=(i,c)=>{if(r.coerce)try{i.value=!!i.value}catch{}const d=i.value;return typeof d=="boolean"||i.issues.push({expected:"boolean",code:"invalid_type",input:d,inst:t}),i}}),b0=oe("$ZodNull",(t,r)=>{ht.init(t,r),t._zod.pattern=M1,t._zod.values=new Set([null]),t._zod.parse=(i,c)=>{const d=i.value;return d===null||i.issues.push({expected:"null",code:"invalid_type",input:d,inst:t}),i}}),A0=oe("$ZodAny",(t,r)=>{ht.init(t,r),t._zod.parse=i=>i}),E0=oe("$ZodUnknown",(t,r)=>{ht.init(t,r),t._zod.parse=i=>i}),I0=oe("$ZodNever",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>(i.issues.push({expected:"never",code:"invalid_type",input:i.value,inst:t}),i)});function Ns(t,r,i){t.issues.length&&r.issues.push(...hr(i,t.issues)),r.value[i]=t.value}const S0=oe("$ZodArray",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value;if(!Array.isArray(d))return i.issues.push({expected:"array",code:"invalid_type",input:d,inst:t}),i;i.value=Array(d.length);const f=[];for(let m=0;m<d.length;m++){const x=d[m],v=r.element._zod.run({value:x,issues:[]},c);v instanceof Promise?f.push(v.then(g=>Ns(g,i,m))):Ns(v,i,m)}return f.length?Promise.all(f).then(()=>i):i}});function vo(t,r,i){t.issues.length&&r.issues.push(...hr(i,t.issues)),r.value[i]=t.value}function Os(t,r,i,c){t.issues.length?c[i]===void 0?i in c?r.value[i]=void 0:r.value[i]=t.value:r.issues.push(...hr(i,t.issues)):t.value===void 0?i in c&&(r.value[i]=void 0):r.value[i]=t.value}const T0=oe("$ZodObject",(t,r)=>{ht.init(t,r);const i=Ui(()=>{const A=Object.keys(r.shape);for(const T of A)if(!(r.shape[T]instanceof ht))throw new Error(`Invalid element at key "${T}": expected a Zod schema`);const D=qd(r.shape);return{shape:r.shape,keys:A,keySet:new Set(A),numKeys:A.length,optionalKeys:new Set(D)}});lt(t._zod,"propValues",()=>{const A=r.shape,D={};for(const T in A){const S=A[T]._zod;if(S.values){D[T]??(D[T]=new Set);for(const P of S.values)D[T].add(P)}}return D});const c=A=>{const D=new q1(["shape","payload","ctx"]),T=i.value,S=$=>{const F=Zr($);return`shape[${F}]._zod.run({ value: input[${F}], issues: [] }, ctx)`};D.write("const input = payload.value;");const P=Object.create(null);let M=0;for(const $ of T.keys)P[$]=`key_${M++}`;D.write("const newResult = {}");for(const $ of T.keys)if(T.optionalKeys.has($)){const F=P[$];D.write(`const ${F} = ${S($)};`);const re=Zr($);D.write(`
15
+ if (${F}.issues.length) {
16
16
  if (input[${re}] === undefined) {
17
17
  if (${re} in input) {
18
18
  newResult[${re}] = undefined;
19
19
  }
20
20
  } else {
21
21
  payload.issues = payload.issues.concat(
22
- ${Z}.issues.map((iss) => ({
22
+ ${F}.issues.map((iss) => ({
23
23
  ...iss,
24
24
  path: iss.path ? [${re}, ...iss.path] : [${re}],
25
25
  }))
26
26
  );
27
27
  }
28
- } else if (${Z}.value === undefined) {
28
+ } else if (${F}.value === undefined) {
29
29
  if (${re} in input) newResult[${re}] = undefined;
30
30
  } else {
31
- newResult[${re}] = ${Z}.value;
31
+ newResult[${re}] = ${F}.value;
32
32
  }
33
- `)}else{const Z=B[z];M.write(`const ${Z} = ${S(z)};`),M.write(`
34
- if (${Z}.issues.length) payload.issues = payload.issues.concat(${Z}.issues.map(iss => ({
33
+ `)}else{const F=P[$];D.write(`const ${F} = ${S($)};`),D.write(`
34
+ if (${F}.issues.length) payload.issues = payload.issues.concat(${F}.issues.map(iss => ({
35
35
  ...iss,
36
- path: iss.path ? [${zr(z)}, ...iss.path] : [${zr(z)}]
37
- })));`),M.write(`newResult[${zr(z)}] = ${Z}.value`)}M.write("payload.value = newResult;"),M.write("return payload;");const ne=M.compile();return(z,Z)=>ne(A,z,Z)};let u;const f=Si,m=!Yl.jitless,v=m&&zd.value,x=r.catchall;let E;t._zod.parse=(A,M)=>{E??(E=o.value);const T=A.value;if(!f(T))return A.issues.push({expected:"object",code:"invalid_type",input:T,inst:t}),A;const S=[];if(m&&v&&M?.async===!1&&M.jitless!==!0)u||(u=c(r.shape)),A=u(A,M);else{A.value={};const Z=E.shape;for(const re of E.keys){const $=Z[re],P=$._zod.run({value:T[re],issues:[]},M),L=$._zod.optin==="optional"&&$._zod.optout==="optional";P instanceof Promise?S.push(P.then(G=>L?Ss(G,A,re,T):xi(G,A,re))):L?Ss(P,A,re,T):xi(P,A,re)}}if(!x)return S.length?Promise.all(S).then(()=>A):A;const B=[],D=E.keySet,ne=x._zod,z=ne.def.type;for(const Z of Object.keys(T)){if(D.has(Z))continue;if(z==="never"){B.push(Z);continue}const re=ne.run({value:T[Z],issues:[]},M);re instanceof Promise?S.push(re.then($=>xi($,A,Z))):xi(re,A,Z)}return B.length&&A.issues.push({code:"unrecognized_keys",keys:B,input:T,inst:t}),S.length?Promise.all(S).then(()=>A):A}});function Ts(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=>tr(f,c,er())))}),r}const fc=ie("$ZodUnion",(t,r)=>{ft.init(t,r),st(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),st(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),st(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),st(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=>Fo(c.source)).join("|")})$`)}}),t._zod.parse=(o,c)=>{let u=!1;const f=[];for(const m of r.options){const g=m._zod.run({value:o.value,issues:[]},c);if(g instanceof Promise)f.push(g),u=!0;else{if(g.issues.length===0)return g;f.push(g)}}return u?Promise.all(f).then(m=>Ts(m,o,t,c)):Ts(f,o,t,c)}}),b0=ie("$ZodDiscriminatedUnion",(t,r)=>{fc.init(t,r);const o=t._zod.parse;st(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[g,v]of Object.entries(m)){u[g]||(u[g]=new Set);for(const x of v)u[g].add(x)}}return u});const c=Bo(()=>{const u=r.options,f=new Map;for(const m of u){const g=m._zod.propValues[r.discriminator];if(!g||g.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(m)}"`);for(const v of g){if(f.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);f.set(v,m)}}return f});t._zod.parse=(u,f)=>{const m=u.value;if(!Si(m))return u.issues.push({code:"invalid_type",expected:"object",input:m,inst:t}),u;const g=c.value.get(m?.[r.discriminator]);return g?g._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)}}),A0=ie("$ZodIntersection",(t,r)=>{ft.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(([v,x])=>Ns(o,v,x)):Ns(o,f,m)}});function _o(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(Ti(t)&&Ti(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=_o(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=_o(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 Ns(t,r,o){if(r.issues.length&&t.issues.push(...r.issues),o.issues.length&&t.issues.push(...o.issues),Gr(t))return t;const c=_o(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 E0=ie("$ZodRecord",(t,r)=>{ft.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!Ti(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 v of m)if(typeof v=="string"||typeof v=="number"||typeof v=="symbol"){const x=r.valueType._zod.run({value:u[v],issues:[]},c);x instanceof Promise?f.push(x.then(E=>{E.issues.length&&o.issues.push(...hr(v,E.issues)),o.value[v]=E.value})):(x.issues.length&&o.issues.push(...hr(v,x.issues)),o.value[v]=x.value)}let g;for(const v in u)m.has(v)||(g=g??[],g.push(v));g&&g.length>0&&o.issues.push({code:"unrecognized_keys",input:u,inst:t,keys:g})}else{o.value={};for(const m of Reflect.ownKeys(u)){if(m==="__proto__")continue;const g=r.keyType._zod.run({value:m,issues:[]},c);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(g.issues.length){o.issues.push({origin:"record",code:"invalid_key",issues:g.issues.map(x=>tr(x,c,er())),input:m,path:[m],inst:t}),o.value[g.value]=g.value;continue}const v=r.valueType._zod.run({value:u[m],issues:[]},c);v instanceof Promise?f.push(v.then(x=>{x.issues.length&&o.issues.push(...hr(m,x.issues)),o.value[g.value]=x.value})):(v.issues.length&&o.issues.push(...hr(m,v.issues)),o.value[g.value]=v.value)}}return f.length?Promise.all(f).then(()=>o):o}}),I0=ie("$ZodEnum",(t,r)=>{ft.init(t,r);const o=Kl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Vd.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}}),S0=ie("$ZodLiteral",(t,r)=>{ft.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}}),T0=ie("$ZodTransform",(t,r)=>{ft.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}}),N0=ie("$ZodOptional",(t,r)=>{ft.init(t,r),t._zod.optin="optional",t._zod.optout="optional",st(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),st(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Fo(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)}),O0=ie("$ZodNullable",(t,r)=>{ft.init(t,r),st(t._zod,"optin",()=>r.innerType._zod.optin),st(t._zod,"optout",()=>r.innerType._zod.optout),st(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Fo(o.source)}|null)$`):void 0}),st(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)}),k0=ie("$ZodDefault",(t,r)=>{ft.init(t,r),t._zod.optin="optional",st(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=>Os(f,r)):Os(u,r)}});function Os(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const R0=ie("$ZodPrefault",(t,r)=>{ft.init(t,r),t._zod.optin="optional",st(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))}),M0=ie("$ZodNonOptional",(t,r)=>{ft.init(t,r),st(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=>ks(f,t)):ks(u,t)}});function ks(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 D0=ie("$ZodCatch",(t,r)=>{ft.init(t,r),t._zod.optin="optional",st(t._zod,"optout",()=>r.innerType._zod.optout),st(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=>tr(m,c,er()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>tr(f,c,er()))},input:o.value}),o.issues=[]),o)}}),P0=ie("$ZodPipe",(t,r)=>{ft.init(t,r),st(t._zod,"values",()=>r.in._zod.values),st(t._zod,"optin",()=>r.in._zod.optin),st(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=>Rs(f,r,c)):Rs(u,r,c)}});function Rs(t,r,o){return Gr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const B0=ie("$ZodReadonly",(t,r)=>{ft.init(t,r),st(t._zod,"propValues",()=>r.innerType._zod.propValues),st(t._zod,"values",()=>r.innerType._zod.values),st(t._zod,"optin",()=>r.innerType._zod.optin),st(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(Ms):Ms(u)}});function Ms(t){return t.value=Object.freeze(t.value),t}const L0=ie("$ZodLazy",(t,r)=>{ft.init(t,r),st(t._zod,"innerType",()=>r.getter()),st(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),st(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),st(t._zod,"optin",()=>t._zod.innerType._zod.optin),st(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),F0=ie("$ZodCustom",(t,r)=>{an.init(t,r),ft.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=>Ds(f,o,c,t));Ds(u,o,c,t)}});function Ds(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(Kr(u))}}class hc{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 U0(){return new hc}const jr=U0();function z0(t,r){return new t({type:"string",...Ne(r)})}function V0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Ne(r)})}function Ps(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Ne(r)})}function Z0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Ne(r)})}function $0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ne(r)})}function j0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ne(r)})}function H0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ne(r)})}function W0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Ne(r)})}function G0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Ne(r)})}function X0(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ne(r)})}function q0(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Ne(r)})}function Y0(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ne(r)})}function K0(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Ne(r)})}function J0(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Ne(r)})}function Q0(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ne(r)})}function ef(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ne(r)})}function tf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ne(r)})}function nf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ne(r)})}function rf(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ne(r)})}function of(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Ne(r)})}function sf(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Ne(r)})}function af(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Ne(r)})}function lf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Ne(r)})}function cf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ne(r)})}function uf(t,r){return new t({type:"string",format:"date",check:"string_format",...Ne(r)})}function df(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Ne(r)})}function ff(t,r){return new t({type:"string",format:"duration",check:"string_format",...Ne(r)})}function hf(t,r){return new t({type:"number",checks:[],...Ne(r)})}function pf(t,r){return new t({type:"number",coerce:!0,checks:[],...Ne(r)})}function mf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Ne(r)})}function gf(t,r){return new t({type:"boolean",...Ne(r)})}function xf(t,r){return new t({type:"null",...Ne(r)})}function yf(t){return new t({type:"any"})}function wf(t){return new t({type:"unknown"})}function _f(t,r){return new t({type:"never",...Ne(r)})}function Bs(t,r){return new lc({check:"less_than",...Ne(r),value:t,inclusive:!1})}function oo(t,r){return new lc({check:"less_than",...Ne(r),value:t,inclusive:!0})}function Ls(t,r){return new cc({check:"greater_than",...Ne(r),value:t,inclusive:!1})}function so(t,r){return new cc({check:"greater_than",...Ne(r),value:t,inclusive:!0})}function Fs(t,r){return new O1({check:"multiple_of",...Ne(r),value:t})}function pc(t,r){return new R1({check:"max_length",...Ne(r),maximum:t})}function Ni(t,r){return new M1({check:"min_length",...Ne(r),minimum:t})}function mc(t,r){return new D1({check:"length_equals",...Ne(r),length:t})}function vf(t,r){return new P1({check:"string_format",format:"regex",...Ne(r),pattern:t})}function Cf(t){return new B1({check:"string_format",format:"lowercase",...Ne(t)})}function bf(t){return new L1({check:"string_format",format:"uppercase",...Ne(t)})}function Af(t,r){return new F1({check:"string_format",format:"includes",...Ne(r),includes:t})}function Ef(t,r){return new U1({check:"string_format",format:"starts_with",...Ne(r),prefix:t})}function If(t,r){return new z1({check:"string_format",format:"ends_with",...Ne(r),suffix:t})}function ri(t){return new V1({check:"overwrite",tx:t})}function Sf(t){return ri(r=>r.normalize(t))}function Tf(){return ri(t=>t.trim())}function Nf(){return ri(t=>t.toLowerCase())}function Of(){return ri(t=>t.toUpperCase())}function kf(t,r,o){return new t({type:"array",element:r,...Ne(o)})}function Rf(t,r,o){return new t({type:"custom",check:"custom",fn:r,...Ne(o)})}class Us{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 g={schema:{},count:1,cycle:void 0,path:o.path};this.seen.set(r,g);const v=r._zod.toJSONSchema?.();if(v)g.schema=v;else{const A={...o,schemaPath:[...o.schemaPath,r],path:o.path},M=r._zod.parent;if(M)g.ref=M,this.process(M,A),this.seen.get(M).isParent=!0;else{const T=g.schema;switch(u.type){case"string":{const S=T;S.type="string";const{minimum:B,maximum:D,format:ne,patterns:z,contentEncoding:Z}=r._zod.bag;if(typeof B=="number"&&(S.minLength=B),typeof D=="number"&&(S.maxLength=D),ne&&(S.format=f[ne]??ne,S.format===""&&delete S.format),Z&&(S.contentEncoding=Z),z&&z.size>0){const re=[...z];re.length===1?S.pattern=re[0].source:re.length>1&&(g.schema.allOf=[...re.map($=>({...this.target==="draft-7"?{type:"string"}:{},pattern:$.source}))])}break}case"number":{const S=T,{minimum:B,maximum:D,format:ne,multipleOf:z,exclusiveMaximum:Z,exclusiveMinimum:re}=r._zod.bag;typeof ne=="string"&&ne.includes("int")?S.type="integer":S.type="number",typeof re=="number"&&(S.exclusiveMinimum=re),typeof B=="number"&&(S.minimum=B,typeof re=="number"&&(re>=B?delete S.minimum:delete S.exclusiveMinimum)),typeof Z=="number"&&(S.exclusiveMaximum=Z),typeof D=="number"&&(S.maximum=D,typeof Z=="number"&&(Z<=D?delete S.maximum:delete S.exclusiveMaximum)),typeof z=="number"&&(S.multipleOf=z);break}case"boolean":{const S=T;S.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":{T.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":{T.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const S=T,{minimum:B,maximum:D}=r._zod.bag;typeof B=="number"&&(S.minItems=B),typeof D=="number"&&(S.maxItems=D),S.type="array",S.items=this.process(u.element,{...A,path:[...A.path,"items"]});break}case"object":{const S=T;S.type="object",S.properties={};const B=u.shape;for(const z in B)S.properties[z]=this.process(B[z],{...A,path:[...A.path,"properties",z]});const D=new Set(Object.keys(B)),ne=new Set([...D].filter(z=>{const Z=u.shape[z]._zod;return this.io==="input"?Z.optin===void 0:Z.optout===void 0}));ne.size>0&&(S.required=Array.from(ne)),u.catchall?._zod.def.type==="never"?S.additionalProperties=!1:u.catchall?u.catchall&&(S.additionalProperties=this.process(u.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(S.additionalProperties=!1);break}case"union":{const S=T;S.anyOf=u.options.map((B,D)=>this.process(B,{...A,path:[...A.path,"anyOf",D]}));break}case"intersection":{const S=T,B=this.process(u.left,{...A,path:[...A.path,"allOf",0]}),D=this.process(u.right,{...A,path:[...A.path,"allOf",1]}),ne=Z=>"allOf"in Z&&Object.keys(Z).length===1,z=[...ne(B)?B.allOf:[B],...ne(D)?D.allOf:[D]];S.allOf=z;break}case"tuple":{const S=T;S.type="array";const B=u.items.map((z,Z)=>this.process(z,{...A,path:[...A.path,"prefixItems",Z]}));if(this.target==="draft-2020-12"?S.prefixItems=B:S.items=B,u.rest){const z=this.process(u.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?S.items=z:S.additionalItems=z}u.rest&&(S.items=this.process(u.rest,{...A,path:[...A.path,"items"]}));const{minimum:D,maximum:ne}=r._zod.bag;typeof D=="number"&&(S.minItems=D),typeof ne=="number"&&(S.maxItems=ne);break}case"record":{const S=T;S.type="object",S.propertyNames=this.process(u.keyType,{...A,path:[...A.path,"propertyNames"]}),S.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 S=T,B=Kl(u.entries);B.every(D=>typeof D=="number")&&(S.type="number"),B.every(D=>typeof D=="string")&&(S.type="string"),S.enum=B;break}case"literal":{const S=T,B=[];for(const D of u.values)if(D===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof D=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");B.push(Number(D))}else B.push(D);if(B.length!==0)if(B.length===1){const D=B[0];S.type=D===null?"null":typeof D,S.const=D}else B.every(D=>typeof D=="number")&&(S.type="number"),B.every(D=>typeof D=="string")&&(S.type="string"),B.every(D=>typeof D=="boolean")&&(S.type="string"),B.every(D=>D===null)&&(S.type="null"),S.enum=B;break}case"file":{const S=T,B={type:"string",format:"binary",contentEncoding:"binary"},{minimum:D,maximum:ne,mime:z}=r._zod.bag;D!==void 0&&(B.minLength=D),ne!==void 0&&(B.maxLength=ne),z?z.length===1?(B.contentMediaType=z[0],Object.assign(S,B)):S.anyOf=z.map(Z=>({...B,contentMediaType:Z})):Object.assign(S,B);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const S=this.process(u.innerType,A);T.anyOf=[S,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,A),g.ref=u.innerType;break}case"success":{const S=T;S.type="boolean";break}case"default":{this.process(u.innerType,A),g.ref=u.innerType,T.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,A),g.ref=u.innerType,this.io==="input"&&(T._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,A),g.ref=u.innerType;let S;try{S=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}T.default=S;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const S=T,B=r._zod.pattern;if(!B)throw new Error("Pattern not found in template literal");S.type="string",S.pattern=B.source;break}case"pipe":{const S=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(S,A),g.ref=S;break}case"readonly":{this.process(u.innerType,A),g.ref=u.innerType,T.readOnly=!0;break}case"promise":{this.process(u.innerType,A),g.ref=u.innerType;break}case"optional":{this.process(u.innerType,A),g.ref=u.innerType;break}case"lazy":{const S=r._zod.innerType;this.process(S,A),g.ref=S;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const x=this.metadataRegistry.get(r);return x&&Object.assign(g.schema,x),this.io==="input"&&Ut(r)&&(delete g.schema.examples,delete g.schema.default),this.io==="input"&&g.schema._prefault&&((c=g.schema).default??(c.default=g.schema._prefault)),delete g.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=E=>{const A=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const B=c.external.registry.get(E[0])?.id,D=c.external.uri??(z=>z);if(B)return{ref:D(B)};const ne=E[1].defId??E[1].schema.id??`schema${this.counter++}`;return E[1].defId=ne,{defId:ne,ref:`${D("__shared")}#/${A}/${ne}`}}if(E[1]===u)return{ref:"#"};const T=`#/${A}/`,S=E[1].schema.id??`__schema${this.counter++}`;return{defId:S,ref:T+S}},m=E=>{if(E[1].schema.$ref)return;const A=E[1],{ref:M,defId:T}=f(E);A.def={...A.schema},T&&(A.defId=T);const S=A.schema;for(const B in S)delete S[B];S.$ref=M};if(c.cycles==="throw")for(const E of this.seen.entries()){const A=E[1];if(A.cycle)throw new Error(`Cycle detected: #/${A.cycle?.join("/")}/<root>
36
+ path: iss.path ? [${Zr($)}, ...iss.path] : [${Zr($)}]
37
+ })));`),D.write(`newResult[${Zr($)}] = ${F}.value`)}D.write("payload.value = newResult;"),D.write("return payload;");const ee=D.compile();return($,F)=>ee(A,$,F)};let d;const f=ko,m=!tc.jitless,v=m&&Wd.value,g=r.catchall;let E;t._zod.parse=(A,D)=>{E??(E=i.value);const T=A.value;if(!f(T))return A.issues.push({expected:"object",code:"invalid_type",input:T,inst:t}),A;const S=[];if(m&&v&&D?.async===!1&&D.jitless!==!0)d||(d=c(r.shape)),A=d(A,D);else{A.value={};const F=E.shape;for(const re of E.keys){const Z=F[re],B=Z._zod.run({value:T[re],issues:[]},D),L=Z._zod.optin==="optional"&&Z._zod.optout==="optional";B instanceof Promise?S.push(B.then(W=>L?Os(W,A,re,T):vo(W,A,re))):L?Os(B,A,re,T):vo(B,A,re)}}if(!g)return S.length?Promise.all(S).then(()=>A):A;const P=[],M=E.keySet,ee=g._zod,$=ee.def.type;for(const F of Object.keys(T)){if(M.has(F))continue;if($==="never"){P.push(F);continue}const re=ee.run({value:T[F],issues:[]},D);re instanceof Promise?S.push(re.then(Z=>vo(Z,A,F))):vo(re,A,F)}return P.length&&A.issues.push({code:"unrecognized_keys",keys:P,input:T,inst:t}),S.length?Promise.all(S).then(()=>A):A}});function ks(t,r,i,c){for(const d of t)if(d.issues.length===0)return r.value=d.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:i,errors:t.map(d=>d.issues.map(f=>er(f,c,Qn())))}),r}const xc=oe("$ZodUnion",(t,r)=>{ht.init(t,r),lt(t._zod,"optin",()=>r.options.some(i=>i._zod.optin==="optional")?"optional":void 0),lt(t._zod,"optout",()=>r.options.some(i=>i._zod.optout==="optional")?"optional":void 0),lt(t._zod,"values",()=>{if(r.options.every(i=>i._zod.values))return new Set(r.options.flatMap(i=>Array.from(i._zod.values)))}),lt(t._zod,"pattern",()=>{if(r.options.every(i=>i._zod.pattern)){const i=r.options.map(c=>c._zod.pattern);return new RegExp(`^(${i.map(c=>Vi(c.source)).join("|")})$`)}}),t._zod.parse=(i,c)=>{let d=!1;const f=[];for(const m of r.options){const x=m._zod.run({value:i.value,issues:[]},c);if(x instanceof Promise)f.push(x),d=!0;else{if(x.issues.length===0)return x;f.push(x)}}return d?Promise.all(f).then(m=>ks(m,i,t,c)):ks(f,i,t,c)}}),N0=oe("$ZodDiscriminatedUnion",(t,r)=>{xc.init(t,r);const i=t._zod.parse;lt(t._zod,"propValues",()=>{const d={};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,v]of Object.entries(m)){d[x]||(d[x]=new Set);for(const g of v)d[x].add(g)}}return d});const c=Ui(()=>{const d=r.options,f=new Map;for(const m of d){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 v of x){if(f.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);f.set(v,m)}}return f});t._zod.parse=(d,f)=>{const m=d.value;if(!ko(m))return d.issues.push({code:"invalid_type",expected:"object",input:m,inst:t}),d;const x=c.value.get(m?.[r.discriminator]);return x?x._zod.run(d,f):r.unionFallback?i(d,f):(d.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:m,path:[r.discriminator],inst:t}),d)}}),O0=oe("$ZodIntersection",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value,f=r.left._zod.run({value:d,issues:[]},c),m=r.right._zod.run({value:d,issues:[]},c);return f instanceof Promise||m instanceof Promise?Promise.all([f,m]).then(([v,g])=>Rs(i,v,g)):Rs(i,f,m)}});function bi(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(Ro(t)&&Ro(r)){const i=Object.keys(r),c=Object.keys(t).filter(f=>i.indexOf(f)!==-1),d={...t,...r};for(const f of c){const m=bi(t[f],r[f]);if(!m.valid)return{valid:!1,mergeErrorPath:[f,...m.mergeErrorPath]};d[f]=m.data}return{valid:!0,data:d}}if(Array.isArray(t)&&Array.isArray(r)){if(t.length!==r.length)return{valid:!1,mergeErrorPath:[]};const i=[];for(let c=0;c<t.length;c++){const d=t[c],f=r[c],m=bi(d,f);if(!m.valid)return{valid:!1,mergeErrorPath:[c,...m.mergeErrorPath]};i.push(m.data)}return{valid:!0,data:i}}return{valid:!1,mergeErrorPath:[]}}function Rs(t,r,i){if(r.issues.length&&t.issues.push(...r.issues),i.issues.length&&t.issues.push(...i.issues),Yr(t))return t;const c=bi(r.value,i.value);if(!c.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`);return t.value=c.data,t}const k0=oe("$ZodRecord",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=i.value;if(!Ro(d))return i.issues.push({expected:"record",code:"invalid_type",input:d,inst:t}),i;const f=[];if(r.keyType._zod.values){const m=r.keyType._zod.values;i.value={};for(const v of m)if(typeof v=="string"||typeof v=="number"||typeof v=="symbol"){const g=r.valueType._zod.run({value:d[v],issues:[]},c);g instanceof Promise?f.push(g.then(E=>{E.issues.length&&i.issues.push(...hr(v,E.issues)),i.value[v]=E.value})):(g.issues.length&&i.issues.push(...hr(v,g.issues)),i.value[v]=g.value)}let x;for(const v in d)m.has(v)||(x=x??[],x.push(v));x&&x.length>0&&i.issues.push({code:"unrecognized_keys",input:d,inst:t,keys:x})}else{i.value={};for(const m of Reflect.ownKeys(d)){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){i.issues.push({origin:"record",code:"invalid_key",issues:x.issues.map(g=>er(g,c,Qn())),input:m,path:[m],inst:t}),i.value[x.value]=x.value;continue}const v=r.valueType._zod.run({value:d[m],issues:[]},c);v instanceof Promise?f.push(v.then(g=>{g.issues.length&&i.issues.push(...hr(m,g.issues)),i.value[x.value]=g.value})):(v.issues.length&&i.issues.push(...hr(m,v.issues)),i.value[x.value]=v.value)}}return f.length?Promise.all(f).then(()=>i):i}}),R0=oe("$ZodEnum",(t,r)=>{ht.init(t,r);const i=nc(r.entries);t._zod.values=new Set(i),t._zod.pattern=new RegExp(`^(${i.filter(c=>Gd.has(typeof c)).map(c=>typeof c=="string"?io(c):c.toString()).join("|")})$`),t._zod.parse=(c,d)=>{const f=c.value;return t._zod.values.has(f)||c.issues.push({code:"invalid_value",values:i,input:f,inst:t}),c}}),M0=oe("$ZodLiteral",(t,r)=>{ht.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(i=>typeof i=="string"?io(i):i?i.toString():String(i)).join("|")})$`),t._zod.parse=(i,c)=>{const d=i.value;return t._zod.values.has(d)||i.issues.push({code:"invalid_value",values:r.values,input:d,inst:t}),i}}),D0=oe("$ZodTransform",(t,r)=>{ht.init(t,r),t._zod.parse=(i,c)=>{const d=r.transform(i.value,i);if(c.async)return(d instanceof Promise?d:Promise.resolve(d)).then(m=>(i.value=m,i));if(d instanceof Promise)throw new Qr;return i.value=d,i}}),P0=oe("$ZodOptional",(t,r)=>{ht.init(t,r),t._zod.optin="optional",t._zod.optout="optional",lt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),lt(t._zod,"pattern",()=>{const i=r.innerType._zod.pattern;return i?new RegExp(`^(${Vi(i.source)})?$`):void 0}),t._zod.parse=(i,c)=>r.innerType._zod.optin==="optional"?r.innerType._zod.run(i,c):i.value===void 0?i:r.innerType._zod.run(i,c)}),B0=oe("$ZodNullable",(t,r)=>{ht.init(t,r),lt(t._zod,"optin",()=>r.innerType._zod.optin),lt(t._zod,"optout",()=>r.innerType._zod.optout),lt(t._zod,"pattern",()=>{const i=r.innerType._zod.pattern;return i?new RegExp(`^(${Vi(i.source)}|null)$`):void 0}),lt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,null]):void 0),t._zod.parse=(i,c)=>i.value===null?i:r.innerType._zod.run(i,c)}),L0=oe("$ZodDefault",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>{if(i.value===void 0)return i.value=r.defaultValue,i;const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>Ms(f,r)):Ms(d,r)}});function Ms(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const F0=oe("$ZodPrefault",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>(i.value===void 0&&(i.value=r.defaultValue),r.innerType._zod.run(i,c))}),U0=oe("$ZodNonOptional",(t,r)=>{ht.init(t,r),lt(t._zod,"values",()=>{const i=r.innerType._zod.values;return i?new Set([...i].filter(c=>c!==void 0)):void 0}),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>Ds(f,t)):Ds(d,t)}});function Ds(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 z0=oe("$ZodCatch",(t,r)=>{ht.init(t,r),t._zod.optin="optional",lt(t._zod,"optout",()=>r.innerType._zod.optout),lt(t._zod,"values",()=>r.innerType._zod.values),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(f=>(i.value=f.value,f.issues.length&&(i.value=r.catchValue({...i,error:{issues:f.issues.map(m=>er(m,c,Qn()))},input:i.value}),i.issues=[]),i)):(i.value=d.value,d.issues.length&&(i.value=r.catchValue({...i,error:{issues:d.issues.map(f=>er(f,c,Qn()))},input:i.value}),i.issues=[]),i)}}),V0=oe("$ZodPipe",(t,r)=>{ht.init(t,r),lt(t._zod,"values",()=>r.in._zod.values),lt(t._zod,"optin",()=>r.in._zod.optin),lt(t._zod,"optout",()=>r.out._zod.optout),t._zod.parse=(i,c)=>{const d=r.in._zod.run(i,c);return d instanceof Promise?d.then(f=>Ps(f,r,c)):Ps(d,r,c)}});function Ps(t,r,i){return Yr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},i)}const Z0=oe("$ZodReadonly",(t,r)=>{ht.init(t,r),lt(t._zod,"propValues",()=>r.innerType._zod.propValues),lt(t._zod,"values",()=>r.innerType._zod.values),lt(t._zod,"optin",()=>r.innerType._zod.optin),lt(t._zod,"optout",()=>r.innerType._zod.optout),t._zod.parse=(i,c)=>{const d=r.innerType._zod.run(i,c);return d instanceof Promise?d.then(Bs):Bs(d)}});function Bs(t){return t.value=Object.freeze(t.value),t}const $0=oe("$ZodLazy",(t,r)=>{ht.init(t,r),lt(t._zod,"innerType",()=>r.getter()),lt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),lt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),lt(t._zod,"optin",()=>t._zod.innerType._zod.optin),lt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(i,c)=>t._zod.innerType._zod.run(i,c)}),j0=oe("$ZodCustom",(t,r)=>{on.init(t,r),ht.init(t,r),t._zod.parse=(i,c)=>i,t._zod.check=i=>{const c=i.value,d=r.fn(c);if(d instanceof Promise)return d.then(f=>Ls(f,i,c,t));Ls(d,i,c,t)}});function Ls(t,r,i,c){if(!t){const d={code:"custom",input:i,inst:c,path:[...c._zod.def.path??[]],continue:!c._zod.def.abort};c._zod.def.params&&(d.params=c._zod.def.params),r.issues.push(eo(d))}}class yc{constructor(){this._map=new Map,this._idmap=new Map}add(r,...i){const c=i[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 i=this._map.get(r);return i&&typeof i=="object"&&"id"in i&&this._idmap.delete(i.id),this._map.delete(r),this}get(r){const i=r._zod.parent;if(i){const c={...this.get(i)??{}};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 yc}const Gr=H0();function W0(t,r){return new t({type:"string",...Ie(r)})}function G0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Ie(r)})}function Fs(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Ie(r)})}function q0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Ie(r)})}function X0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ie(r)})}function Y0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ie(r)})}function K0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ie(r)})}function J0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Ie(r)})}function Q0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Ie(r)})}function ef(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ie(r)})}function tf(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Ie(r)})}function nf(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ie(r)})}function rf(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Ie(r)})}function of(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Ie(r)})}function sf(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ie(r)})}function af(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ie(r)})}function lf(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ie(r)})}function cf(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ie(r)})}function uf(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ie(r)})}function df(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Ie(r)})}function ff(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Ie(r)})}function hf(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Ie(r)})}function pf(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Ie(r)})}function mf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ie(r)})}function gf(t,r){return new t({type:"string",format:"date",check:"string_format",...Ie(r)})}function xf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Ie(r)})}function yf(t,r){return new t({type:"string",format:"duration",check:"string_format",...Ie(r)})}function wf(t,r){return new t({type:"number",checks:[],...Ie(r)})}function _f(t,r){return new t({type:"number",coerce:!0,checks:[],...Ie(r)})}function vf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Ie(r)})}function Cf(t,r){return new t({type:"boolean",...Ie(r)})}function bf(t,r){return new t({type:"null",...Ie(r)})}function Af(t){return new t({type:"any"})}function Ef(t){return new t({type:"unknown"})}function If(t,r){return new t({type:"never",...Ie(r)})}function Us(t,r){return new hc({check:"less_than",...Ie(r),value:t,inclusive:!1})}function ci(t,r){return new hc({check:"less_than",...Ie(r),value:t,inclusive:!0})}function zs(t,r){return new pc({check:"greater_than",...Ie(r),value:t,inclusive:!1})}function ui(t,r){return new pc({check:"greater_than",...Ie(r),value:t,inclusive:!0})}function Vs(t,r){return new B1({check:"multiple_of",...Ie(r),value:t})}function wc(t,r){return new F1({check:"max_length",...Ie(r),maximum:t})}function Mo(t,r){return new U1({check:"min_length",...Ie(r),minimum:t})}function _c(t,r){return new z1({check:"length_equals",...Ie(r),length:t})}function Sf(t,r){return new V1({check:"string_format",format:"regex",...Ie(r),pattern:t})}function Tf(t){return new Z1({check:"string_format",format:"lowercase",...Ie(t)})}function Nf(t){return new $1({check:"string_format",format:"uppercase",...Ie(t)})}function Of(t,r){return new j1({check:"string_format",format:"includes",...Ie(r),includes:t})}function kf(t,r){return new H1({check:"string_format",format:"starts_with",...Ie(r),prefix:t})}function Rf(t,r){return new W1({check:"string_format",format:"ends_with",...Ie(r),suffix:t})}function so(t){return new G1({check:"overwrite",tx:t})}function Mf(t){return so(r=>r.normalize(t))}function Df(){return so(t=>t.trim())}function Pf(){return so(t=>t.toLowerCase())}function Bf(){return so(t=>t.toUpperCase())}function Lf(t,r,i){return new t({type:"array",element:r,...Ie(i)})}function Ff(t,r,i){return new t({type:"custom",check:"custom",fn:r,...Ie(i)})}class Zs{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??Gr,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,i={path:[],schemaPath:[]}){var c;const d=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++,i.schemaPath.includes(r)&&(m.cycle=i.path),m.schema;const x={schema:{},count:1,cycle:void 0,path:i.path};this.seen.set(r,x);const v=r._zod.toJSONSchema?.();if(v)x.schema=v;else{const A={...i,schemaPath:[...i.schemaPath,r],path:i.path},D=r._zod.parent;if(D)x.ref=D,this.process(D,A),this.seen.get(D).isParent=!0;else{const T=x.schema;switch(d.type){case"string":{const S=T;S.type="string";const{minimum:P,maximum:M,format:ee,patterns:$,contentEncoding:F}=r._zod.bag;if(typeof P=="number"&&(S.minLength=P),typeof M=="number"&&(S.maxLength=M),ee&&(S.format=f[ee]??ee,S.format===""&&delete S.format),F&&(S.contentEncoding=F),$&&$.size>0){const re=[...$];re.length===1?S.pattern=re[0].source:re.length>1&&(x.schema.allOf=[...re.map(Z=>({...this.target==="draft-7"?{type:"string"}:{},pattern:Z.source}))])}break}case"number":{const S=T,{minimum:P,maximum:M,format:ee,multipleOf:$,exclusiveMaximum:F,exclusiveMinimum:re}=r._zod.bag;typeof ee=="string"&&ee.includes("int")?S.type="integer":S.type="number",typeof re=="number"&&(S.exclusiveMinimum=re),typeof P=="number"&&(S.minimum=P,typeof re=="number"&&(re>=P?delete S.minimum:delete S.exclusiveMinimum)),typeof F=="number"&&(S.exclusiveMaximum=F),typeof M=="number"&&(S.maximum=M,typeof F=="number"&&(F<=M?delete S.maximum:delete S.exclusiveMaximum)),typeof $=="number"&&(S.multipleOf=$);break}case"boolean":{const S=T;S.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":{T.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":{T.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const S=T,{minimum:P,maximum:M}=r._zod.bag;typeof P=="number"&&(S.minItems=P),typeof M=="number"&&(S.maxItems=M),S.type="array",S.items=this.process(d.element,{...A,path:[...A.path,"items"]});break}case"object":{const S=T;S.type="object",S.properties={};const P=d.shape;for(const $ in P)S.properties[$]=this.process(P[$],{...A,path:[...A.path,"properties",$]});const M=new Set(Object.keys(P)),ee=new Set([...M].filter($=>{const F=d.shape[$]._zod;return this.io==="input"?F.optin===void 0:F.optout===void 0}));ee.size>0&&(S.required=Array.from(ee)),d.catchall?._zod.def.type==="never"?S.additionalProperties=!1:d.catchall?d.catchall&&(S.additionalProperties=this.process(d.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(S.additionalProperties=!1);break}case"union":{const S=T;S.anyOf=d.options.map((P,M)=>this.process(P,{...A,path:[...A.path,"anyOf",M]}));break}case"intersection":{const S=T,P=this.process(d.left,{...A,path:[...A.path,"allOf",0]}),M=this.process(d.right,{...A,path:[...A.path,"allOf",1]}),ee=F=>"allOf"in F&&Object.keys(F).length===1,$=[...ee(P)?P.allOf:[P],...ee(M)?M.allOf:[M]];S.allOf=$;break}case"tuple":{const S=T;S.type="array";const P=d.items.map(($,F)=>this.process($,{...A,path:[...A.path,"prefixItems",F]}));if(this.target==="draft-2020-12"?S.prefixItems=P:S.items=P,d.rest){const $=this.process(d.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?S.items=$:S.additionalItems=$}d.rest&&(S.items=this.process(d.rest,{...A,path:[...A.path,"items"]}));const{minimum:M,maximum:ee}=r._zod.bag;typeof M=="number"&&(S.minItems=M),typeof ee=="number"&&(S.maxItems=ee);break}case"record":{const S=T;S.type="object",S.propertyNames=this.process(d.keyType,{...A,path:[...A.path,"propertyNames"]}),S.additionalProperties=this.process(d.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 S=T,P=nc(d.entries);P.every(M=>typeof M=="number")&&(S.type="number"),P.every(M=>typeof M=="string")&&(S.type="string"),S.enum=P;break}case"literal":{const S=T,P=[];for(const M of d.values)if(M===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof M=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");P.push(Number(M))}else P.push(M);if(P.length!==0)if(P.length===1){const M=P[0];S.type=M===null?"null":typeof M,S.const=M}else P.every(M=>typeof M=="number")&&(S.type="number"),P.every(M=>typeof M=="string")&&(S.type="string"),P.every(M=>typeof M=="boolean")&&(S.type="string"),P.every(M=>M===null)&&(S.type="null"),S.enum=P;break}case"file":{const S=T,P={type:"string",format:"binary",contentEncoding:"binary"},{minimum:M,maximum:ee,mime:$}=r._zod.bag;M!==void 0&&(P.minLength=M),ee!==void 0&&(P.maxLength=ee),$?$.length===1?(P.contentMediaType=$[0],Object.assign(S,P)):S.anyOf=$.map(F=>({...P,contentMediaType:F})):Object.assign(S,P);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const S=this.process(d.innerType,A);T.anyOf=[S,{type:"null"}];break}case"nonoptional":{this.process(d.innerType,A),x.ref=d.innerType;break}case"success":{const S=T;S.type="boolean";break}case"default":{this.process(d.innerType,A),x.ref=d.innerType,T.default=JSON.parse(JSON.stringify(d.defaultValue));break}case"prefault":{this.process(d.innerType,A),x.ref=d.innerType,this.io==="input"&&(T._prefault=JSON.parse(JSON.stringify(d.defaultValue)));break}case"catch":{this.process(d.innerType,A),x.ref=d.innerType;let S;try{S=d.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}T.default=S;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const S=T,P=r._zod.pattern;if(!P)throw new Error("Pattern not found in template literal");S.type="string",S.pattern=P.source;break}case"pipe":{const S=this.io==="input"?d.in._zod.def.type==="transform"?d.out:d.in:d.out;this.process(S,A),x.ref=S;break}case"readonly":{this.process(d.innerType,A),x.ref=d.innerType,T.readOnly=!0;break}case"promise":{this.process(d.innerType,A),x.ref=d.innerType;break}case"optional":{this.process(d.innerType,A),x.ref=d.innerType;break}case"lazy":{const S=r._zod.innerType;this.process(S,A),x.ref=S;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"&&Lt(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,i){const c={cycles:i?.cycles??"ref",reused:i?.reused??"inline",external:i?.external??void 0},d=this.seen.get(r);if(!d)throw new Error("Unprocessed schema. This is a bug in Zod.");const f=E=>{const A=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const P=c.external.registry.get(E[0])?.id,M=c.external.uri??($=>$);if(P)return{ref:M(P)};const ee=E[1].defId??E[1].schema.id??`schema${this.counter++}`;return E[1].defId=ee,{defId:ee,ref:`${M("__shared")}#/${A}/${ee}`}}if(E[1]===d)return{ref:"#"};const T=`#/${A}/`,S=E[1].schema.id??`__schema${this.counter++}`;return{defId:S,ref:T+S}},m=E=>{if(E[1].schema.$ref)return;const A=E[1],{ref:D,defId:T}=f(E);A.def={...A.schema},T&&(A.defId=T);const S=A.schema;for(const P in S)delete S[P];S.$ref=D};if(c.cycles==="throw")for(const E of this.seen.entries()){const A=E[1];if(A.cycle)throw new Error(`Cycle detected: #/${A.cycle?.join("/")}/<root>
38
38
 
39
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const E of this.seen.entries()){const A=E[1];if(r===E[0]){m(E);continue}if(c.external){const T=c.external.registry.get(E[0])?.id;if(r!==E[0]&&T){m(E);continue}}if(this.metadataRegistry.get(E[0])?.id){m(E);continue}if(A.cycle){m(E);continue}if(A.count>1&&c.reused==="ref"){m(E);continue}}const g=(E,A)=>{const M=this.seen.get(E),T=M.def??M.schema,S={...T};if(M.ref===null)return;const B=M.ref;if(M.ref=null,B){g(B,A);const D=this.seen.get(B).schema;D.$ref&&A.target==="draft-7"?(T.allOf=T.allOf??[],T.allOf.push(D)):(Object.assign(T,D),Object.assign(T,S))}M.isParent||this.override({zodSchema:E,jsonSchema:T,path:M.path??[]})};for(const E of[...this.seen.entries()].reverse())g(E[0],{target:this.target});const v={};if(this.target==="draft-2020-12"?v.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?v.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const E=c.external.registry.get(r)?.id;if(!E)throw new Error("Schema is missing an `id` property");v.$id=c.external.uri(E)}Object.assign(v,u.def);const x=c.external?.defs??{};for(const E of this.seen.entries()){const A=E[1];A.def&&A.defId&&(x[A.defId]=A.def)}c.external||Object.keys(x).length>0&&(this.target==="draft-2020-12"?v.$defs=x:v.definitions=x);try{return JSON.parse(JSON.stringify(v))}catch{throw new Error("Error converting schema to JSON.")}}}function Mf(t,r){if(t instanceof hc){const c=new Us(r),u={};for(const g of t._idmap.entries()){const[v,x]=g;c.process(x)}const f={},m={registry:t,uri:r?.uri,defs:u};for(const g of t._idmap.entries()){const[v,x]=g;f[v]=c.emit(x,{...r,external:m})}if(Object.keys(u).length>0){const g=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[g]:u}}return{schemas:f}}const o=new Us(r);return o.process(t),o.emit(t,r)}function Ut(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 Ut(u.element,o);case"object":{for(const f in u.shape)if(Ut(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(Ut(f,o))return!0;return!1}case"intersection":return Ut(u.left,o)||Ut(u.right,o);case"tuple":{for(const f of u.items)if(Ut(f,o))return!0;return!!(u.rest&&Ut(u.rest,o))}case"record":return Ut(u.keyType,o)||Ut(u.valueType,o);case"map":return Ut(u.keyType,o)||Ut(u.valueType,o);case"set":return Ut(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ut(u.innerType,o);case"lazy":return Ut(u.getter(),o);case"default":return Ut(u.innerType,o);case"prefault":return Ut(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return Ut(u.in,o)||Ut(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const Df=ie("ZodISODateTime",(t,r)=>{t0.init(t,r),Et.init(t,r)});function Pf(t){return cf(Df,t)}const Bf=ie("ZodISODate",(t,r)=>{n0.init(t,r),Et.init(t,r)});function Lf(t){return uf(Bf,t)}const Ff=ie("ZodISOTime",(t,r)=>{r0.init(t,r),Et.init(t,r)});function Uf(t){return df(Ff,t)}const zf=ie("ZodISODuration",(t,r)=>{i0.init(t,r),Et.init(t,r)});function Vf(t){return ff(zf,t)}const Zf=(t,r)=>{ec.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>Kd(t,o)},flatten:{value:o=>Yd(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},Pi=ie("ZodError",Zf,{Parent:Error}),$f=Jd(Pi),jf=Qd(Pi),Hf=nc(Pi),gc=rc(Pi),wt=ie("ZodType",(t,r)=>(ft.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)=>gr(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>$f(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Hf(t,o,c),t.parseAsync=async(o,c)=>jf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>gc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(zh(o,c)),t.superRefine=o=>t.check(Vh(o)),t.overwrite=o=>t.check(ri(o)),t.optional=()=>Zs(t),t.nullable=()=>$s(t),t.nullish=()=>Zs($s(t)),t.nonoptional=o=>kh(t,o),t.array=()=>le(t),t.or=o=>it([t,o]),t.and=o=>vh(t,o),t.transform=o=>js(t,Eh(o)),t.default=o=>Th(t,o),t.prefault=o=>Oh(t,o),t.catch=o=>Mh(t,o),t.pipe=o=>js(t,o),t.readonly=()=>Bh(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)),xc=ie("_ZodString",(t,r)=>{Vo.init(t,r),wt.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(vf(...c)),t.includes=(...c)=>t.check(Af(...c)),t.startsWith=(...c)=>t.check(Ef(...c)),t.endsWith=(...c)=>t.check(If(...c)),t.min=(...c)=>t.check(Ni(...c)),t.max=(...c)=>t.check(pc(...c)),t.length=(...c)=>t.check(mc(...c)),t.nonempty=(...c)=>t.check(Ni(1,...c)),t.lowercase=c=>t.check(Cf(c)),t.uppercase=c=>t.check(bf(c)),t.trim=()=>t.check(Tf()),t.normalize=(...c)=>t.check(Sf(...c)),t.toLowerCase=()=>t.check(Nf()),t.toUpperCase=()=>t.check(Of())}),Wf=ie("ZodString",(t,r)=>{Vo.init(t,r),xc.init(t,r),t.email=o=>t.check(V0(Gf,o)),t.url=o=>t.check(W0(Xf,o)),t.jwt=o=>t.check(lf(ch,o)),t.emoji=o=>t.check(G0(qf,o)),t.guid=o=>t.check(Ps(zs,o)),t.uuid=o=>t.check(Z0(yi,o)),t.uuidv4=o=>t.check($0(yi,o)),t.uuidv6=o=>t.check(j0(yi,o)),t.uuidv7=o=>t.check(H0(yi,o)),t.nanoid=o=>t.check(X0(Yf,o)),t.guid=o=>t.check(Ps(zs,o)),t.cuid=o=>t.check(q0(Kf,o)),t.cuid2=o=>t.check(Y0(Jf,o)),t.ulid=o=>t.check(K0(Qf,o)),t.base64=o=>t.check(of(sh,o)),t.base64url=o=>t.check(sf(ah,o)),t.xid=o=>t.check(J0(eh,o)),t.ksuid=o=>t.check(Q0(th,o)),t.ipv4=o=>t.check(ef(nh,o)),t.ipv6=o=>t.check(tf(rh,o)),t.cidrv4=o=>t.check(nf(ih,o)),t.cidrv6=o=>t.check(rf(oh,o)),t.e164=o=>t.check(af(lh,o)),t.datetime=o=>t.check(Pf(o)),t.date=o=>t.check(Lf(o)),t.time=o=>t.check(Uf(o)),t.duration=o=>t.check(Vf(o))});function w(t){return z0(Wf,t)}const Et=ie("ZodStringFormat",(t,r)=>{Ct.init(t,r),xc.init(t,r)}),Gf=ie("ZodEmail",(t,r)=>{W1.init(t,r),Et.init(t,r)}),zs=ie("ZodGUID",(t,r)=>{j1.init(t,r),Et.init(t,r)}),yi=ie("ZodUUID",(t,r)=>{H1.init(t,r),Et.init(t,r)}),Xf=ie("ZodURL",(t,r)=>{G1.init(t,r),Et.init(t,r)}),qf=ie("ZodEmoji",(t,r)=>{X1.init(t,r),Et.init(t,r)}),Yf=ie("ZodNanoID",(t,r)=>{q1.init(t,r),Et.init(t,r)}),Kf=ie("ZodCUID",(t,r)=>{Y1.init(t,r),Et.init(t,r)}),Jf=ie("ZodCUID2",(t,r)=>{K1.init(t,r),Et.init(t,r)}),Qf=ie("ZodULID",(t,r)=>{J1.init(t,r),Et.init(t,r)}),eh=ie("ZodXID",(t,r)=>{Q1.init(t,r),Et.init(t,r)}),th=ie("ZodKSUID",(t,r)=>{e0.init(t,r),Et.init(t,r)}),nh=ie("ZodIPv4",(t,r)=>{o0.init(t,r),Et.init(t,r)}),rh=ie("ZodIPv6",(t,r)=>{s0.init(t,r),Et.init(t,r)}),ih=ie("ZodCIDRv4",(t,r)=>{a0.init(t,r),Et.init(t,r)}),oh=ie("ZodCIDRv6",(t,r)=>{l0.init(t,r),Et.init(t,r)}),sh=ie("ZodBase64",(t,r)=>{c0.init(t,r),Et.init(t,r)}),ah=ie("ZodBase64URL",(t,r)=>{d0.init(t,r),Et.init(t,r)}),lh=ie("ZodE164",(t,r)=>{f0.init(t,r),Et.init(t,r)}),ch=ie("ZodJWT",(t,r)=>{p0.init(t,r),Et.init(t,r)}),Zo=ie("ZodNumber",(t,r)=>{dc.init(t,r),wt.init(t,r),t.gt=(c,u)=>t.check(Ls(c,u)),t.gte=(c,u)=>t.check(so(c,u)),t.min=(c,u)=>t.check(so(c,u)),t.lt=(c,u)=>t.check(Bs(c,u)),t.lte=(c,u)=>t.check(oo(c,u)),t.max=(c,u)=>t.check(oo(c,u)),t.int=c=>t.check(Vs(c)),t.safe=c=>t.check(Vs(c)),t.positive=c=>t.check(Ls(0,c)),t.nonnegative=c=>t.check(so(0,c)),t.negative=c=>t.check(Bs(0,c)),t.nonpositive=c=>t.check(oo(0,c)),t.multipleOf=(c,u)=>t.check(Fs(c,u)),t.step=(c,u)=>t.check(Fs(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 j(t){return hf(Zo,t)}const uh=ie("ZodNumberFormat",(t,r)=>{m0.init(t,r),Zo.init(t,r)});function Vs(t){return mf(uh,t)}const dh=ie("ZodBoolean",(t,r)=>{g0.init(t,r),wt.init(t,r)});function Dt(t){return gf(dh,t)}const fh=ie("ZodNull",(t,r)=>{x0.init(t,r),wt.init(t,r)});function yc(t){return xf(fh,t)}const hh=ie("ZodAny",(t,r)=>{y0.init(t,r),wt.init(t,r)});function xr(){return yf(hh)}const ph=ie("ZodUnknown",(t,r)=>{w0.init(t,r),wt.init(t,r)});function An(){return wf(ph)}const mh=ie("ZodNever",(t,r)=>{_0.init(t,r),wt.init(t,r)});function gh(t){return _f(mh,t)}const xh=ie("ZodArray",(t,r)=>{v0.init(t,r),wt.init(t,r),t.element=r.element,t.min=(o,c)=>t.check(Ni(o,c)),t.nonempty=o=>t.check(Ni(1,o)),t.max=(o,c)=>t.check(pc(o,c)),t.length=(o,c)=>t.check(mc(o,c)),t.unwrap=()=>t.element});function le(t,r){return kf(xh,t,r)}const yh=ie("ZodObject",(t,r)=>{C0.init(t,r),wt.init(t,r),st(t,"shape",()=>r.shape),t.keyof=()=>Ee(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:An()}),t.loose=()=>t.clone({...t._zod.def,catchall:An()}),t.strict=()=>t.clone({...t._zod.def,catchall:gh()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Wd(t,o),t.merge=o=>Gd(t,o),t.pick=o=>jd(t,o),t.omit=o=>Hd(t,o),t.partial=(...o)=>Xd(_c,t,o[0]),t.required=(...o)=>qd(vc,t,o[0])});function N(t,r){const o={type:"object",get shape(){return Uo(this,"shape",{...t}),this.shape},...Ne(r)};return new yh(o)}const wc=ie("ZodUnion",(t,r)=>{fc.init(t,r),wt.init(t,r),t.options=r.options});function it(t,r){return new wc({type:"union",options:t,...Ne(r)})}const wh=ie("ZodDiscriminatedUnion",(t,r)=>{wc.init(t,r),b0.init(t,r)});function pt(t,r,o){return new wh({type:"union",options:r,discriminator:t,...Ne(o)})}const _h=ie("ZodIntersection",(t,r)=>{A0.init(t,r),wt.init(t,r)});function vh(t,r){return new _h({type:"intersection",left:t,right:r})}const Ch=ie("ZodRecord",(t,r)=>{E0.init(t,r),wt.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function yt(t,r,o){return new Ch({type:"record",keyType:t,valueType:r,...Ne(o)})}const vo=ie("ZodEnum",(t,r)=>{I0.init(t,r),wt.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 vo({...r,checks:[],...Ne(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 vo({...r,checks:[],...Ne(u),entries:f})}});function Ee(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new vo({type:"enum",entries:o,...Ne(r)})}const bh=ie("ZodLiteral",(t,r)=>{S0.init(t,r),wt.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 q(t,r){return new bh({type:"literal",values:Array.isArray(t)?t:[t],...Ne(r)})}const Ah=ie("ZodTransform",(t,r)=>{T0.init(t,r),wt.init(t,r),t._zod.parse=(o,c)=>{o.addIssue=f=>{if(typeof f=="string")o.issues.push(Kr(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(Kr(m))}};const u=r.transform(o.value,o);return u instanceof Promise?u.then(f=>(o.value=f,o)):(o.value=u,o)}});function Eh(t){return new Ah({type:"transform",transform:t})}const _c=ie("ZodOptional",(t,r)=>{N0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Zs(t){return new _c({type:"optional",innerType:t})}const Ih=ie("ZodNullable",(t,r)=>{O0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function $s(t){return new Ih({type:"nullable",innerType:t})}const Sh=ie("ZodDefault",(t,r)=>{k0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Th(t,r){return new Sh({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Nh=ie("ZodPrefault",(t,r)=>{R0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Oh(t,r){return new Nh({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const vc=ie("ZodNonOptional",(t,r)=>{M0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function kh(t,r){return new vc({type:"nonoptional",innerType:t,...Ne(r)})}const Rh=ie("ZodCatch",(t,r)=>{D0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Mh(t,r){return new Rh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Dh=ie("ZodPipe",(t,r)=>{P0.init(t,r),wt.init(t,r),t.in=r.in,t.out=r.out});function js(t,r){return new Dh({type:"pipe",in:t,out:r})}const Ph=ie("ZodReadonly",(t,r)=>{B0.init(t,r),wt.init(t,r)});function Bh(t){return new Ph({type:"readonly",innerType:t})}const Lh=ie("ZodLazy",(t,r)=>{L0.init(t,r),wt.init(t,r),t.unwrap=()=>t._zod.def.getter()});function $o(t){return new Lh({type:"lazy",getter:t})}const Fh=ie("ZodCustom",(t,r)=>{F0.init(t,r),wt.init(t,r)});function Uh(t){const r=new an({check:"custom"});return r._zod.check=t,r}function zh(t,r={}){return Rf(Fh,t,r)}function Vh(t){const r=Uh(o=>(o.addIssue=c=>{if(typeof c=="string")o.issues.push(Kr(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(Kr(u))}},t(o.value,o)));return r}function Zh(t){return pf(Zo,t)}var ze;(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"})(ze||(ze={}));function Hs(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Bi(t){return Object.fromEntries([...t.headers])}var $h=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let g=0;g<r;g++)m[g]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Nl({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},wi=$h();function Co(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var jh=["fetch failed","failed to fetch"];function Hh({error:t,url:r,requestBodyValues:o}){if(Co(t))return t;if(t instanceof TypeError&&jh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Zn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function Wh(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 Gh(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 Cc(t,...r){const o=new Headers(Gh(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var Xh="3.0.18";function qh({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new mi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new mi({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 mi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new mi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var Yh=/"__proto__"\s*:/,Kh=/"constructor"\s*:/;function Ws(t){const r=JSON.parse(t);return r===null||typeof r!="object"||Yh.test(t)===!1&&Kh.test(t)===!1?r:Jh(r)}function Jh(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 jo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Ws(t)}try{return Ws(t)}finally{Error.stackTraceLimit=r}}var bo=Symbol.for("vercel.ai.validator");function Qh(t){return{[bo]:!0,validate:t}}function ep(t){return typeof t=="object"&&t!==null&&bo in t&&t[bo]===!0&&"validate"in t}function tp(t){return ep(t)?t:typeof t=="function"?t():np(t)}function np(t){return Qh(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 rp({value:t,schema:r}){const o=await Jr({value:t,schema:r});if(!o.success)throw qr.wrap({value:t,cause:o.error});return o.value}async function Jr({value:t,schema:r}){const o=tp(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 ip({text:t,schema:r}){try{const o=jo(t);return r==null?o:rp({value:o,schema:r})}catch(o){throw Ii.isInstance(o)||qr.isInstance(o)?o:new Ii({text:t,cause:o})}}async function bc({text:t,schema:r}){try{const o=jo(t);return r==null?{success:!0,value:o,rawValue:o}:await Jr({value:o,schema:r})}catch(o){return{success:!1,error:Ii.isInstance(o)?o:new Ii({text:t,cause:o}),rawValue:void 0}}}function Gs(t){try{return jo(t),!0}catch{return!1}}function op({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ql).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await bc({text:o,schema:r}))}}))}async function Xs({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Jr({value:r[t],schema:o});if(!c.success)throw new Nl({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var sp=()=>globalThis.fetch,qs=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>ap({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),ap=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=sp()})=>{try{const g=await m(t,{method:"POST",headers:Cc(r,`ai-sdk/provider-utils/${Xh}`,Wh()),body:o.content,signal:f}),v=Bi(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(E){throw Co(E)||Zn.isInstance(E)?E:new Zn({message:"Failed to process error response",cause:E,statusCode:g.status,url:t,responseHeaders:v,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(Co(x)||Zn.isInstance(x))?x:new Zn({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:v,requestBodyValues:o.values})}}catch(g){throw Hh({error:g,url:t,requestBodyValues:o.values})}},lp=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),g=Bi(c);if(m.trim()==="")return{responseHeaders:g,value:new Zn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const v=await ip({text:m,schema:t});return{responseHeaders:g,value:new Zn({message:r(v),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:v,isRetryable:o?.(c,v)})}}catch{return{responseHeaders:g,value:new Zn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},cp=t=>async({response:r})=>{const o=Bi(r);if(r.body==null)throw new Sd({});return{responseHeaders:o,value:op({stream:r.body,schema:t})}},up=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await bc({text:u,schema:t}),m=Bi(r);if(!f.success)throw new Zn({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:dp}=globalThis;function fp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return dp(r)}function hp(t){return t instanceof Uint8Array?fp(t):t}function pp(t){return t?.replace(/\/$/,"")}function Vr(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function mp(t){const r=[];for(const{role:o,content:c,...u}of t){const f=Vr({...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,...Vr(c[0])});break}r.push({role:"user",content:c.map(m=>{const g=Vr(m);switch(m.type){case"text":return{type:"text",text:m.text,...g};case"file":if(m.mediaType.startsWith("image/")){const v=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${v};base64,${hp(m.data)}`},...g}}else throw new Xl({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const g=[];for(const v of c){const x=Vr(v);switch(v.type){case"text":{m+=v.text;break}case"tool-call":{g.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.input)},...x});break}}}r.push({role:"assistant",content:m,tool_calls:g.length>0?g:void 0,...f});break}case"tool":{for(const m of c){const g=m.output;let v;switch(g.type){case"text":case"error-text":v=g.value;break;case"content":case"json":case"error-json":v=JSON.stringify(g.value);break}const x=Vr(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:v,...x})}break}default:{const m=o;throw new Error(`Unsupported role: ${m}`)}}}return r}function Ys({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 Ks(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 ao=N({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),gp=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:it([w(),j()]).nullish()})}),xp={errorSchema:gp,errorToMessage:t=>t.error.message};function yp({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 Xl({functionality:`tool choice type: ${f}`})}}}var wp=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:xp;this.chunkSchema=vp(u.errorSchema),this.failedResponseHandler=lp(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:g,stopSequences:v,responseFormat:x,seed:E,toolChoice:A,tools:M}){var T,S,B,D;const ne=[],z=Object.assign((T=await Xs({provider:"openai-compatible",providerOptions:g,schema:ao}))!=null?T:{},(S=await Xs({provider:this.providerOptionsName,providerOptions:g,schema:ao}))!=null?S:{});u!=null&&ne.push({type:"unsupported-setting",setting:"topK"}),x?.type==="json"&&x.schema!=null&&!this.supportsStructuredOutputs&&ne.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:Z,toolChoice:re,toolWarnings:$}=yp({tools:M,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:x?.type==="json"?this.supportsStructuredOutputs===!0&&x.schema!=null?{type:"json_schema",json_schema:{schema:x.schema,name:(B=x.name)!=null?B:"response",description:x.description}}:{type:"json_object"}:void 0,stop:v,seed:E,...Object.fromEntries(Object.entries((D=g?.[this.providerOptionsName])!=null?D:{}).filter(([P])=>!Object.keys(ao.shape).includes(P))),reasoning_effort:z.reasoningEffort,verbosity:z.textVerbosity,messages:mp(t),tools:Z,tool_choice:re},warnings:[...ne,...$]}}async doGenerate(t){var r,o,c,u,f,m,g,v,x,E,A,M,T,S,B,D,ne;const{args:z,warnings:Z}=await this.getArgs({...t}),re=JSON.stringify(z),{responseHeaders:$,value:P,rawValue:L}=await qs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hs(this.config.headers(),t.headers),body:z,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:up(_p),abortSignal:t.abortSignal,fetch:this.config.fetch}),G=P.choices[0],U=[],ee=G.message.content;ee!=null&&ee.length>0&&U.push({type:"text",text:ee});const Y=(r=G.message.reasoning_content)!=null?r:G.message.reasoning;if(Y!=null&&Y.length>0&&U.push({type:"reasoning",text:Y}),G.message.tool_calls!=null)for(const Te of G.message.tool_calls)U.push({type:"tool-call",toolCallId:(o=Te.id)!=null?o:wi(),toolName:Te.function.name,input:Te.function.arguments});const ue={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:L}))},ge=(f=P.usage)==null?void 0:f.completion_tokens_details;return ge?.accepted_prediction_tokens!=null&&(ue[this.providerOptionsName].acceptedPredictionTokens=ge?.accepted_prediction_tokens),ge?.rejected_prediction_tokens!=null&&(ue[this.providerOptionsName].rejectedPredictionTokens=ge?.rejected_prediction_tokens),{content:U,finishReason:Ks(G.finish_reason),usage:{inputTokens:(g=(m=P.usage)==null?void 0:m.prompt_tokens)!=null?g:void 0,outputTokens:(x=(v=P.usage)==null?void 0:v.completion_tokens)!=null?x:void 0,totalTokens:(A=(E=P.usage)==null?void 0:E.total_tokens)!=null?A:void 0,reasoningTokens:(S=(T=(M=P.usage)==null?void 0:M.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?S:void 0,cachedInputTokens:(ne=(D=(B=P.usage)==null?void 0:B.prompt_tokens_details)==null?void 0:D.cached_tokens)!=null?ne:void 0},providerMetadata:ue,request:{body:re},response:{...Ys(P),headers:$,body:L},warnings:Z}}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:g}=await qs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Hs(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:cp(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=[];let x="unknown";const E={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 M=this.providerOptionsName;let T=!1,S=!1;return{stream:g.pipeThrough(new TransformStream({start(B){B.enqueue({type:"stream-start",warnings:c})},transform(B,D){var ne,z,Z,re,$,P,L,G,U,ee,Y,ue,ge;if(t.includeRawChunks&&D.enqueue({type:"raw",rawValue:B.rawValue}),!B.success){x="error",D.enqueue({type:"error",error:B.error});return}const Te=B.value;if(f?.processChunk(B.rawValue),"error"in Te){x="error",D.enqueue({type:"error",error:Te.error.message});return}if(A&&(A=!1,D.enqueue({type:"response-metadata",...Ys(Te)})),Te.usage!=null){const{prompt_tokens:Se,completion_tokens:We,total_tokens:me,prompt_tokens_details:Oe,completion_tokens_details:Me}=Te.usage;E.promptTokens=Se??void 0,E.completionTokens=We??void 0,E.totalTokens=me??void 0,Me?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=Me?.reasoning_tokens),Me?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=Me?.accepted_prediction_tokens),Me?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=Me?.rejected_prediction_tokens),Oe?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=Oe?.cached_tokens)}const H=Te.choices[0];if(H?.finish_reason!=null&&(x=Ks(H.finish_reason)),H?.delta==null)return;const ye=H.delta,he=(ne=ye.reasoning_content)!=null?ne:ye.reasoning;if(he&&(T||(D.enqueue({type:"reasoning-start",id:"reasoning-0"}),T=!0),D.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:he})),ye.content&&(S||(D.enqueue({type:"text-start",id:"txt-0"}),S=!0),D.enqueue({type:"text-delta",id:"txt-0",delta:ye.content})),ye.tool_calls!=null)for(const Se of ye.tool_calls){const We=Se.index;if(v[We]==null){if(Se.id==null)throw new _s({data:Se,message:"Expected 'id' to be a string."});if(((z=Se.function)==null?void 0:z.name)==null)throw new _s({data:Se,message:"Expected 'function.name' to be a string."});D.enqueue({type:"tool-input-start",id:Se.id,toolName:Se.function.name}),v[We]={id:Se.id,type:"function",function:{name:Se.function.name,arguments:(Z=Se.function.arguments)!=null?Z:""},hasFinished:!1};const Oe=v[We];((re=Oe.function)==null?void 0:re.name)!=null&&(($=Oe.function)==null?void 0:$.arguments)!=null&&(Oe.function.arguments.length>0&&D.enqueue({type:"tool-input-delta",id:Oe.id,delta:Oe.function.arguments}),Gs(Oe.function.arguments)&&(D.enqueue({type:"tool-input-end",id:Oe.id}),D.enqueue({type:"tool-call",toolCallId:(P=Oe.id)!=null?P:wi(),toolName:Oe.function.name,input:Oe.function.arguments}),Oe.hasFinished=!0));continue}const me=v[We];me.hasFinished||(((L=Se.function)==null?void 0:L.arguments)!=null&&(me.function.arguments+=(U=(G=Se.function)==null?void 0:G.arguments)!=null?U:""),D.enqueue({type:"tool-input-delta",id:me.id,delta:(ee=Se.function.arguments)!=null?ee:""}),((Y=me.function)==null?void 0:Y.name)!=null&&((ue=me.function)==null?void 0:ue.arguments)!=null&&Gs(me.function.arguments)&&(D.enqueue({type:"tool-input-end",id:me.id}),D.enqueue({type:"tool-call",toolCallId:(ge=me.id)!=null?ge:wi(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}},flush(B){var D,ne,z,Z,re,$;T&&B.enqueue({type:"reasoning-end",id:"reasoning-0"}),S&&B.enqueue({type:"text-end",id:"txt-0"});for(const L of v.filter(G=>!G.hasFinished))B.enqueue({type:"tool-input-end",id:L.id}),B.enqueue({type:"tool-call",toolCallId:(D=L.id)!=null?D:wi(),toolName:L.function.name,input:L.function.arguments});const P={[M]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(P[M].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(P[M].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),B.enqueue({type:"finish",finishReason:x,usage:{inputTokens:(ne=E.promptTokens)!=null?ne:void 0,outputTokens:(z=E.completionTokens)!=null?z:void 0,totalTokens:(Z=E.totalTokens)!=null?Z:void 0,reasoningTokens:(re=E.completionTokensDetails.reasoningTokens)!=null?re:void 0,cachedInputTokens:($=E.promptTokensDetails.cachedTokens)!=null?$:void 0},providerMetadata:P})}})),request:{body:u},response:{headers:m}}}},Ac=N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),_p=N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({message:N({role:q("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:le(N({id:w().nullish(),function:N({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:Ac}),vp=t=>it([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({delta:N({role:Ee(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:le(N({index:j(),id:w().nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:Ac}),t]);N({echo:Dt().optional(),logitBias:yt(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var Cp=N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({text:w(),finish_reason:w()})),usage:Cp.nullish()});N({dimensions:j().optional(),user:w().optional()});N({data:le(N({embedding:le(j())})),usage:N({prompt_tokens:j()}).nullish(),providerMetadata:yt(w(),yt(w(),xr())).optional()});N({data:le(N({b64_json:w()}))});var Js=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}}},bp={extractMetadata:async({parsedBody:t})=>{const r=await Jr({value:t,schema:Ap});return!r.success||r.value.usage==null?void 0:Js(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await Jr({value:r,schema:Ep});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:()=>Js(t)}}},Ec=N({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),Ap=N({usage:Ec.nullish()}),Ep=N({choices:le(N({finish_reason:w().nullish()})).nullish(),usage:Ec.nullish()}),Ip="1.0.30";function Ic(t={}){var r;const o=pp((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>Cc({Authorization:`Bearer ${qh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Ip}`);class u extends wp{addJsonInstruction(v){var x;if(((x=v.responseFormat)==null?void 0:x.type)!=="json")return v;const M=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:M}}async doGenerate(v){return super.doGenerate(this.addJsonInstruction(v))}async doStream(v){return super.doStream(this.addJsonInstruction(v))}}const f=g=>new u(g,{provider:"deepseek.chat",url:({path:v})=>`${o}${v}`,headers:c,fetch:t.fetch,metadataExtractor:bp}),m=g=>f(g);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=g=>{throw new vs({modelId:g,modelType:"textEmbeddingModel"})},m.imageModel=g=>{throw new vs({modelId:g,modelType:"imageModel"})},m}Ic();var Sc="vercel.ai.error",Sp=Symbol.for(Sc),Qs,ea,Ot=class Tc extends(ea=Error,Qs=Sp,ea){constructor({name:r,message:o,cause:c}){super(o),this[Qs]=!0,this.name=r,this.cause=c}static isInstance(r){return Tc.hasMarker(r,Sc)}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}},Nc="AI_APICallError",Oc=`vercel.ai.error.${Nc}`,Tp=Symbol.for(Oc),ta,na,sn=class extends(na=Ot,ta=Tp,na){constructor({message:t,url:r,requestBodyValues:o,statusCode:c,responseHeaders:u,responseBody:f,cause:m,isRetryable:g=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Nc,message:t,cause:m}),this[ta]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=g,this.data=v}static isInstance(t){return Ot.hasMarker(t,Oc)}},kc="AI_EmptyResponseBodyError",Rc=`vercel.ai.error.${kc}`,Np=Symbol.for(Rc),ra,ia,Op=class extends(ia=Ot,ra=Np,ia){constructor({message:t="Empty response body"}={}){super({name:kc,message:t}),this[ra]=!0}static isInstance(t){return Ot.hasMarker(t,Rc)}};function Mc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Dc="AI_InvalidArgumentError",Pc=`vercel.ai.error.${Dc}`,kp=Symbol.for(Pc),oa,sa,Bc=class extends(sa=Ot,oa=kp,sa){constructor({message:t,cause:r,argument:o}){super({name:Dc,message:t,cause:r}),this[oa]=!0,this.argument=o}static isInstance(t){return Ot.hasMarker(t,Pc)}},Lc="AI_InvalidPromptError",Fc=`vercel.ai.error.${Lc}`,Rp=Symbol.for(Fc),aa,la,Mp=class extends(la=Ot,aa=Rp,la){constructor({prompt:t,message:r,cause:o}){super({name:Lc,message:`Invalid prompt: ${r}`,cause:o}),this[aa]=!0,this.prompt=t}static isInstance(t){return Ot.hasMarker(t,Fc)}},Uc="AI_InvalidResponseDataError",zc=`vercel.ai.error.${Uc}`,Dp=Symbol.for(zc),ca,ua,lo=class extends(ua=Ot,ca=Dp,ua){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Uc,message:r}),this[ca]=!0,this.data=t}static isInstance(t){return Ot.hasMarker(t,zc)}},Vc="AI_JSONParseError",Zc=`vercel.ai.error.${Vc}`,Pp=Symbol.for(Zc),da,fa,Oi=class extends(fa=Ot,da=Pp,fa){constructor({text:t,cause:r}){super({name:Vc,message:`JSON parsing failed: Text: ${t}.
40
- Error message: ${Mc(r)}`,cause:r}),this[da]=!0,this.text=t}static isInstance(t){return Ot.hasMarker(t,Zc)}},$c="AI_LoadAPIKeyError",jc=`vercel.ai.error.${$c}`,Bp=Symbol.for(jc),ha,pa,_i=class extends(pa=Ot,ha=Bp,pa){constructor({message:t}){super({name:$c,message:t}),this[ha]=!0}static isInstance(t){return Ot.hasMarker(t,jc)}},Hc="AI_TooManyEmbeddingValuesForCallError",Wc=`vercel.ai.error.${Hc}`,Lp=Symbol.for(Wc),ma,ga,Fp=class extends(ga=Ot,ma=Lp,ga){constructor(t){super({name:Hc,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[ma]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return Ot.hasMarker(t,Wc)}},Gc="AI_TypeValidationError",Xc=`vercel.ai.error.${Gc}`,Up=Symbol.for(Xc),xa,ya,Qr=class Ao extends(ya=Ot,xa=Up,ya){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:Gc,message:`${u}: Value: ${JSON.stringify(r)}.
41
- Error message: ${Mc(o)}`,cause:o}),this[xa]=!0,this.value=r,this.context=c}static isInstance(r){return Ot.hasMarker(r,Xc)}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})}},qc="AI_UnsupportedFunctionalityError",Yc=`vercel.ai.error.${qc}`,zp=Symbol.for(Yc),wa,_a,Bn=class extends(_a=Ot,wa=zp,_a){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:qc,message:r}),this[wa]=!0,this.functionality=t}static isInstance(t){return Ot.hasMarker(t,Yc)}};function En(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Vp({tools:t=[],providerToolNames:r,resolveProviderToolName:o}){var c;const u={},f={};for(const m of t)if(m.type==="provider"){const g=(c=o?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(g==null)continue;u[m.name]=g,f[g]=m.name}return{toProviderToolName:m=>{var g;return(g=u[m])!=null?g:m},toCustomToolName:m=>{var g;return(g=f[m])!=null?g:m}}}var Zp=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:$p,atob:jp}=globalThis;function Ho(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=jp(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function Hp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return $p(r)}function Nr(t){return t instanceof Uint8Array?Hp(t):t}function Wp(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 g of f)c.append(m,g);continue}c.append(u,f)}return c}async function Wo(t){var r;try{await((r=t.body)==null?void 0:r.cancel())}catch{}}var Kc="AI_DownloadError",Jc=`vercel.ai.error.${Kc}`,Gp=Symbol.for(Jc),va,Ca,dn=class extends(Ca=Ot,va=Gp,Ca){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:Kc,message:u,cause:c}),this[va]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return Ot.hasMarker(t,Jc)}};function Xp(t=globalThis){return t.window!=null}function qp(t){let r;try{r=new URL(t)}catch{throw new dn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new dn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const o=r.hostname.toLowerCase().replace(/\.+$/,"");if(!o)throw new dn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new dn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if(Kp(c))throw new dn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(Qc(o)){if(eu(o))throw new dn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function Qc(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 eu(t){const r=t.split(".").map(Number),[o,c,u]=r;return o===0||o===10||o===100&&c>=64&&c<=127||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===0&&u===0||o===192&&c===168||o===198&&(c===18||c===19)||o>=240}function Yp(t){let r=t.toLowerCase();const o=r.indexOf("%");o!==-1&&(r=r.slice(0,o));const c=r.split("::");if(c.length>2)return null;const u=m=>{if(m==="")return[];const g=[],v=m.split(":");for(let x=0;x<v.length;x++){const E=v[x];if(E.includes(".")){if(x!==v.length-1||!Qc(E))return null;const[A,M,T,S]=E.split(".").map(Number);g.push(A<<8|M,T<<8|S);continue}if(!/^[0-9a-f]{1,4}$/.test(E))return null;g.push(parseInt(E,16))}return g},f=u(c[0]);if(f===null)return null;if(c.length===2){const m=u(c[1]);if(m===null)return null;const g=8-f.length-m.length;return g<0?null:[...f,...new Array(g).fill(0),...m]}return f.length===8?f:null}function Kp(t){const r=Yp(t);if(r===null)return!0;const o=u=>r.slice(0,u).every(f=>f===0);if(o(7)&&(r[7]===0||r[7]===1)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||(r[0]&65280)===65280)return!0;if(o(6)||o(5)&&r[5]===65535||o(4)&&r[4]===65535&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===0&&r[3]===0&&r[4]===0&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===1){const u=r[6]>>8&255,f=r[6]&255,m=r[7]>>8&255,g=r[7]&255;return eu(`${u}.${f}.${m}.${g}`)}return!1}var Jp=10;async function Qp({url:t,headers:r,abortSignal:o,maxRedirects:c=Jp}){const u={signal:o};r!==void 0&&(u.headers=r);let f=t;for(let m=0;m<=c;m++){qp(f);const g=await fetch(f,{...u,redirect:"manual"});if(g.type==="opaqueredirect"){if(!Xp())throw new dn({url:t,message:`Redirect from ${f} could not be validated and was blocked`});return await fetch(f,{...u,redirect:"follow"})}const v=g.headers.get("location");if(g.status>=300&&g.status<400&&v){await Wo(g),f=new URL(v,f).toString();continue}return g}throw new dn({url:t,message:`Too many redirects (max ${c})`})}var tu=2*1024*1024*1024;async function nu({response:t,url:r,maxBytes:o=tu}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>o)throw await Wo(t),new dn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes (Content-Length: ${E}).`})}const u=t.body;if(u==null)return new Uint8Array(0);const f=u.getReader(),m=[];let g=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(g+=A.length,g>o)throw new dn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(g);let x=0;for(const E of m)v.set(E,x),x+=E.length;return v}async function ru(t,r){var o,c;try{const u=await Qp({url:t,abortSignal:r?.abortSignal});if(!u.ok)throw await Wo(u),new dn({url:t,statusCode:u.status,statusText:u.statusText});const f=await nu({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:tu}),m=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(u){throw dn.isInstance(u)?u:new dn({url:t,cause:u})}}var em=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,m=new Array(r);for(let g=0;g<r;g++)m[g]=o[Math.random()*f|0];return m.join("")};if(t==null)return u;if(o.includes(c))throw new Bc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Qt=em();function Eo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var tm=["fetch failed","failed to fetch"],nm=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function rm(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&nm.includes(r))}function im({error:t,url:r,requestBodyValues:o}){if(Eo(t))return t;if(t instanceof TypeError&&tm.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 rm(t)?new sn({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function om(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 sm(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 iu(t,...r){const o=new Headers(sm(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var am="4.0.33";function ba(t){return t!=null}function lm({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new _i({message:`${c} API key must be a string.`});if(typeof process>"u")throw new _i({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new _i({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new _i({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function cm({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 um(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 dm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,fm=/"(?: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 Aa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||dm.test(t)===!1&&fm.test(t)===!1?r:hm(r)}function hm(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 Go(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Aa(t)}try{return Aa(t)}finally{Error.stackTraceLimit=r}}function Xo(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]=dr(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(dr):dr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(dr)),t.allOf!=null&&(t.allOf=t.allOf.map(dr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(dr));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=dr(r[o]);return t}function dr(t){return typeof t=="boolean"?t:Xo(t)}var pm=Symbol("Let zodToJsonSchema decide on which parser to use"),Ea={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"},mm=t=>typeof t=="string"?{...Ea,name:t}:{...Ea,...t};function pn(){return{}}function gm(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)!==ze.ZodAny&&(f.items=lt(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 xm(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 ym(){return{type:"boolean"}}function ou(t,r){return lt(t.type._def,r)}var wm=(t,r)=>lt(t.innerType._def,r);function su(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>su(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 _m(t)}}var _m=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 vm(t,r){return{...lt(t.innerType._def,r),default:t.defaultValue()}}function Cm(t,r){return r.effectStrategy==="input"?lt(t.schema._def,r):pn()}function bm(t){return{type:"string",enum:Array.from(t.values)}}var Am=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Em(t,r){const o=[lt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),lt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(Am(u))c.push(...u.allOf);else{let f=u;if("additionalProperties"in u&&u.additionalProperties===!1){const{additionalProperties:m,...g}=u;f=g}c.push(f)}}),c.length?{allOf:c}:void 0}function Im(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 co=void 0,vn={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:()=>(co===void 0&&(co=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),co),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 au(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":Cn(o,"email",c.message,r);break;case"format:idn-email":Cn(o,"idn-email",c.message,r);break;case"pattern:zod":Jt(o,vn.email,c.message,r);break}break;case"url":Cn(o,"uri",c.message,r);break;case"uuid":Cn(o,"uuid",c.message,r);break;case"regex":Jt(o,c.regex,c.message,r);break;case"cuid":Jt(o,vn.cuid,c.message,r);break;case"cuid2":Jt(o,vn.cuid2,c.message,r);break;case"startsWith":Jt(o,RegExp(`^${uo(c.value,r)}`),c.message,r);break;case"endsWith":Jt(o,RegExp(`${uo(c.value,r)}$`),c.message,r);break;case"datetime":Cn(o,"date-time",c.message,r);break;case"date":Cn(o,"date",c.message,r);break;case"time":Cn(o,"time",c.message,r);break;case"duration":Cn(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":{Jt(o,RegExp(uo(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&Cn(o,"ipv4",c.message,r),c.version!=="v4"&&Cn(o,"ipv6",c.message,r);break}case"base64url":Jt(o,vn.base64url,c.message,r);break;case"jwt":Jt(o,vn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Jt(o,vn.ipv4Cidr,c.message,r),c.version!=="v4"&&Jt(o,vn.ipv6Cidr,c.message,r);break}case"emoji":Jt(o,vn.emoji(),c.message,r);break;case"ulid":{Jt(o,vn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{Cn(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Jt(o,vn.base64,c.message,r);break}}break}case"nanoid":Jt(o,vn.nanoid,c.message,r)}return o}function uo(t,r){return r.patternStrategy==="escape"?Tm(t):t}var Sm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Tm(t){let r="";for(let o=0;o<t.length;o++)Sm.has(t[o])||(r+="\\"),r+=t[o];return r}function Cn(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 Jt(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:Ia(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=Ia(r,c)}function Ia(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,g=!1,v=!1;for(let x=0;x<u.length;x++){if(m){f+=u[x],m=!1;continue}if(c.i){if(g){if(u[x].match(/[a-z]/)){v?(f+=u[x],f+=`${u[x-2]}-${u[x]}`.toUpperCase(),v=!1):u[x+1]==="-"&&((o=u[x+2])!=null&&o.match(/[a-z]/))?(f+=u[x],v=!0):f+=`${u[x]}${u[x].toUpperCase()}`;continue}}else if(u[x].match(/[a-z]/)){f+=`[${u[x]}${u[x].toUpperCase()}]`;continue}}if(c.m){if(u[x]==="^"){f+=`(^|(?<=[\r
42
- ]))`;continue}else if(u[x]==="$"){f+=`($|(?=[\r
43
- ]))`;continue}}if(c.s&&u[x]==="."){f+=g?`${u[x]}\r
44
- `:`[${u[x]}\r
45
- ]`;continue}f+=u[x],u[x]==="\\"?m=!0:g&&u[x]==="]"?g=!1:!g&&u[x]==="["&&(g=!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 lu(t,r){var o,c,u,f,m,g;const v={type:"object",additionalProperties:(o=lt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===ze.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:x,...E}=au(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===ze.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===ze.ZodBranded&&t.keyType._def.type._def.typeName===ze.ZodString&&((g=t.keyType._def.type._def.checks)!=null&&g.length)){const{type:x,...E}=ou(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function Nm(t,r){if(r.mapStrategy==="record")return lu(t,r);const o=lt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||pn(),c=lt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||pn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function Om(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 km(){return{not:pn()}}function Rm(){return{type:"null"}}var Io={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Mm(t,r){const o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(c=>c._def.typeName in Io&&(!c._def.checks||!c._def.checks.length))){const c=o.reduce((u,f)=>{const m=Io[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,g)=>g.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 Dm(t,r)}var Dm=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>lt(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 Pm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Io[t.innerType._def.typeName],"null"]};const o=lt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function Bm(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 Lm(t,r){const o={type:"object",properties:{}},c=[],u=t.shape();for(const m in u){let g=u[m];if(g===void 0||g._def===void 0)continue;const v=Um(g),x=lt(g._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});x!==void 0&&(o.properties[m]=x,v||c.push(m))}c.length&&(o.required=c);const f=Fm(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Fm(t,r){if(t.catchall._def.typeName!=="ZodNever")return lt(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 Um(t){try{return t.isOptional()}catch{return!0}}var zm=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return lt(t.innerType._def,r);const c=lt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:pn()},c]}:pn()},Vm=(t,r)=>{if(r.pipeStrategy==="input")return lt(t.in._def,r);if(r.pipeStrategy==="output")return lt(t.out._def,r);const o=lt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=lt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function Zm(t,r){return lt(t.type._def,r)}function $m(t,r){const c={type:"array",uniqueItems:!0,items:lt(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 jm(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>lt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:lt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>lt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Hm(){return{not:pn()}}function Wm(){return pn()}var Gm=(t,r)=>lt(t.innerType._def,r),Xm=(t,r,o)=>{switch(r){case ze.ZodString:return au(t,o);case ze.ZodNumber:return Bm(t);case ze.ZodObject:return Lm(t,o);case ze.ZodBigInt:return xm(t);case ze.ZodBoolean:return ym();case ze.ZodDate:return su(t,o);case ze.ZodUndefined:return Hm();case ze.ZodNull:return Rm();case ze.ZodArray:return gm(t,o);case ze.ZodUnion:case ze.ZodDiscriminatedUnion:return Mm(t,o);case ze.ZodIntersection:return Em(t,o);case ze.ZodTuple:return jm(t,o);case ze.ZodRecord:return lu(t,o);case ze.ZodLiteral:return Im(t);case ze.ZodEnum:return bm(t);case ze.ZodNativeEnum:return Om(t);case ze.ZodNullable:return Pm(t,o);case ze.ZodOptional:return zm(t,o);case ze.ZodMap:return Nm(t,o);case ze.ZodSet:return $m(t,o);case ze.ZodLazy:return()=>t.getter()._def;case ze.ZodPromise:return Zm(t,o);case ze.ZodNaN:case ze.ZodNever:return km();case ze.ZodEffects:return Cm(t,o);case ze.ZodAny:return pn();case ze.ZodUnknown:return Wm();case ze.ZodDefault:return vm(t,o);case ze.ZodBranded:return ou(t,o);case ze.ZodReadonly:return Gm(t,o);case ze.ZodCatch:return wm(t,o);case ze.ZodPipeline:return Vm(t,o);case ze.ZodFunction:case ze.ZodVoid:case ze.ZodSymbol:return;default:return(c=>{})()}},qm=(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 lt(t,r,o=!1){var c;const u=r.seen.get(t);if(r.override){const v=(c=r.override)==null?void 0:c.call(r,t,r,u,o);if(v!==pm)return v}if(u&&!o){const v=Ym(u,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=Xm(t,t.typeName,r),g=typeof m=="function"?lt(m(),r):m;if(g&&Km(t,r,g),r.postProcess){const v=r.postProcess(g,t,r);return f.jsonSchema=g,v}return f.jsonSchema=g,g}var Ym=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:qm(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`),pn()):r.$refStrategy==="seen"?pn():void 0}},Km=(t,r,o)=>(t.description&&(o.description=t.description),o),Jm=t=>{const r=mm(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}]))}},Qm=(t,r)=>{var o;const c=Jm(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((x,[E,A])=>{var M;return{...x,[E]:(M=lt(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?M:pn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(o=lt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:pn(),g=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;g!==void 0&&(m.title=g);const v=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 v.$schema="http://json-schema.org/draft-07/schema#",v},So=Symbol.for("vercel.ai.schema");function Ue(t){let r;return()=>(r==null&&(r=t()),r)}function Li(t,{validate:r}={}){return{[So]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function eg(t){return typeof t=="object"&&t!==null&&So in t&&t[So]===!0&&"jsonSchema"in t&&"validate"in t}function tg(t){return t==null?Li({properties:{},additionalProperties:!1}):eg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Fe(t):ng(t):t()}function ng(t){return Li(()=>Xo(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 Qr({value:r,cause:o.issues})}}})}function rg(t,r){var o;const c=(o=void 0)!=null?o:!1;return Li(()=>Qm(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 ig(t,r){var o;const c=(o=void 0)!=null?o:!1;return Li(()=>Xo(Mf(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await gc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function og(t){return"_zod"in t}function Fe(t,r){return og(t)?ig(t):rg(t)}async function Pt({value:t,schema:r,context:o}){const c=await qo({value:t,schema:r,context:o});if(!c.success)throw Qr.wrap({value:t,cause:c.error,context:o});return c.value}async function qo({value:t,schema:r,context:o}){const c=tg(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:Qr.wrap({value:t,cause:u.error,context:o}),rawValue:t}}catch(u){return{success:!1,error:Qr.wrap({value:t,cause:u,context:o}),rawValue:t}}}async function cu({text:t,schema:r}){try{const o=Go(t);return r==null?o:Pt({value:o,schema:r})}catch(o){throw Oi.isInstance(o)||Qr.isInstance(o)?o:new Oi({text:t,cause:o})}}async function uu({text:t,schema:r}){try{const o=Go(t);return r==null?{success:!0,value:o,rawValue:o}:await qo({value:o,schema:r})}catch(o){return{success:!1,error:Oi.isInstance(o)?o:new Oi({text:t,cause:o}),rawValue:void 0}}}function Sa(t){try{return Go(t),!0}catch{return!1}}function sg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ql).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await uu({text:o,schema:r}))}}))}async function In({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await qo({value:r[t],schema:o});if(!c.success)throw new Bc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var ag=()=>globalThis.fetch,jn=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>fu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),du=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>fu({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),fu=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=ag()})=>{try{const g=await m(t,{method:"POST",headers:iu(r,`ai-sdk/provider-utils/${am}`,om()),body:o.content,signal:f}),v=ii(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(E){throw Eo(E)||sn.isInstance(E)?E:new sn({message:"Failed to process error response",cause:E,statusCode:g.status,url:t,responseHeaders:v,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(Eo(x)||sn.isInstance(x))?x:new sn({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:v,requestBodyValues:o.values})}}catch(g){throw im({error:g,url:t,requestBodyValues:o.values})}};function lg({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:v,...x})=>({type:"provider",id:t,args:x,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:v})}function Ln({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:v,onInputAvailable:x,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:v,onInputAvailable:x,supportsDeferredResults:c})}var cg=new TextDecoder;async function hu({response:t,url:r}){return cg.decode(await nu({response:t,url:r}))}var ug=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await hu({response:c,url:u}),g=ii(c);if(m.trim()==="")return{responseHeaders:g,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const v=await cu({text:m,schema:t});return{responseHeaders:g,value:new sn({message:r(v),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:v,isRetryable:o?.(c,v)})}}catch{return{responseHeaders:g,value:new sn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},Yo=t=>async({response:r})=>{const o=ii(r);if(r.body==null)throw new Op({});return{responseHeaders:o,value:sg({stream:r.body,schema:t})}},mr=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await hu({response:r,url:o}),f=await uu({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}},dg=()=>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 fg(t){return t?.replace(/\/$/,"")}var Ko=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:it([w(),j()]).nullish()})}),Sn=ug({errorSchema:Ko,errorToMessage:t=>t.error.message});function pu(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")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||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")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4")||t.startsWith("gpt-5.5");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function Ta(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 g=(r=t.prompt_tokens)!=null?r:0,v=(o=t.completion_tokens)!=null?o:0,x=(u=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?u:0,E=(m=(f=t.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:g,noCache:g-x,cacheRead:x,cacheWrite:void 0},outputTokens:{total:v,text:v-E,reasoning:E},raw:t}}function hg(t){return JSON.stringify(t===void 0?{}:t)}function pg({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 g=r;throw new Error(`Unsupported system message mode: ${g}`)}}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((g,v)=>{var x,E,A;switch(g.type){case"text":return{type:"text",text:g.text};case"file":if(g.mediaType.startsWith("image/")){const M=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${M};base64,${Nr(g.data)}`,detail:(E=(x=g.providerOptions)==null?void 0:x.openai)==null?void 0:E.imageDetail}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new Bn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Nr(g.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Nr(g.data),format:"mp3"}};default:throw new Bn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new Bn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(A=g.filename)!=null?A:`part-${v}.pdf`,file_data:`data:application/pdf;base64,${Nr(g.data)}`}}}else throw new Bn({functionality:`file part media type ${g.mediaType}`})}})});break}case"assistant":{let g="";const v=[];for(const x of m)switch(x.type){case"text":{g+=x.text;break}case"tool-call":{v.push({id:x.toolCallId,type:"function",function:{name:x.toolName,arguments:hg(x.input)}});break}}c.push({role:"assistant",content:v.length>0?g||null:g,tool_calls:v.length>0?v:void 0});break}case"tool":{for(const g of m){if(g.type==="tool-approval-response")continue;const v=g.output;let x;switch(v.type){case"text":case"error-text":x=v.value;break;case"execution-denied":x=(o=v.reason)!=null?o:"Tool execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(v.value);break}c.push({role:"tool",tool_call_id:g.toolCallId,content:x})}break}default:{const g=f;throw new Error(`Unsupported role: ${g}`)}}return{messages:c,warnings:u}}function fo({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Na(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 mg=Ue(()=>Fe(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({message:N({role:q("assistant").nullish(),content:w().nullish(),tool_calls:le(N({id:w().nullish(),type:q("function"),function:N({name:w(),arguments:w()})})).nullish(),annotations:le(N({type:q("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:N({content:le(N({token:w(),logprob:j(),top_logprobs:le(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),gg=Ue(()=>Fe(it([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({delta:N({role:Ee(["assistant"]).nullish(),content:w().nullish(),tool_calls:le(N({index:j(),id:w().nullish(),type:q("function").nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:le(N({type:q("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:N({content:le(N({token:w(),logprob:j(),top_logprobs:le(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Ko]))),xg=Ue(()=>Fe(N({logitBias:yt(Zh(),j()).optional(),logprobs:it([Dt(),j()]).optional(),parallelToolCalls:Dt().optional(),user:w().optional(),reasoningEffort:Ee(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:Dt().optional(),metadata:yt(w().max(64),w().max(512)).optional(),prediction:yt(w(),xr()).optional(),serviceTier:Ee(["auto","flex","priority","default"]).optional(),strictJsonSchema:Dt().optional(),textVerbosity:Ee(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheRetention:Ee(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Ee(["system","developer","remove"]).optional(),forceReasoning:Dt().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 Bn({functionality:`tool choice type: ${f}`})}}}var wg=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:g,responseFormat:v,seed:x,tools:E,toolChoice:A,providerOptions:M}){var T,S,B,D,ne;const z=[],Z=(T=await In({provider:"openai",providerOptions:M,schema:xg}))!=null?T:{},re=pu(this.modelId),$=(S=Z.forceReasoning)!=null?S:re.isReasoningModel;u!=null&&z.push({type:"unsupported",feature:"topK"});const{messages:P,warnings:L}=pg({prompt:t,systemMessageMode:(B=Z.systemMessageMode)!=null?B:$?"developer":re.systemMessageMode});z.push(...L);const G=(D=Z.strictJsonSchema)!=null?D:!0,U={model:this.modelId,logit_bias:Z.logitBias,logprobs:Z.logprobs===!0||typeof Z.logprobs=="number"?!0:void 0,top_logprobs:typeof Z.logprobs=="number"?Z.logprobs:typeof Z.logprobs=="boolean"&&Z.logprobs?0:void 0,user:Z.user,parallel_tool_calls:Z.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:G,name:(ne=v.name)!=null?ne:"response",description:v.description}}:{type:"json_object"}:void 0,stop:g,seed:x,verbosity:Z.textVerbosity,max_completion_tokens:Z.maxCompletionTokens,store:Z.store,metadata:Z.metadata,prediction:Z.prediction,reasoning_effort:Z.reasoningEffort,service_tier:Z.serviceTier,prompt_cache_key:Z.promptCacheKey,prompt_cache_retention:Z.promptCacheRetention,safety_identifier:Z.safetyIdentifier,messages:P};$?((Z.reasoningEffort!=="none"||!re.supportsNonReasoningParameters)&&(U.temperature!=null&&(U.temperature=void 0,z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),U.top_p!=null&&(U.top_p=void 0,z.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),U.logprobs!=null&&(U.logprobs=void 0,z.push({type:"other",message:"logprobs is not supported for reasoning models"}))),U.frequency_penalty!=null&&(U.frequency_penalty=void 0,z.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),U.presence_penalty!=null&&(U.presence_penalty=void 0,z.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),U.logit_bias!=null&&(U.logit_bias=void 0,z.push({type:"other",message:"logitBias is not supported for reasoning models"})),U.top_logprobs!=null&&(U.top_logprobs=void 0,z.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),U.max_tokens!=null&&(U.max_completion_tokens==null&&(U.max_completion_tokens=U.max_tokens),U.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&U.temperature!=null&&(U.temperature=void 0,z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),Z.serviceTier==="flex"&&!re.supportsFlexProcessing&&(z.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),U.service_tier=void 0),Z.serviceTier==="priority"&&!re.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"}),U.service_tier=void 0);const{tools:ee,toolChoice:Y,toolWarnings:ue}=yg({tools:E,toolChoice:A});return{args:{...U,tools:ee,tool_choice:Y},warnings:[...z,...ue]}}async doGenerate(t){var r,o,c,u,f,m,g;const{args:v,warnings:x}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:M}=await jn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:v,failedResponseHandler:Sn,successfulResponseHandler:mr(mg),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],B=T.message.content;B!=null&&B.length>0&&S.push({type:"text",text:B});for(const z of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(o=z.id)!=null?o:Qt(),toolName:z.function.name,input:z.function.arguments});for(const z of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:Qt(),url:z.url_citation.url,title:z.url_citation.title});const D=(u=A.usage)==null?void 0:u.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const ne={openai:{}};return D?.accepted_prediction_tokens!=null&&(ne.openai.acceptedPredictionTokens=D?.accepted_prediction_tokens),D?.rejected_prediction_tokens!=null&&(ne.openai.rejectedPredictionTokens=D?.rejected_prediction_tokens),((m=T.logprobs)==null?void 0:m.content)!=null&&(ne.openai.logprobs=T.logprobs.content),{content:S,finishReason:{unified:Na(T.finish_reason),raw:(g=T.finish_reason)!=null?g:void 0},usage:Ta(A.usage),request:{body:v},response:{...fo(A),headers:E,body:M},warnings:x,providerMetadata:ne}}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 jn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:Sn,successfulResponseHandler:Yo(gg),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=[];let g={unified:"other",raw:void 0},v,x=!1,E=!1;const A={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(M){M.enqueue({type:"stream-start",warnings:o})},transform(M,T){var S,B,D,ne,z,Z,re,$,P,L,G,U,ee,Y,ue,ge,Te;if(t.includeRawChunks&&T.enqueue({type:"raw",rawValue:M.rawValue}),!M.success){g={unified:"error",raw:void 0},T.enqueue({type:"error",error:M.error});return}const H=M.value;if("error"in H){g={unified:"error",raw:void 0},T.enqueue({type:"error",error:H.error});return}if(!x){const Se=fo(H);Object.values(Se).some(Boolean)&&(x=!0,T.enqueue({type:"response-metadata",...fo(H)}))}H.usage!=null&&(v=H.usage,((S=H.usage.completion_tokens_details)==null?void 0:S.accepted_prediction_tokens)!=null&&(A.openai.acceptedPredictionTokens=(B=H.usage.completion_tokens_details)==null?void 0:B.accepted_prediction_tokens),((D=H.usage.completion_tokens_details)==null?void 0:D.rejected_prediction_tokens)!=null&&(A.openai.rejectedPredictionTokens=(ne=H.usage.completion_tokens_details)==null?void 0:ne.rejected_prediction_tokens));const ye=H.choices[0];if(ye?.finish_reason!=null&&(g={unified:Na(ye.finish_reason),raw:ye.finish_reason}),((z=ye?.logprobs)==null?void 0:z.content)!=null&&(A.openai.logprobs=ye.logprobs.content),ye?.delta==null)return;const he=ye.delta;if(he.content!=null&&(E||(T.enqueue({type:"text-start",id:"0"}),E=!0),T.enqueue({type:"text-delta",id:"0",delta:he.content})),he.tool_calls!=null)for(const Se of he.tool_calls){const We=Se.index;if(m[We]==null){if(Se.type!=null&&Se.type!=="function")throw new lo({data:Se,message:"Expected 'function' type."});if(Se.id==null)throw new lo({data:Se,message:"Expected 'id' to be a string."});if(((Z=Se.function)==null?void 0:Z.name)==null)throw new lo({data:Se,message:"Expected 'function.name' to be a string."});T.enqueue({type:"tool-input-start",id:Se.id,toolName:Se.function.name}),m[We]={id:Se.id,type:"function",function:{name:Se.function.name,arguments:(re=Se.function.arguments)!=null?re:""},hasFinished:!1};const Oe=m[We];(($=Oe.function)==null?void 0:$.name)!=null&&((P=Oe.function)==null?void 0:P.arguments)!=null&&(Oe.function.arguments.length>0&&T.enqueue({type:"tool-input-delta",id:Oe.id,delta:Oe.function.arguments}),Sa(Oe.function.arguments)&&(T.enqueue({type:"tool-input-end",id:Oe.id}),T.enqueue({type:"tool-call",toolCallId:(L=Oe.id)!=null?L:Qt(),toolName:Oe.function.name,input:Oe.function.arguments}),Oe.hasFinished=!0));continue}const me=m[We];me.hasFinished||(((G=Se.function)==null?void 0:G.arguments)!=null&&(me.function.arguments+=(ee=(U=Se.function)==null?void 0:U.arguments)!=null?ee:""),T.enqueue({type:"tool-input-delta",id:me.id,delta:(Y=Se.function.arguments)!=null?Y:""}),((ue=me.function)==null?void 0:ue.name)!=null&&((ge=me.function)==null?void 0:ge.arguments)!=null&&Sa(me.function.arguments)&&(T.enqueue({type:"tool-input-end",id:me.id}),T.enqueue({type:"tool-call",toolCallId:(Te=me.id)!=null?Te:Qt(),toolName:me.function.name,input:me.function.arguments}),me.hasFinished=!0))}if(he.annotations!=null)for(const Se of he.annotations)T.enqueue({type:"source",sourceType:"url",id:Qt(),url:Se.url_citation.url,title:Se.url_citation.title})},flush(M){E&&M.enqueue({type:"text-end",id:"0"}),M.enqueue({type:"finish",finishReason:g,usage:Ta(v),...A!=null?{providerMetadata:A}:{}})}})),request:{body:c},response:{headers:u}}}};function Oa(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 _g({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
39
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const E of this.seen.entries()){const A=E[1];if(r===E[0]){m(E);continue}if(c.external){const T=c.external.registry.get(E[0])?.id;if(r!==E[0]&&T){m(E);continue}}if(this.metadataRegistry.get(E[0])?.id){m(E);continue}if(A.cycle){m(E);continue}if(A.count>1&&c.reused==="ref"){m(E);continue}}const x=(E,A)=>{const D=this.seen.get(E),T=D.def??D.schema,S={...T};if(D.ref===null)return;const P=D.ref;if(D.ref=null,P){x(P,A);const M=this.seen.get(P).schema;M.$ref&&A.target==="draft-7"?(T.allOf=T.allOf??[],T.allOf.push(M)):(Object.assign(T,M),Object.assign(T,S))}D.isParent||this.override({zodSchema:E,jsonSchema:T,path:D.path??[]})};for(const E of[...this.seen.entries()].reverse())x(E[0],{target:this.target});const v={};if(this.target==="draft-2020-12"?v.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?v.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const E=c.external.registry.get(r)?.id;if(!E)throw new Error("Schema is missing an `id` property");v.$id=c.external.uri(E)}Object.assign(v,d.def);const g=c.external?.defs??{};for(const E of this.seen.entries()){const A=E[1];A.def&&A.defId&&(g[A.defId]=A.def)}c.external||Object.keys(g).length>0&&(this.target==="draft-2020-12"?v.$defs=g:v.definitions=g);try{return JSON.parse(JSON.stringify(v))}catch{throw new Error("Error converting schema to JSON.")}}}function Uf(t,r){if(t instanceof yc){const c=new Zs(r),d={};for(const x of t._idmap.entries()){const[v,g]=x;c.process(g)}const f={},m={registry:t,uri:r?.uri,defs:d};for(const x of t._idmap.entries()){const[v,g]=x;f[v]=c.emit(g,{...r,external:m})}if(Object.keys(d).length>0){const x=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[x]:d}}return{schemas:f}}const i=new Zs(r);return i.process(t),i.emit(t,r)}function Lt(t,r){const i=r??{seen:new Set};if(i.seen.has(t))return!1;i.seen.add(t);const d=t._zod.def;switch(d.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 Lt(d.element,i);case"object":{for(const f in d.shape)if(Lt(d.shape[f],i))return!0;return!1}case"union":{for(const f of d.options)if(Lt(f,i))return!0;return!1}case"intersection":return Lt(d.left,i)||Lt(d.right,i);case"tuple":{for(const f of d.items)if(Lt(f,i))return!0;return!!(d.rest&&Lt(d.rest,i))}case"record":return Lt(d.keyType,i)||Lt(d.valueType,i);case"map":return Lt(d.keyType,i)||Lt(d.valueType,i);case"set":return Lt(d.valueType,i);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Lt(d.innerType,i);case"lazy":return Lt(d.getter(),i);case"default":return Lt(d.innerType,i);case"prefault":return Lt(d.innerType,i);case"custom":return!1;case"transform":return!0;case"pipe":return Lt(d.in,i)||Lt(d.out,i);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${d.type}`)}const zf=oe("ZodISODateTime",(t,r)=>{a0.init(t,r),It.init(t,r)});function Vf(t){return mf(zf,t)}const Zf=oe("ZodISODate",(t,r)=>{l0.init(t,r),It.init(t,r)});function $f(t){return gf(Zf,t)}const jf=oe("ZodISOTime",(t,r)=>{c0.init(t,r),It.init(t,r)});function Hf(t){return xf(jf,t)}const Wf=oe("ZodISODuration",(t,r)=>{u0.init(t,r),It.init(t,r)});function Gf(t){return yf(Wf,t)}const qf=(t,r)=>{ic.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:i=>r1(t,i)},flatten:{value:i=>n1(t,i)},addIssue:{value:i=>t.issues.push(i)},addIssues:{value:i=>t.issues.push(...i)},isEmpty:{get(){return t.issues.length===0}}})},Uo=oe("ZodError",qf,{Parent:Error}),Xf=o1(Uo),Yf=i1(Uo),Kf=ac(Uo),vc=lc(Uo),_t=oe("ZodType",(t,r)=>(ht.init(t,r),t.def=r,Object.defineProperty(t,"_def",{value:r}),t.check=(...i)=>t.clone({...r,checks:[...r.checks??[],...i.map(c=>typeof c=="function"?{_zod:{check:c,def:{check:"custom"},onattach:[]}}:c)]}),t.clone=(i,c)=>gr(t,i,c),t.brand=()=>t,t.register=((i,c)=>(i.add(t,c),t)),t.parse=(i,c)=>Xf(t,i,c,{callee:t.parse}),t.safeParse=(i,c)=>Kf(t,i,c),t.parseAsync=async(i,c)=>Yf(t,i,c,{callee:t.parseAsync}),t.safeParseAsync=async(i,c)=>vc(t,i,c),t.spa=t.safeParseAsync,t.refine=(i,c)=>t.check(Wh(i,c)),t.superRefine=i=>t.check(Gh(i)),t.overwrite=i=>t.check(so(i)),t.optional=()=>Hs(t),t.nullable=()=>Ws(t),t.nullish=()=>Hs(Ws(t)),t.nonoptional=i=>Lh(t,i),t.array=()=>ue(t),t.or=i=>st([t,i]),t.and=i=>Sh(t,i),t.transform=i=>Gs(t,kh(i)),t.default=i=>Dh(t,i),t.prefault=i=>Bh(t,i),t.catch=i=>Uh(t,i),t.pipe=i=>Gs(t,i),t.readonly=()=>Zh(t),t.describe=i=>{const c=t.clone();return Gr.add(c,{description:i}),c},Object.defineProperty(t,"description",{get(){return Gr.get(t)?.description},configurable:!0}),t.meta=(...i)=>{if(i.length===0)return Gr.get(t);const c=t.clone();return Gr.add(c,i[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cc=oe("_ZodString",(t,r)=>{ji.init(t,r),_t.init(t,r);const i=t._zod.bag;t.format=i.format??null,t.minLength=i.minimum??null,t.maxLength=i.maximum??null,t.regex=(...c)=>t.check(Sf(...c)),t.includes=(...c)=>t.check(Of(...c)),t.startsWith=(...c)=>t.check(kf(...c)),t.endsWith=(...c)=>t.check(Rf(...c)),t.min=(...c)=>t.check(Mo(...c)),t.max=(...c)=>t.check(wc(...c)),t.length=(...c)=>t.check(_c(...c)),t.nonempty=(...c)=>t.check(Mo(1,...c)),t.lowercase=c=>t.check(Tf(c)),t.uppercase=c=>t.check(Nf(c)),t.trim=()=>t.check(Df()),t.normalize=(...c)=>t.check(Mf(...c)),t.toLowerCase=()=>t.check(Pf()),t.toUpperCase=()=>t.check(Bf())}),Jf=oe("ZodString",(t,r)=>{ji.init(t,r),Cc.init(t,r),t.email=i=>t.check(G0(Qf,i)),t.url=i=>t.check(J0(eh,i)),t.jwt=i=>t.check(pf(mh,i)),t.emoji=i=>t.check(Q0(th,i)),t.guid=i=>t.check(Fs($s,i)),t.uuid=i=>t.check(q0(Co,i)),t.uuidv4=i=>t.check(X0(Co,i)),t.uuidv6=i=>t.check(Y0(Co,i)),t.uuidv7=i=>t.check(K0(Co,i)),t.nanoid=i=>t.check(ef(nh,i)),t.guid=i=>t.check(Fs($s,i)),t.cuid=i=>t.check(tf(rh,i)),t.cuid2=i=>t.check(nf(oh,i)),t.ulid=i=>t.check(rf(ih,i)),t.base64=i=>t.check(df(fh,i)),t.base64url=i=>t.check(ff(hh,i)),t.xid=i=>t.check(of(sh,i)),t.ksuid=i=>t.check(sf(ah,i)),t.ipv4=i=>t.check(af(lh,i)),t.ipv6=i=>t.check(lf(ch,i)),t.cidrv4=i=>t.check(cf(uh,i)),t.cidrv6=i=>t.check(uf(dh,i)),t.e164=i=>t.check(hf(ph,i)),t.datetime=i=>t.check(Vf(i)),t.date=i=>t.check($f(i)),t.time=i=>t.check(Hf(i)),t.duration=i=>t.check(Gf(i))});function w(t){return W0(Jf,t)}const It=oe("ZodStringFormat",(t,r)=>{bt.init(t,r),Cc.init(t,r)}),Qf=oe("ZodEmail",(t,r)=>{J1.init(t,r),It.init(t,r)}),$s=oe("ZodGUID",(t,r)=>{Y1.init(t,r),It.init(t,r)}),Co=oe("ZodUUID",(t,r)=>{K1.init(t,r),It.init(t,r)}),eh=oe("ZodURL",(t,r)=>{Q1.init(t,r),It.init(t,r)}),th=oe("ZodEmoji",(t,r)=>{e0.init(t,r),It.init(t,r)}),nh=oe("ZodNanoID",(t,r)=>{t0.init(t,r),It.init(t,r)}),rh=oe("ZodCUID",(t,r)=>{n0.init(t,r),It.init(t,r)}),oh=oe("ZodCUID2",(t,r)=>{r0.init(t,r),It.init(t,r)}),ih=oe("ZodULID",(t,r)=>{o0.init(t,r),It.init(t,r)}),sh=oe("ZodXID",(t,r)=>{i0.init(t,r),It.init(t,r)}),ah=oe("ZodKSUID",(t,r)=>{s0.init(t,r),It.init(t,r)}),lh=oe("ZodIPv4",(t,r)=>{d0.init(t,r),It.init(t,r)}),ch=oe("ZodIPv6",(t,r)=>{f0.init(t,r),It.init(t,r)}),uh=oe("ZodCIDRv4",(t,r)=>{h0.init(t,r),It.init(t,r)}),dh=oe("ZodCIDRv6",(t,r)=>{p0.init(t,r),It.init(t,r)}),fh=oe("ZodBase64",(t,r)=>{m0.init(t,r),It.init(t,r)}),hh=oe("ZodBase64URL",(t,r)=>{x0.init(t,r),It.init(t,r)}),ph=oe("ZodE164",(t,r)=>{y0.init(t,r),It.init(t,r)}),mh=oe("ZodJWT",(t,r)=>{_0.init(t,r),It.init(t,r)}),Hi=oe("ZodNumber",(t,r)=>{gc.init(t,r),_t.init(t,r),t.gt=(c,d)=>t.check(zs(c,d)),t.gte=(c,d)=>t.check(ui(c,d)),t.min=(c,d)=>t.check(ui(c,d)),t.lt=(c,d)=>t.check(Us(c,d)),t.lte=(c,d)=>t.check(ci(c,d)),t.max=(c,d)=>t.check(ci(c,d)),t.int=c=>t.check(js(c)),t.safe=c=>t.check(js(c)),t.positive=c=>t.check(zs(0,c)),t.nonnegative=c=>t.check(ui(0,c)),t.negative=c=>t.check(Us(0,c)),t.nonpositive=c=>t.check(ci(0,c)),t.multipleOf=(c,d)=>t.check(Vs(c,d)),t.step=(c,d)=>t.check(Vs(c,d)),t.finite=()=>t;const i=t._zod.bag;t.minValue=Math.max(i.minimum??Number.NEGATIVE_INFINITY,i.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(i.maximum??Number.POSITIVE_INFINITY,i.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(i.format??"").includes("int")||Number.isSafeInteger(i.multipleOf??.5),t.isFinite=!0,t.format=i.format??null});function j(t){return wf(Hi,t)}const gh=oe("ZodNumberFormat",(t,r)=>{v0.init(t,r),Hi.init(t,r)});function js(t){return vf(gh,t)}const xh=oe("ZodBoolean",(t,r)=>{C0.init(t,r),_t.init(t,r)});function Mt(t){return Cf(xh,t)}const yh=oe("ZodNull",(t,r)=>{b0.init(t,r),_t.init(t,r)});function bc(t){return bf(yh,t)}const wh=oe("ZodAny",(t,r)=>{A0.init(t,r),_t.init(t,r)});function xr(){return Af(wh)}const _h=oe("ZodUnknown",(t,r)=>{E0.init(t,r),_t.init(t,r)});function Cn(){return Ef(_h)}const vh=oe("ZodNever",(t,r)=>{I0.init(t,r),_t.init(t,r)});function Ch(t){return If(vh,t)}const bh=oe("ZodArray",(t,r)=>{S0.init(t,r),_t.init(t,r),t.element=r.element,t.min=(i,c)=>t.check(Mo(i,c)),t.nonempty=i=>t.check(Mo(1,i)),t.max=(i,c)=>t.check(wc(i,c)),t.length=(i,c)=>t.check(_c(i,c)),t.unwrap=()=>t.element});function ue(t,r){return Lf(bh,t,r)}const Ah=oe("ZodObject",(t,r)=>{T0.init(t,r),_t.init(t,r),lt(t,"shape",()=>r.shape),t.keyof=()=>Ae(Object.keys(t._zod.def.shape)),t.catchall=i=>t.clone({...t._zod.def,catchall:i}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Cn()}),t.loose=()=>t.clone({...t._zod.def,catchall:Cn()}),t.strict=()=>t.clone({...t._zod.def,catchall:Ch()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=i=>Jd(t,i),t.merge=i=>Qd(t,i),t.pick=i=>Yd(t,i),t.omit=i=>Kd(t,i),t.partial=(...i)=>e1(Ec,t,i[0]),t.required=(...i)=>t1(Ic,t,i[0])});function N(t,r){const i={type:"object",get shape(){return Zi(this,"shape",{...t}),this.shape},...Ie(r)};return new Ah(i)}const Ac=oe("ZodUnion",(t,r)=>{xc.init(t,r),_t.init(t,r),t.options=r.options});function st(t,r){return new Ac({type:"union",options:t,...Ie(r)})}const Eh=oe("ZodDiscriminatedUnion",(t,r)=>{Ac.init(t,r),N0.init(t,r)});function mt(t,r,i){return new Eh({type:"union",options:r,discriminator:t,...Ie(i)})}const Ih=oe("ZodIntersection",(t,r)=>{O0.init(t,r),_t.init(t,r)});function Sh(t,r){return new Ih({type:"intersection",left:t,right:r})}const Th=oe("ZodRecord",(t,r)=>{k0.init(t,r),_t.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function wt(t,r,i){return new Th({type:"record",keyType:t,valueType:r,...Ie(i)})}const Ai=oe("ZodEnum",(t,r)=>{R0.init(t,r),_t.init(t,r),t.enum=r.entries,t.options=Object.values(r.entries);const i=new Set(Object.keys(r.entries));t.extract=(c,d)=>{const f={};for(const m of c)if(i.has(m))f[m]=r.entries[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})},t.exclude=(c,d)=>{const f={...r.entries};for(const m of c)if(i.has(m))delete f[m];else throw new Error(`Key ${m} not found in enum`);return new Ai({...r,checks:[],...Ie(d),entries:f})}});function Ae(t,r){const i=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new Ai({type:"enum",entries:i,...Ie(r)})}const Nh=oe("ZodLiteral",(t,r)=>{M0.init(t,r),_t.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 Y(t,r){return new Nh({type:"literal",values:Array.isArray(t)?t:[t],...Ie(r)})}const Oh=oe("ZodTransform",(t,r)=>{D0.init(t,r),_t.init(t,r),t._zod.parse=(i,c)=>{i.addIssue=f=>{if(typeof f=="string")i.issues.push(eo(f,i.value,r));else{const m=f;m.fatal&&(m.continue=!1),m.code??(m.code="custom"),m.input??(m.input=i.value),m.inst??(m.inst=t),m.continue??(m.continue=!0),i.issues.push(eo(m))}};const d=r.transform(i.value,i);return d instanceof Promise?d.then(f=>(i.value=f,i)):(i.value=d,i)}});function kh(t){return new Oh({type:"transform",transform:t})}const Ec=oe("ZodOptional",(t,r)=>{P0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Hs(t){return new Ec({type:"optional",innerType:t})}const Rh=oe("ZodNullable",(t,r)=>{B0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Ws(t){return new Rh({type:"nullable",innerType:t})}const Mh=oe("ZodDefault",(t,r)=>{L0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function Dh(t,r){return new Mh({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ph=oe("ZodPrefault",(t,r)=>{F0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Bh(t,r){return new Ph({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ic=oe("ZodNonOptional",(t,r)=>{U0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Lh(t,r){return new Ic({type:"nonoptional",innerType:t,...Ie(r)})}const Fh=oe("ZodCatch",(t,r)=>{z0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Uh(t,r){return new Fh({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const zh=oe("ZodPipe",(t,r)=>{V0.init(t,r),_t.init(t,r),t.in=r.in,t.out=r.out});function Gs(t,r){return new zh({type:"pipe",in:t,out:r})}const Vh=oe("ZodReadonly",(t,r)=>{Z0.init(t,r),_t.init(t,r)});function Zh(t){return new Vh({type:"readonly",innerType:t})}const $h=oe("ZodLazy",(t,r)=>{$0.init(t,r),_t.init(t,r),t.unwrap=()=>t._zod.def.getter()});function Wi(t){return new $h({type:"lazy",getter:t})}const jh=oe("ZodCustom",(t,r)=>{j0.init(t,r),_t.init(t,r)});function Hh(t){const r=new on({check:"custom"});return r._zod.check=t,r}function Wh(t,r={}){return Ff(jh,t,r)}function Gh(t){const r=Hh(i=>(i.addIssue=c=>{if(typeof c=="string")i.issues.push(eo(c,i.value,r._zod.def));else{const d=c;d.fatal&&(d.continue=!1),d.code??(d.code="custom"),d.input??(d.input=i.value),d.inst??(d.inst=r),d.continue??(d.continue=!r._zod.def.abort),i.issues.push(eo(d))}},t(i.value,i)));return r}function qh(t){return _f(Hi,t)}var je;(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"})(je||(je={}));function qs(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function zo(t){return Object.fromEntries([...t.headers])}var Xh=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Dl({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},bo=Xh();function Ei(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Yh=["fetch failed","failed to fetch"];function Kh({error:t,url:r,requestBodyValues:i}){if(Ei(t))return t;if(t instanceof TypeError&&Yh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Vn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return t}function Jh(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function Qh(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function Sc(t,...r){const i=new Headers(Qh(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var ep="3.0.18";function tp({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new wo({message:`${c} API key must be a string.`});if(typeof process>"u")throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new wo({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new wo({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var np=/"__proto__"\s*:/,rp=/"constructor"\s*:/;function Xs(t){const r=JSON.parse(t);return r===null||typeof r!="object"||np.test(t)===!1&&rp.test(t)===!1?r:op(r)}function op(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){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 d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function Gi(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Xs(t)}try{return Xs(t)}finally{Error.stackTraceLimit=r}}var Ii=Symbol.for("vercel.ai.validator");function ip(t){return{[Ii]:!0,validate:t}}function sp(t){return typeof t=="object"&&t!==null&&Ii in t&&t[Ii]===!0&&"validate"in t}function ap(t){return sp(t)?t:typeof t=="function"?t():lp(t)}function lp(t){return ip(async r=>{const i=await t["~standard"].validate(r);return i.issues==null?{success:!0,value:i.value}:{success:!1,error:new Jr({value:r,cause:i.issues})}})}async function cp({value:t,schema:r}){const i=await to({value:t,schema:r});if(!i.success)throw Jr.wrap({value:t,cause:i.error});return i.value}async function to({value:t,schema:r}){const i=ap(r);try{if(i.validate==null)return{success:!0,value:t,rawValue:t};const c=await i.validate(t);return c.success?{success:!0,value:c.value,rawValue:t}:{success:!1,error:Jr.wrap({value:t,cause:c.error}),rawValue:t}}catch(c){return{success:!1,error:Jr.wrap({value:t,cause:c}),rawValue:t}}}async function up({text:t,schema:r}){try{const i=Gi(t);return r==null?i:cp({value:i,schema:r})}catch(i){throw Oo.isInstance(i)||Jr.isInstance(i)?i:new Oo({text:t,cause:i})}}async function Tc({text:t,schema:r}){try{const i=Gi(t);return r==null?{success:!0,value:i,rawValue:i}:await to({value:i,schema:r})}catch(i){return{success:!1,error:Oo.isInstance(i)?i:new Oo({text:t,cause:i}),rawValue:void 0}}}function Ys(t){try{return Gi(t),!0}catch{return!1}}function dp({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await Tc({text:i,schema:r}))}}))}async function Ks({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await to({value:r[t],schema:i});if(!c.success)throw new Dl({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var fp=()=>globalThis.fetch,Js=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>hp({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),hp=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=fp()})=>{try{const x=await m(t,{method:"POST",headers:Sc(r,`ai-sdk/provider-utils/${ep}`,Jh()),body:i.content,signal:f}),v=zo(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ei(E)||Vn.isInstance(E)?E:new Vn({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ei(g)||Vn.isInstance(g))?g:new Vn({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw Kh({error:x,url:t,requestBodyValues:i.values})}},pp=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await c.text(),x=zo(c);if(m.trim()==="")return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await up({text:m,schema:t});return{responseHeaders:x,value:new Vn({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Vn({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},mp=t=>async({response:r})=>{const i=zo(r);if(r.body==null)throw new Md({});return{responseHeaders:i,value:dp({stream:r.body,schema:t})}},gp=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await r.text(),f=await Tc({text:d,schema:t}),m=zo(r);if(!f.success)throw new Vn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:xp}=globalThis;function yp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return xp(r)}function wp(t){return t instanceof Uint8Array?yp(t):t}function _p(t){return t?.replace(/\/$/,"")}function $r(t){var r,i;return(i=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?i:{}}function vp(t){const r=[];for(const{role:i,content:c,...d}of t){const f=$r({...d});switch(i){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,...$r(c[0])});break}r.push({role:"user",content:c.map(m=>{const x=$r(m);switch(m.type){case"text":return{type:"text",text:m.text,...x};case"file":if(m.mediaType.startsWith("image/")){const v=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${v};base64,${wp(m.data)}`},...x}}else throw new Ql({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const x=[];for(const v of c){const g=$r(v);switch(v.type){case"text":{m+=v.text;break}case"tool-call":{x.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.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 v;switch(x.type){case"text":case"error-text":v=x.value;break;case"content":case"json":case"error-json":v=JSON.stringify(x.value);break}const g=$r(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:v,...g})}break}default:{const m=i;throw new Error(`Unsupported role: ${m}`)}}}return r}function Qs({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function ea(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 di=N({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),Cp=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),bp={errorSchema:Cp,errorToMessage:t=>t.error.message};function Ap({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};const c=[];for(const f of t)f.type==="provider-defined"?i.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:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Ql({functionality:`tool choice type: ${f}`})}}}var Ep=class{constructor(t,r){this.specificationVersion="v2";var i,c;this.modelId=t,this.config=r;const d=(i=r.errorStructure)!=null?i:bp;this.chunkSchema=Sp(d.errorSchema),this.failedResponseHandler=pp(d),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,i;return(i=(r=(t=this.config).supportedUrls)==null?void 0:r.call(t))!=null?i:{}}async getArgs({prompt:t,maxOutputTokens:r,temperature:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,providerOptions:x,stopSequences:v,responseFormat:g,seed:E,toolChoice:A,tools:D}){var T,S,P,M;const ee=[],$=Object.assign((T=await Ks({provider:"openai-compatible",providerOptions:x,schema:di}))!=null?T:{},(S=await Ks({provider:this.providerOptionsName,providerOptions:x,schema:di}))!=null?S:{});d!=null&&ee.push({type:"unsupported-setting",setting:"topK"}),g?.type==="json"&&g.schema!=null&&!this.supportsStructuredOutputs&&ee.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:F,toolChoice:re,toolWarnings:Z}=Ap({tools:D,toolChoice:A});return{args:{model:this.modelId,user:$.user,max_tokens:r,temperature:i,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:(P=g.name)!=null?P:"response",description:g.description}}:{type:"json_object"}:void 0,stop:v,seed:E,...Object.fromEntries(Object.entries((M=x?.[this.providerOptionsName])!=null?M:{}).filter(([B])=>!Object.keys(di.shape).includes(B))),reasoning_effort:$.reasoningEffort,verbosity:$.textVerbosity,messages:vp(t),tools:F,tool_choice:re},warnings:[...ee,...Z]}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee;const{args:$,warnings:F}=await this.getArgs({...t}),re=JSON.stringify($),{responseHeaders:Z,value:B,rawValue:L}=await Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:$,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:gp(Ip),abortSignal:t.abortSignal,fetch:this.config.fetch}),W=B.choices[0],z=[],we=W.message.content;we!=null&&we.length>0&&z.push({type:"text",text:we});const G=(r=W.message.reasoning_content)!=null?r:W.message.reasoning;if(G!=null&&G.length>0&&z.push({type:"reasoning",text:G}),W.message.tool_calls!=null)for(const te of W.message.tool_calls)z.push({type:"tool-call",toolCallId:(i=te.id)!=null?i:bo(),toolName:te.function.name,input:te.function.arguments});const me={[this.providerOptionsName]:{},...await((d=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:d.call(c,{parsedBody:L}))},fe=(f=B.usage)==null?void 0:f.completion_tokens_details;return fe?.accepted_prediction_tokens!=null&&(me[this.providerOptionsName].acceptedPredictionTokens=fe?.accepted_prediction_tokens),fe?.rejected_prediction_tokens!=null&&(me[this.providerOptionsName].rejectedPredictionTokens=fe?.rejected_prediction_tokens),{content:z,finishReason:ea(W.finish_reason),usage:{inputTokens:(x=(m=B.usage)==null?void 0:m.prompt_tokens)!=null?x:void 0,outputTokens:(g=(v=B.usage)==null?void 0:v.completion_tokens)!=null?g:void 0,totalTokens:(A=(E=B.usage)==null?void 0:E.total_tokens)!=null?A:void 0,reasoningTokens:(S=(T=(D=B.usage)==null?void 0:D.completion_tokens_details)==null?void 0:T.reasoning_tokens)!=null?S:void 0,cachedInputTokens:(ee=(M=(P=B.usage)==null?void 0:P.prompt_tokens_details)==null?void 0:M.cached_tokens)!=null?ee:void 0},providerMetadata:me,request:{body:re},response:{...Qs(B),headers:Z,body:L},warnings:F}}async doStream(t){var r;const{args:i,warnings:c}=await this.getArgs({...t}),d={...i,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 Js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:qs(this.config.headers(),t.headers),body:d,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:mp(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),v=[];let g="unknown";const E={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 D=this.providerOptionsName;let T=!1,S=!1;return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:c})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g="error",M.enqueue({type:"error",error:P.error});return}const te=P.value;if(f?.processChunk(P.rawValue),"error"in te){g="error",M.enqueue({type:"error",error:te.error.message});return}if(A&&(A=!1,M.enqueue({type:"response-metadata",...Qs(te)})),te.usage!=null){const{prompt_tokens:Te,completion_tokens:Je,total_tokens:xe,prompt_tokens_details:$e,completion_tokens_details:Ue}=te.usage;E.promptTokens=Te??void 0,E.completionTokens=Je??void 0,E.totalTokens=xe??void 0,Ue?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=Ue?.reasoning_tokens),Ue?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=Ue?.accepted_prediction_tokens),Ue?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=Ue?.rejected_prediction_tokens),$e?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=$e?.cached_tokens)}const q=te.choices[0];if(q?.finish_reason!=null&&(g=ea(q.finish_reason)),q?.delta==null)return;const ke=q.delta,le=(ee=ke.reasoning_content)!=null?ee:ke.reasoning;if(le&&(T||(M.enqueue({type:"reasoning-start",id:"reasoning-0"}),T=!0),M.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:le})),ke.content&&(S||(M.enqueue({type:"text-start",id:"txt-0"}),S=!0),M.enqueue({type:"text-delta",id:"txt-0",delta:ke.content})),ke.tool_calls!=null)for(const Te of ke.tool_calls){const Je=Te.index;if(v[Je]==null){if(Te.id==null)throw new bs({data:Te,message:"Expected 'id' to be a string."});if((($=Te.function)==null?void 0:$.name)==null)throw new bs({data:Te,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:Te.id,toolName:Te.function.name}),v[Je]={id:Te.id,type:"function",function:{name:Te.function.name,arguments:(F=Te.function.arguments)!=null?F:""},hasFinished:!1};const $e=v[Je];((re=$e.function)==null?void 0:re.name)!=null&&((Z=$e.function)==null?void 0:Z.arguments)!=null&&($e.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:$e.id,delta:$e.function.arguments}),Ys($e.function.arguments)&&(M.enqueue({type:"tool-input-end",id:$e.id}),M.enqueue({type:"tool-call",toolCallId:(B=$e.id)!=null?B:bo(),toolName:$e.function.name,input:$e.function.arguments}),$e.hasFinished=!0));continue}const xe=v[Je];xe.hasFinished||(((L=Te.function)==null?void 0:L.arguments)!=null&&(xe.function.arguments+=(z=(W=Te.function)==null?void 0:W.arguments)!=null?z:""),M.enqueue({type:"tool-input-delta",id:xe.id,delta:(we=Te.function.arguments)!=null?we:""}),((G=xe.function)==null?void 0:G.name)!=null&&((me=xe.function)==null?void 0:me.arguments)!=null&&Ys(xe.function.arguments)&&(M.enqueue({type:"tool-input-end",id:xe.id}),M.enqueue({type:"tool-call",toolCallId:(fe=xe.id)!=null?fe:bo(),toolName:xe.function.name,input:xe.function.arguments}),xe.hasFinished=!0))}},flush(P){var M,ee,$,F,re,Z;T&&P.enqueue({type:"reasoning-end",id:"reasoning-0"}),S&&P.enqueue({type:"text-end",id:"txt-0"});for(const L of v.filter(W=>!W.hasFinished))P.enqueue({type:"tool-input-end",id:L.id}),P.enqueue({type:"tool-call",toolCallId:(M=L.id)!=null?M:bo(),toolName:L.function.name,input:L.function.arguments});const B={[D]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(B[D].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(B[D].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),P.enqueue({type:"finish",finishReason:g,usage:{inputTokens:(ee=E.promptTokens)!=null?ee:void 0,outputTokens:($=E.completionTokens)!=null?$:void 0,totalTokens:(F=E.totalTokens)!=null?F:void 0,reasoningTokens:(re=E.completionTokensDetails.reasoningTokens)!=null?re:void 0,cachedInputTokens:(Z=E.promptTokensDetails.cachedTokens)!=null?Z:void 0},providerMetadata:B})}})),request:{body:d},response:{headers:m}}}},Nc=N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),Ip=N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({id:w().nullish(),function:N({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:Nc}),Sp=t=>st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:Nc}),t]);N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var Tp=N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w()})),usage:Tp.nullish()});N({dimensions:j().optional(),user:w().optional()});N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish(),providerMetadata:wt(w(),wt(w(),xr())).optional()});N({data:ue(N({b64_json:w()}))});var ta=t=>{var r,i;return t==null?void 0:{deepseek:{promptCacheHitTokens:(r=t.prompt_cache_hit_tokens)!=null?r:NaN,promptCacheMissTokens:(i=t.prompt_cache_miss_tokens)!=null?i:NaN}}},Np={extractMetadata:async({parsedBody:t})=>{const r=await to({value:t,schema:Op});return!r.success||r.value.usage==null?void 0:ta(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var i,c;const d=await to({value:r,schema:kp});d.success&&((c=(i=d.value.choices)==null?void 0:i[0])==null?void 0:c.finish_reason)==="stop"&&d.value.usage&&(t=d.value.usage)},buildMetadata:()=>ta(t)}}},Oc=N({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),Op=N({usage:Oc.nullish()}),kp=N({choices:ue(N({finish_reason:w().nullish()})).nullish(),usage:Oc.nullish()}),Rp="1.0.30";function kc(t={}){var r;const i=_p((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>Sc({Authorization:`Bearer ${tp({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${Rp}`);class d extends Ep{addJsonInstruction(v){var g;if(((g=v.responseFormat)==null?void 0:g.type)!=="json")return v;const D=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:D}}async doGenerate(v){return super.doGenerate(this.addJsonInstruction(v))}async doStream(v){return super.doStream(this.addJsonInstruction(v))}}const f=x=>new d(x,{provider:"deepseek.chat",url:({path:v})=>`${i}${v}`,headers:c,fetch:t.fetch,metadataExtractor:Np}),m=x=>f(x);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=x=>{throw new As({modelId:x,modelType:"textEmbeddingModel"})},m.imageModel=x=>{throw new As({modelId:x,modelType:"imageModel"})},m}kc();var Rc="vercel.ai.error",Mp=Symbol.for(Rc),na,ra,kt=class Mc extends(ra=Error,na=Mp,ra){constructor({name:r,message:i,cause:c}){super(i),this[na]=!0,this.name=r,this.cause=c}static isInstance(r){return Mc.hasMarker(r,Rc)}static hasMarker(r,i){const c=Symbol.for(i);return r!=null&&typeof r=="object"&&c in r&&typeof r[c]=="boolean"&&r[c]===!0}},Dc="AI_APICallError",Pc=`vercel.ai.error.${Dc}`,Dp=Symbol.for(Pc),oa,ia,Kt=class extends(ia=kt,oa=Dp,ia){constructor({message:t,url:r,requestBodyValues:i,statusCode:c,responseHeaders:d,responseBody:f,cause:m,isRetryable:x=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Dc,message:t,cause:m}),this[oa]=!0,this.url=r,this.requestBodyValues=i,this.statusCode=c,this.responseHeaders=d,this.responseBody=f,this.isRetryable=x,this.data=v}static isInstance(t){return kt.hasMarker(t,Pc)}},Bc="AI_EmptyResponseBodyError",Lc=`vercel.ai.error.${Bc}`,Pp=Symbol.for(Lc),sa,aa,Bp=class extends(aa=kt,sa=Pp,aa){constructor({message:t="Empty response body"}={}){super({name:Bc,message:t}),this[sa]=!0}static isInstance(t){return kt.hasMarker(t,Lc)}};function Fc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Uc="AI_InvalidArgumentError",zc=`vercel.ai.error.${Uc}`,Lp=Symbol.for(zc),la,ca,Vc=class extends(ca=kt,la=Lp,ca){constructor({message:t,cause:r,argument:i}){super({name:Uc,message:t,cause:r}),this[la]=!0,this.argument=i}static isInstance(t){return kt.hasMarker(t,zc)}},Zc="AI_InvalidPromptError",$c=`vercel.ai.error.${Zc}`,Fp=Symbol.for($c),ua,da,Up=class extends(da=kt,ua=Fp,da){constructor({prompt:t,message:r,cause:i}){super({name:Zc,message:`Invalid prompt: ${r}`,cause:i}),this[ua]=!0,this.prompt=t}static isInstance(t){return kt.hasMarker(t,$c)}},jc="AI_InvalidResponseDataError",Hc=`vercel.ai.error.${jc}`,zp=Symbol.for(Hc),fa,ha,fi=class extends(ha=kt,fa=zp,ha){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:jc,message:r}),this[fa]=!0,this.data=t}static isInstance(t){return kt.hasMarker(t,Hc)}},Wc="AI_JSONParseError",Gc=`vercel.ai.error.${Wc}`,Vp=Symbol.for(Gc),pa,ma,Do=class extends(ma=kt,pa=Vp,ma){constructor({text:t,cause:r}){super({name:Wc,message:`JSON parsing failed: Text: ${t}.
40
+ Error message: ${Fc(r)}`,cause:r}),this[pa]=!0,this.text=t}static isInstance(t){return kt.hasMarker(t,Gc)}},qc="AI_LoadAPIKeyError",Xc=`vercel.ai.error.${qc}`,Zp=Symbol.for(Xc),ga,xa,Ao=class extends(xa=kt,ga=Zp,xa){constructor({message:t}){super({name:qc,message:t}),this[ga]=!0}static isInstance(t){return kt.hasMarker(t,Xc)}},Yc="AI_TooManyEmbeddingValuesForCallError",Kc=`vercel.ai.error.${Yc}`,$p=Symbol.for(Kc),ya,wa,jp=class extends(wa=kt,ya=$p,wa){constructor(t){super({name:Yc,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[ya]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return kt.hasMarker(t,Kc)}},Jc="AI_TypeValidationError",Qc=`vercel.ai.error.${Jc}`,Hp=Symbol.for(Qc),_a,va,no=class Si extends(va=kt,_a=Hp,va){constructor({value:r,cause:i,context:c}){let d="Type validation failed";if(c?.field&&(d+=` for ${c.field}`),c?.entityName||c?.entityId){d+=" (";const f=[];c.entityName&&f.push(c.entityName),c.entityId&&f.push(`id: "${c.entityId}"`),d+=f.join(", "),d+=")"}super({name:Jc,message:`${d}: Value: ${JSON.stringify(r)}.
41
+ Error message: ${Fc(i)}`,cause:i}),this[_a]=!0,this.value=r,this.context=c}static isInstance(r){return kt.hasMarker(r,Qc)}static wrap({value:r,cause:i,context:c}){var d,f,m;return Si.isInstance(i)&&i.value===r&&((d=i.context)==null?void 0:d.field)===c?.field&&((f=i.context)==null?void 0:f.entityName)===c?.entityName&&((m=i.context)==null?void 0:m.entityId)===c?.entityId?i:new Si({value:r,cause:i,context:c})}},eu="AI_UnsupportedFunctionalityError",tu=`vercel.ai.error.${eu}`,Wp=Symbol.for(tu),Ca,ba,Mn=class extends(ba=kt,Ca=Wp,ba){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:eu,message:r}),this[Ca]=!0,this.functionality=t}static isInstance(t){return kt.hasMarker(t,tu)}};function bn(...t){return t.reduce((r,i)=>({...r,...i??{}}),{})}function Gp({tools:t=[],providerToolNames:r,resolveProviderToolName:i}){var c;const d={},f={};for(const m of t)if(m.type==="provider"){const x=(c=i?.(m))!=null?c:m.id in r?r[m.id]:void 0;if(x==null)continue;d[m.name]=x,f[x]=m.name}return{toProviderToolName:m=>{var x;return(x=d[m])!=null?x:m},toCustomToolName:m=>{var x;return(x=f[m])!=null?x:m}}}var qp=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 ao(t){return Object.fromEntries([...t.headers])}var{btoa:Xp,atob:Yp}=globalThis;function qi(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),i=Yp(r);return Uint8Array.from(i,c=>c.codePointAt(0))}function Kp(t){let r="";for(let i=0;i<t.length;i++)r+=String.fromCodePoint(t[i]);return Xp(r)}function kr(t){return t instanceof Uint8Array?Kp(t):t}function Jp(t,r={}){const{useArrayBrackets:i=!0}=r,c=new FormData;for(const[d,f]of Object.entries(t))if(f!=null){if(Array.isArray(f)){if(f.length===1){c.append(d,f[0]);continue}const m=i?`${d}[]`:d;for(const x of f)c.append(m,x);continue}c.append(d,f)}return c}async function Xi(t){var r;try{await((r=t.body)==null?void 0:r.cancel())}catch{}}var nu="AI_DownloadError",ru=`vercel.ai.error.${nu}`,Qp=Symbol.for(ru),Aa,Ea,cn=class extends(Ea=kt,Aa=Qp,Ea){constructor({url:t,statusCode:r,statusText:i,cause:c,message:d=c==null?`Failed to download ${t}: ${r} ${i}`:`Failed to download ${t}: ${c}`}){super({name:nu,message:d,cause:c}),this[Aa]=!0,this.url=t,this.statusCode=r,this.statusText=i}static isInstance(t){return kt.hasMarker(t,ru)}};function em(t=globalThis){return t.window!=null}function tm(t){let r;try{r=new URL(t)}catch{throw new cn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol==="data:")return;if(r.protocol!=="http:"&&r.protocol!=="https:")throw new cn({url:t,message:`URL scheme must be http, https, or data, got ${r.protocol}`});const i=r.hostname.toLowerCase().replace(/\.+$/,"");if(!i)throw new cn({url:t,message:"URL must have a hostname"});if(i==="localhost"||i.endsWith(".local")||i.endsWith(".localhost"))throw new cn({url:t,message:`URL with hostname ${i} is not allowed`});if(i.startsWith("[")&&i.endsWith("]")){const c=i.slice(1,-1);if(rm(c))throw new cn({url:t,message:`URL with IPv6 address ${i} is not allowed`});return}if(ou(i)){if(iu(i))throw new cn({url:t,message:`URL with IP address ${i} is not allowed`});return}}function ou(t){const r=t.split(".");return r.length!==4?!1:r.every(i=>{const c=Number(i);return Number.isInteger(c)&&c>=0&&c<=255&&String(c)===i})}function iu(t){const r=t.split(".").map(Number),[i,c,d]=r;return i===0||i===10||i===100&&c>=64&&c<=127||i===127||i===169&&c===254||i===172&&c>=16&&c<=31||i===192&&c===0&&d===0||i===192&&c===168||i===198&&(c===18||c===19)||i>=240}function nm(t){let r=t.toLowerCase();const i=r.indexOf("%");i!==-1&&(r=r.slice(0,i));const c=r.split("::");if(c.length>2)return null;const d=m=>{if(m==="")return[];const x=[],v=m.split(":");for(let g=0;g<v.length;g++){const E=v[g];if(E.includes(".")){if(g!==v.length-1||!ou(E))return null;const[A,D,T,S]=E.split(".").map(Number);x.push(A<<8|D,T<<8|S);continue}if(!/^[0-9a-f]{1,4}$/.test(E))return null;x.push(parseInt(E,16))}return x},f=d(c[0]);if(f===null)return null;if(c.length===2){const m=d(c[1]);if(m===null)return null;const x=8-f.length-m.length;return x<0?null:[...f,...new Array(x).fill(0),...m]}return f.length===8?f:null}function rm(t){const r=nm(t);if(r===null)return!0;const i=d=>r.slice(0,d).every(f=>f===0);if(i(7)&&(r[7]===0||r[7]===1)||(r[0]&65024)===64512||(r[0]&65472)===65152||(r[0]&65472)===65216||(r[0]&65280)===65280)return!0;if(i(6)||i(5)&&r[5]===65535||i(4)&&r[4]===65535&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===0&&r[3]===0&&r[4]===0&&r[5]===0||r[0]===100&&r[1]===65435&&r[2]===1){const d=r[6]>>8&255,f=r[6]&255,m=r[7]>>8&255,x=r[7]&255;return iu(`${d}.${f}.${m}.${x}`)}return!1}var om=10;async function im({url:t,headers:r,abortSignal:i,maxRedirects:c=om}){const d={signal:i};r!==void 0&&(d.headers=r);let f=t;for(let m=0;m<=c;m++){tm(f);const x=await fetch(f,{...d,redirect:"manual"});if(x.type==="opaqueredirect"){if(!em())throw new cn({url:t,message:`Redirect from ${f} could not be validated and was blocked`});return await fetch(f,{...d,redirect:"follow"})}const v=x.headers.get("location");if(x.status>=300&&x.status<400&&v){await Xi(x),f=new URL(v,f).toString();continue}return x}throw new cn({url:t,message:`Too many redirects (max ${c})`})}var su=2*1024*1024*1024;async function au({response:t,url:r,maxBytes:i=su}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>i)throw await Xi(t),new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes (Content-Length: ${E}).`})}const d=t.body;if(d==null)return new Uint8Array(0);const f=d.getReader(),m=[];let x=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(x+=A.length,x>i)throw new cn({url:r,message:`Download of ${r} exceeded maximum size of ${i} bytes.`});m.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(x);let g=0;for(const E of m)v.set(E,g),g+=E.length;return v}async function lu(t,r){var i,c;try{const d=await im({url:t,abortSignal:r?.abortSignal});if(!d.ok)throw await Xi(d),new cn({url:t,statusCode:d.status,statusText:d.statusText});const f=await au({response:d,url:t,maxBytes:(i=r?.maxBytes)!=null?i:su}),m=(c=d.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(d){throw cn.isInstance(d)?d:new cn({url:t,cause:d})}}var sm=({prefix:t,size:r=16,alphabet:i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const d=()=>{const f=i.length,m=new Array(r);for(let x=0;x<r;x++)m[x]=i[Math.random()*f|0];return m.join("")};if(t==null)return d;if(i.includes(c))throw new Vc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${i}".`});return()=>`${t}${c}${d()}`},rn=sm();function Ti(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var am=["fetch failed","failed to fetch"],lm=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function cm(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&lm.includes(r))}function um({error:t,url:r,requestBodyValues:i}){if(Ti(t))return t;if(t instanceof TypeError&&am.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Kt({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:i,isRetryable:!0})}return cm(t)?new Kt({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:i,isRetryable:!0}):t}function dm(t=globalThis){var r,i,c;return t.window?"runtime/browser":(r=t.navigator)!=null&&r.userAgent?`runtime/${t.navigator.userAgent.toLowerCase()}`:(c=(i=t.process)==null?void 0:i.versions)!=null&&c.node?`runtime/node.js/${t.process.version.substring(0)}`:t.EdgeRuntime?"runtime/vercel-edge":"runtime/unknown"}function fm(t){if(t==null)return{};const r={};if(t instanceof Headers)t.forEach((i,c)=>{r[c.toLowerCase()]=i});else{Array.isArray(t)||(t=Object.entries(t));for(const[i,c]of t)c!=null&&(r[i.toLowerCase()]=c)}return r}function cu(t,...r){const i=new Headers(fm(t)),c=i.get("user-agent")||"";return i.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(i.entries())}var hm="4.0.38";function Ia(t){return t!=null}function pm({apiKey:t,environmentVariableName:r,apiKeyParameterName:i="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new Ao({message:`${c} API key must be a string.`});if(typeof process>"u")throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter. Environment variables are not supported in this environment.`});if(t=process.env[r],t==null)throw new Ao({message:`${c} API key is missing. Pass it using the '${i}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new Ao({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function mm({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 gm(t){var r;const[i,c=""]=t.toLowerCase().split("/");return(r={mpeg:"mp3","x-wav":"wav",opus:"ogg",mp4:"m4a","x-m4a":"m4a"}[c])!=null?r:c}var xm=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ym=/"(?: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 Sa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||xm.test(t)===!1&&ym.test(t)===!1?r:wm(r)}function wm(t){let r=[t];for(;r.length;){const i=r;r=[];for(const c of i){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 d in c){const f=c[d];f&&typeof f=="object"&&r.push(f)}}}return t}function uu(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Sa(t)}try{return Sa(t)}finally{Error.stackTraceLimit=r}}function Yi(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:i}=t;if(i!=null)for(const c of Object.keys(i))i[c]=dr(i[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(dr):dr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(dr)),t.allOf!=null&&(t.allOf=t.allOf.map(dr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(dr));const{definitions:r}=t;if(r!=null)for(const i of Object.keys(r))r[i]=dr(r[i]);return t}function dr(t){return typeof t=="boolean"?t:Yi(t)}var _m=Symbol("Let zodToJsonSchema decide on which parser to use"),Ta={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"},vm=t=>typeof t=="string"?{...Ta,name:t}:{...Ta,...t};function fn(){return{}}function Cm(t,r){var i,c,d;const f={type:"array"};return(i=t.type)!=null&&i._def&&((d=(c=t.type)==null?void 0:c._def)==null?void 0:d.typeName)!==je.ZodAny&&(f.items=ct(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 bm(t){const r={type:"integer",format:"int64"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function Am(){return{type:"boolean"}}function du(t,r){return ct(t.type._def,r)}var Em=(t,r)=>ct(t.innerType._def,r);function fu(t,r,i){const c=i??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((d,f)=>fu(t,r,d))};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 Im(t)}}var Im=t=>{const r={type:"integer",format:"unix-time"};for(const i of t.checks)switch(i.kind){case"min":r.minimum=i.value;break;case"max":r.maximum=i.value;break}return r};function Sm(t,r){return{...ct(t.innerType._def,r),default:t.defaultValue()}}function Tm(t,r){return r.effectStrategy==="input"?ct(t.schema._def,r):fn()}function Nm(t){return{type:"string",enum:Array.from(t.values)}}var Om=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function km(t,r){const i=[ct(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),ct(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(d=>!!d),c=[];return i.forEach(d=>{if(Om(d))c.push(...d.allOf);else{let f=d;if("additionalProperties"in d&&d.additionalProperties===!1){const{additionalProperties:m,...x}=d;f=x}c.push(f)}}),c.length?{allOf:c}:void 0}function Rm(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 hi=void 0,wn={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:()=>(hi===void 0&&(hi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),hi),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 hu(t,r){const i={type:"string"};if(t.checks)for(const c of t.checks)switch(c.kind){case"min":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value;break;case"max":i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"email":switch(r.emailStrategy){case"format:email":_n(i,"email",c.message,r);break;case"format:idn-email":_n(i,"idn-email",c.message,r);break;case"pattern:zod":Yt(i,wn.email,c.message,r);break}break;case"url":_n(i,"uri",c.message,r);break;case"uuid":_n(i,"uuid",c.message,r);break;case"regex":Yt(i,c.regex,c.message,r);break;case"cuid":Yt(i,wn.cuid,c.message,r);break;case"cuid2":Yt(i,wn.cuid2,c.message,r);break;case"startsWith":Yt(i,RegExp(`^${pi(c.value,r)}`),c.message,r);break;case"endsWith":Yt(i,RegExp(`${pi(c.value,r)}$`),c.message,r);break;case"datetime":_n(i,"date-time",c.message,r);break;case"date":_n(i,"date",c.message,r);break;case"time":_n(i,"time",c.message,r);break;case"duration":_n(i,"duration",c.message,r);break;case"length":i.minLength=typeof i.minLength=="number"?Math.max(i.minLength,c.value):c.value,i.maxLength=typeof i.maxLength=="number"?Math.min(i.maxLength,c.value):c.value;break;case"includes":{Yt(i,RegExp(pi(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(i,"ipv4",c.message,r),c.version!=="v4"&&_n(i,"ipv6",c.message,r);break}case"base64url":Yt(i,wn.base64url,c.message,r);break;case"jwt":Yt(i,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(i,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(i,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(i,wn.emoji(),c.message,r);break;case"ulid":{Yt(i,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(i,"binary",c.message,r);break}case"contentEncoding:base64":{i.contentEncoding="base64";break}case"pattern:zod":{Yt(i,wn.base64,c.message,r);break}}break}case"nanoid":Yt(i,wn.nanoid,c.message,r)}return i}function pi(t,r){return r.patternStrategy==="escape"?Dm(t):t}var Mm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Dm(t){let r="";for(let i=0;i<t.length;i++)Mm.has(t[i])||(r+="\\"),r+=t[i];return r}function _n(t,r,i,c){var d;t.format||(d=t.anyOf)!=null&&d.some(f=>f.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format}),delete t.format),t.anyOf.push({format:r,...i&&c.errorMessages&&{errorMessage:{format:i}}})):t.format=r}function Yt(t,r,i,c){var d;t.pattern||(d=t.allOf)!=null&&d.some(f=>f.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern}),delete t.pattern),t.allOf.push({pattern:Na(r,c),...i&&c.errorMessages&&{errorMessage:{pattern:i}}})):t.pattern=Na(r,c)}function Na(t,r){var i;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")},d=c.i?t.source.toLowerCase():t.source;let f="",m=!1,x=!1,v=!1;for(let g=0;g<d.length;g++){if(m){f+=d[g],m=!1;continue}if(c.i){if(x){if(d[g].match(/[a-z]/)){v?(f+=d[g],f+=`${d[g-2]}-${d[g]}`.toUpperCase(),v=!1):d[g+1]==="-"&&((i=d[g+2])!=null&&i.match(/[a-z]/))?(f+=d[g],v=!0):f+=`${d[g]}${d[g].toUpperCase()}`;continue}}else if(d[g].match(/[a-z]/)){f+=`[${d[g]}${d[g].toUpperCase()}]`;continue}}if(c.m){if(d[g]==="^"){f+=`(^|(?<=[\r
42
+ ]))`;continue}else if(d[g]==="$"){f+=`($|(?=[\r
43
+ ]))`;continue}}if(c.s&&d[g]==="."){f+=x?`${d[g]}\r
44
+ `:`[${d[g]}\r
45
+ ]`;continue}f+=d[g],d[g]==="\\"?m=!0:x&&d[g]==="]"?x=!1:!x&&d[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 pu(t,r){var i,c,d,f,m,x;const v={type:"object",additionalProperties:(i=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?i:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===je.ZodString&&((d=t.keyType._def.checks)!=null&&d.length)){const{type:g,...E}=hu(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===je.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===je.ZodBranded&&t.keyType._def.type._def.typeName===je.ZodString&&((x=t.keyType._def.type._def.checks)!=null&&x.length)){const{type:g,...E}=du(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function Pm(t,r){if(r.mapStrategy==="record")return pu(t,r);const i=ct(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=ct(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[i,c],minItems:2,maxItems:2}}}function Bm(t){const r=t.values,c=Object.keys(t.values).filter(f=>typeof r[r[f]]!="number").map(f=>r[f]),d=Array.from(new Set(c.map(f=>typeof f)));return{type:d.length===1?d[0]==="string"?"string":"number":["string","number"],enum:c}}function Lm(){return{not:fn()}}function Fm(){return{type:"null"}}var Ni={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Um(t,r){const i=t.options instanceof Map?Array.from(t.options.values()):t.options;if(i.every(c=>c._def.typeName in Ni&&(!c._def.checks||!c._def.checks.length))){const c=i.reduce((d,f)=>{const m=Ni[f._def.typeName];return m&&!d.includes(m)?[...d,m]:d},[]);return{type:c.length>1?c:c[0]}}else if(i.every(c=>c._def.typeName==="ZodLiteral"&&!c.description)){const c=i.reduce((d,f)=>{const m=typeof f._def.value;switch(m){case"string":case"number":case"boolean":return[...d,m];case"bigint":return[...d,"integer"];case"object":if(f._def.value===null)return[...d,"null"];case"symbol":case"undefined":case"function":default:return d}},[]);if(c.length===i.length){const d=c.filter((f,m,x)=>x.indexOf(f)===m);return{type:d.length>1?d:d[0],enum:i.reduce((f,m)=>f.includes(m._def.value)?f:[...f,m._def.value],[])}}}else if(i.every(c=>c._def.typeName==="ZodEnum"))return{type:"string",enum:i.reduce((c,d)=>[...c,...d._def.values.filter(f=>!c.includes(f))],[])};return zm(t,r)}var zm=(t,r)=>{const i=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,d)=>ct(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${d}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return i.length?{anyOf:i}:void 0};function Vm(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ni[t.innerType._def.typeName],"null"]};const i=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return i&&{anyOf:[i,{type:"null"}]}}function Zm(t){const r={type:"number"};if(!t.checks)return r;for(const i of t.checks)switch(i.kind){case"int":r.type="integer";break;case"min":i.inclusive?r.minimum=i.value:r.exclusiveMinimum=i.value;break;case"max":i.inclusive?r.maximum=i.value:r.exclusiveMaximum=i.value;break;case"multipleOf":r.multipleOf=i.value;break}return r}function $m(t,r){const i={type:"object",properties:{}},c=[],d=t.shape();for(const m in d){let x=d[m];if(x===void 0||x._def===void 0)continue;const v=Hm(x),g=ct(x._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});g!==void 0&&(i.properties[m]=g,v||c.push(m))}c.length&&(i.required=c);const f=jm(t,r);return f!==void 0&&(i.additionalProperties=f),i}function jm(t,r){if(t.catchall._def.typeName!=="ZodNever")return ct(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 Hm(t){try{return t.isOptional()}catch{return!0}}var Wm=(t,r)=>{var i;if(r.currentPath.toString()===((i=r.propertyPath)==null?void 0:i.toString()))return ct(t.innerType._def,r);const c=ct(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Gm=(t,r)=>{if(r.pipeStrategy==="input")return ct(t.in._def,r);if(r.pipeStrategy==="output")return ct(t.out._def,r);const i=ct(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=ct(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",i?"1":"0"]});return{allOf:[i,c].filter(d=>d!==void 0)}};function qm(t,r){return ct(t.type._def,r)}function Xm(t,r){const c={type:"array",uniqueItems:!0,items:ct(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 Ym(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[]),additionalItems:ct(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((i,c)=>ct(i._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((i,c)=>c===void 0?i:[...i,c],[])}}function Km(){return{not:fn()}}function Jm(){return fn()}var Qm=(t,r)=>ct(t.innerType._def,r),eg=(t,r,i)=>{switch(r){case je.ZodString:return hu(t,i);case je.ZodNumber:return Zm(t);case je.ZodObject:return $m(t,i);case je.ZodBigInt:return bm(t);case je.ZodBoolean:return Am();case je.ZodDate:return fu(t,i);case je.ZodUndefined:return Km();case je.ZodNull:return Fm();case je.ZodArray:return Cm(t,i);case je.ZodUnion:case je.ZodDiscriminatedUnion:return Um(t,i);case je.ZodIntersection:return km(t,i);case je.ZodTuple:return Ym(t,i);case je.ZodRecord:return pu(t,i);case je.ZodLiteral:return Rm(t);case je.ZodEnum:return Nm(t);case je.ZodNativeEnum:return Bm(t);case je.ZodNullable:return Vm(t,i);case je.ZodOptional:return Wm(t,i);case je.ZodMap:return Pm(t,i);case je.ZodSet:return Xm(t,i);case je.ZodLazy:return()=>t.getter()._def;case je.ZodPromise:return qm(t,i);case je.ZodNaN:case je.ZodNever:return Lm();case je.ZodEffects:return Tm(t,i);case je.ZodAny:return fn();case je.ZodUnknown:return Jm();case je.ZodDefault:return Sm(t,i);case je.ZodBranded:return du(t,i);case je.ZodReadonly:return Qm(t,i);case je.ZodCatch:return Em(t,i);case je.ZodPipeline:return Gm(t,i);case je.ZodFunction:case je.ZodVoid:case je.ZodSymbol:return;default:return(c=>{})()}},tg=(t,r)=>{let i=0;for(;i<t.length&&i<r.length&&t[i]===r[i];i++);return[(t.length-i).toString(),...r.slice(i)].join("/")};function ct(t,r,i=!1){var c;const d=r.seen.get(t);if(r.override){const v=(c=r.override)==null?void 0:c.call(r,t,r,d,i);if(v!==_m)return v}if(d&&!i){const v=ng(d,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=eg(t,t.typeName,r),x=typeof m=="function"?ct(m(),r):m;if(x&&rg(t,r,x),r.postProcess){const v=r.postProcess(x,t,r);return f.jsonSchema=x,v}return f.jsonSchema=x,x}var ng=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:tg(r.currentPath,t.path)};case"none":case"seen":return t.path.length<r.currentPath.length&&t.path.every((i,c)=>r.currentPath[c]===i)?(console.warn(`Recursive reference detected at ${r.currentPath.join("/")}! Defaulting to any`),fn()):r.$refStrategy==="seen"?fn():void 0}},rg=(t,r,i)=>(t.description&&(i.description=t.description),i),og=t=>{const r=vm(t),i=r.name!==void 0?[...r.basePath,r.definitionPath,r.name]:r.basePath;return{...r,currentPath:i,propertyPath:void 0,seen:new Map(Object.entries(r.definitions).map(([c,d])=>[d._def,{def:d._def,path:[...r.basePath,r.definitionPath,c],jsonSchema:void 0}]))}},ig=(t,r)=>{var i;const c=og(r);let d=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((g,[E,A])=>{var D;return{...g,[E]:(D=ct(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?D:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(i=ct(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?i:fn(),x=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;x!==void 0&&(m.title=x);const v=f===void 0?d?{...m,[c.definitionPath]:d}:m:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...d,[f]:m}};return v.$schema="http://json-schema.org/draft-07/schema#",v},Oi=Symbol.for("vercel.ai.schema");function Fe(t){let r;return()=>(r==null&&(r=t()),r)}function Vo(t,{validate:r}={}){return{[Oi]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function sg(t){return typeof t=="object"&&t!==null&&Oi in t&&t[Oi]===!0&&"jsonSchema"in t&&"validate"in t}function ag(t){return t==null?Vo({type:"object",properties:{},additionalProperties:!1}):sg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Le(t):lg(t):t()}function lg(t){return Vo(()=>Yi(t["~standard"].jsonSchema.input({target:"draft-07"})),{validate:async r=>{const i=await t["~standard"].validate(r);return"value"in i?{success:!0,value:i.value}:{success:!1,error:new no({value:r,cause:i.issues})}}})}function cg(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>ig(t,{$refStrategy:c?"root":"none"}),{validate:async d=>{const f=await t.safeParseAsync(d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function ug(t,r){var i;const c=(i=void 0)!=null?i:!1;return Vo(()=>Yi(Uf(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async d=>{const f=await vc(t,d);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function dg(t){return"_zod"in t}function Le(t,r){return dg(t)?ug(t):cg(t)}async function Dt({value:t,schema:r,context:i}){const c=await Ki({value:t,schema:r,context:i});if(!c.success)throw no.wrap({value:t,cause:c.error,context:i});return c.value}async function Ki({value:t,schema:r,context:i}){const c=ag(r);try{if(c.validate==null)return{success:!0,value:t,rawValue:t};const d=await c.validate(t);return d.success?{success:!0,value:d.value,rawValue:t}:{success:!1,error:no.wrap({value:t,cause:d.error,context:i}),rawValue:t}}catch(d){return{success:!1,error:no.wrap({value:t,cause:d,context:i}),rawValue:t}}}async function mu({text:t,schema:r}){try{const i=uu(t);return r==null?i:Dt({value:i,schema:r})}catch(i){throw Do.isInstance(i)||no.isInstance(i)?i:new Do({text:t,cause:i})}}async function gu({text:t,schema:r}){try{const i=uu(t);return r==null?{success:!0,value:i,rawValue:i}:await Ki({value:i,schema:r})}catch(i){return{success:!1,error:Do.isInstance(i)?i:new Do({text:t,cause:i}),rawValue:void 0}}}function fg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new ec).pipeThrough(new TransformStream({async transform({data:i},c){i!=="[DONE]"&&c.enqueue(await gu({text:i,schema:r}))}}))}async function An({provider:t,providerOptions:r,schema:i}){if(r?.[t]==null)return;const c=await Ki({value:r[t],schema:i});if(!c.success)throw new Vc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var hg=()=>globalThis.fetch,Zn=async({url:t,headers:r,body:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(i),values:i},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),xu=async({url:t,headers:r,formData:i,failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m})=>yu({url:t,headers:r,body:{content:i,values:Object.fromEntries(i.entries())},failedResponseHandler:c,successfulResponseHandler:d,abortSignal:f,fetch:m}),yu=async({url:t,headers:r={},body:i,successfulResponseHandler:c,failedResponseHandler:d,abortSignal:f,fetch:m=hg()})=>{try{const x=await m(t,{method:"POST",headers:cu(r,`ai-sdk/provider-utils/${hm}`,dm()),body:i.content,signal:f}),v=ao(x);if(!x.ok){let g;try{g=await d({response:x,url:t,requestBodyValues:i.values})}catch(E){throw Ti(E)||Kt.isInstance(E)?E:new Kt({message:"Failed to process error response",cause:E,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}throw g.value}try{return await c({response:x,url:t,requestBodyValues:i.values})}catch(g){throw g instanceof Error&&(Ti(g)||Kt.isInstance(g))?g:new Kt({message:"Failed to process successful response",cause:g,statusCode:x.status,url:t,responseHeaders:v,requestBodyValues:i.values})}}catch(x){throw um({error:x,url:t,requestBodyValues:i.values})}};function pg({id:t,inputSchema:r}){return({execute:i,outputSchema:c,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v,...g})=>({type:"provider",id:t,args:g,inputSchema:r,outputSchema:c,execute:i,needsApproval:d,toModelOutput:f,onInputStart:m,onInputDelta:x,onInputAvailable:v})}function Dn({id:t,inputSchema:r,outputSchema:i,supportsDeferredResults:c}){return({execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:i,execute:d,needsApproval:f,toModelOutput:m,onInputStart:x,onInputDelta:v,onInputAvailable:g,supportsDeferredResults:c})}var mg=new TextDecoder;async function wu({response:t,url:r}){return mg.decode(await au({response:t,url:r}))}var gg=({errorSchema:t,errorToMessage:r,isRetryable:i})=>async({response:c,url:d,requestBodyValues:f})=>{const m=await wu({response:c,url:d}),x=ao(c);if(m.trim()==="")return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})};try{const v=await mu({text:m,schema:t});return{responseHeaders:x,value:new Kt({message:r(v),url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,data:v,isRetryable:i?.(c,v)})}}catch{return{responseHeaders:x,value:new Kt({message:c.statusText,url:d,requestBodyValues:f,statusCode:c.status,responseHeaders:x,responseBody:m,isRetryable:i?.(c)})}}},Ji=t=>async({response:r})=>{const i=ao(r);if(r.body==null)throw new Bp({});return{responseHeaders:i,value:fg({stream:r.body,schema:t})}},mr=t=>async({response:r,url:i,requestBodyValues:c})=>{const d=await wu({response:r,url:i}),f=await gu({text:d,schema:t}),m=ao(r);if(!f.success)throw new Kt({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:m,responseBody:d,url:i,requestBodyValues:c});return{responseHeaders:m,value:f.value,rawValue:f.rawValue}},xg=()=>async({response:t,url:r,requestBodyValues:i})=>{const c=ao(t);if(!t.body)throw new Kt({message:"Response body is empty",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0});try{const d=await t.arrayBuffer();return{responseHeaders:c,value:new Uint8Array(d)}}catch(d){throw new Kt({message:"Failed to read response as array buffer",url:r,requestBodyValues:i,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:d})}};function yg(t){return t?.replace(/\/$/,"")}var Qi=N({error:N({message:w(),type:w().nullish(),param:xr().nullish(),code:st([w(),j()]).nullish()})}),En=gg({errorSchema:Qi,errorToMessage:t=>t.error.message});function _u(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),i=t.startsWith("gpt-4")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")&&!t.startsWith("gpt-5.4-nano")||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"),d=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2")||t.startsWith("gpt-5.3")||t.startsWith("gpt-5.4")||t.startsWith("gpt-5.5")||t.startsWith("gpt-5.6");return{supportsFlexProcessing:r,supportsPriorityProcessing:i,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:d}}async function es({stream:t,getError:r,isOutputChunk:i,url:c,requestBodyValues:d,responseHeaders:f}){const[m,x]=t.tee(),v=m.getReader();try{for(;;){const g=await v.read();if(g.done)return x;const E=g.value;if(!E.success)return x;const A=r(E.value);if(A!=null)throw x.cancel().catch(()=>{}),wg({frame:A,url:c,requestBodyValues:d,responseHeaders:f});if(i(E.value))return x}}finally{v.cancel().catch(()=>{}),v.releaseLock()}}function wg({frame:t,url:r,requestBodyValues:i,responseHeaders:c}){var d;const f=_g(t);return new Kt({message:(d=f?.message)!=null?d:"OpenAI stream failed before any output was generated",url:r,requestBodyValues:i,statusCode:f==null?500:vg(f),responseHeaders:c,responseBody:JSON.stringify(t),data:t})}function _g(t){var r;const i=jr(t);if(i==null)return;if(i.type==="response.failed"){const d=jr(i.response),f=jr(d?.error);return typeof f?.message=="string"?{message:f.message,code:Oa(f.code),type:"response.failed",frame:t}:void 0}const c=(r=jr(i.error))!=null?r:i;return typeof c.message=="string"&&(jr(i.error)!=null||typeof c.type=="string"||"code"in c||"param"in c)?{message:c.message,code:Oa(c.code),type:typeof c.type=="string"?c.type:void 0,frame:t}:void 0}function vg(t){if(typeof t.code=="number"&&ka(t.code))return t.code;if(typeof t.code=="string"&&/^\d{3}$/.test(t.code)){const i=Number(t.code);if(ka(i))return i}const r=[t.code,t.type].filter(i=>typeof i=="string"||typeof i=="number").join(" ").toLowerCase();return["insufficient_quota","rate_limit"].some(i=>r.includes(i))?429:r.includes("authentication")?401:r.includes("permission")?403:r.includes("not_found")?404:["invalid","bad_request","context_length"].some(i=>r.includes(i))?400:r.includes("overload")?503:r.includes("timeout")?504:500}function jr(t){return typeof t=="object"&&t!=null?t:void 0}function Oa(t){return typeof t=="string"||typeof t=="number"?t:void 0}function ka(t){return Number.isInteger(t)&&t>=400&&t<=599}function Ra(t){var r,i,c,d,f,m,x,v;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 g=(r=t.prompt_tokens)!=null?r:0,E=(i=t.completion_tokens)!=null?i:0,A=(d=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?d:0,D=(m=(f=t.prompt_tokens_details)==null?void 0:f.cache_write_tokens)!=null?m:void 0,T=(v=(x=t.completion_tokens_details)==null?void 0:x.reasoning_tokens)!=null?v:0;return{inputTokens:{total:g,noCache:g-A-(D??0),cacheRead:A,cacheWrite:D},outputTokens:{total:E,text:E-T,reasoning:T},raw:t}}function Cg(t){return JSON.stringify(t===void 0?{}:t)}function Un(t){var r;return(r=t?.openai)==null?void 0:r.promptCacheBreakpoint}function bg({prompt:t,systemMessageMode:r="system"}){var i,c;const d=[],f=[];for(const{role:m,content:x,providerOptions:v}of t)switch(m){case"system":{switch(r){case"system":{const g=Un(v);d.push({role:"system",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"developer":{const g=Un(v);d.push({role:"developer",content:g==null?x:[{type:"text",text:x,prompt_cache_breakpoint:g}]});break}case"remove":{f.push({type:"other",message:"system messages are removed for this model"});break}default:{const g=r;throw new Error(`Unsupported system message mode: ${g}`)}}break}case"user":{if(x.length===1&&x[0].type==="text"&&Un(x[0].providerOptions)==null){d.push({role:"user",content:x[0].text});break}d.push({role:"user",content:x.map((g,E)=>{var A,D,T;switch(g.type){case"text":{const S=Un(g.providerOptions);return{type:"text",text:g.text,...S!=null&&{prompt_cache_breakpoint:S}}}case"file":{const S=Un(g.providerOptions);if(g.mediaType.startsWith("image/")){const P=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${P};base64,${kr(g.data)}`,detail:(D=(A=g.providerOptions)==null?void 0:A.openai)==null?void 0:D.imageDetail},...S!=null&&{prompt_cache_breakpoint:S}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new Mn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:kr(g.data),format:"wav"},...S!=null&&{prompt_cache_breakpoint:S}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:kr(g.data),format:"mp3"},...S!=null&&{prompt_cache_breakpoint:S}};default:throw new Mn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new Mn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(T=g.filename)!=null?T:`part-${E}.pdf`,file_data:`data:application/pdf;base64,${kr(g.data)}`},...S!=null&&{prompt_cache_breakpoint:S}}}else throw new Mn({functionality:`file part media type ${g.mediaType}`})}}})});break}case"assistant":{let g="";const E=[];let A=!1;const D=[];for(const T of x)switch(T.type){case"text":{const S=Un(T.providerOptions);g+=T.text,E.push({type:"text",text:T.text,...S!=null&&{prompt_cache_breakpoint:S}}),A||(A=S!=null);break}case"tool-call":{D.push({id:T.toolCallId,type:"function",function:{name:T.toolName,arguments:Cg(T.input)}});break}}d.push({role:"assistant",content:A?E:D.length>0?g||null:g,tool_calls:D.length>0?D:void 0});break}case"tool":{for(const g of x){if(g.type==="tool-approval-response")continue;const E=g.output,A=(i=E.type==="content"?E.value.map(T=>Un(T.providerOptions)).find(T=>T!=null):Un(E.providerOptions))!=null?i:Un(g.providerOptions);let D;switch(E.type){case"text":case"error-text":D=E.value;break;case"execution-denied":D=(c=E.reason)!=null?c:"Tool call execution denied.";break;case"content":case"json":case"error-json":D=JSON.stringify(E.value);break}d.push({role:"tool",tool_call_id:g.toolCallId,content:A==null?D:[{type:"text",text:D,prompt_cache_breakpoint:A}]})}break}default:{const g=m;throw new Error(`Unsupported role: ${g}`)}}return{messages:d,warnings:f}}function mi({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i?new Date(i*1e3):void 0}}function Ma(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 Ag=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({message:N({role:Y("assistant").nullish(),content:w().nullish(),tool_calls:ue(N({id:w().nullish(),type:Y("function"),function:N({name:w(),arguments:w()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),Eg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({delta:N({role:Ae(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(N({index:j(),id:w().nullish(),type:Y("function").nullish(),function:N({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(N({type:Y("url_citation"),url_citation:N({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:N({content:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:N({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish()}).nullish(),completion_tokens_details:N({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Qi]))),Ig=Fe(()=>Le(N({logitBias:wt(qh(),j()).optional(),logprobs:st([Mt(),j()]).optional(),parallelToolCalls:Mt().optional(),user:w().optional(),reasoningEffort:Ae(["none","minimal","low","medium","high","xhigh","max"]).optional(),maxCompletionTokens:j().optional(),store:Mt().optional(),metadata:wt(w().max(64),w().max(512)).optional(),prediction:wt(w(),xr()).optional(),serviceTier:Ae(["auto","flex","priority","default"]).optional(),strictJsonSchema:Mt().optional(),textVerbosity:Ae(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional()})));function Sg({tools:t,toolChoice:r}){t=t?.length?t:void 0;const i=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:i};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:i.push({type:"unsupported",feature:`tool type: ${f.type}`});break}if(r==null)return{tools:c,toolChoice:void 0,toolWarnings:i};const d=r.type;switch(d){case"auto":case"none":case"required":return{tools:c,toolChoice:d,toolWarnings:i};case"tool":return{tools:c,toolChoice:{type:"function",function:{name:r.toolName}},toolWarnings:i};default:{const f=d;throw new Mn({functionality:`tool choice type: ${f}`})}}}var Tg=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:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,seed:g,tools:E,toolChoice:A,providerOptions:D}){var T,S,P,M,ee;const $=[],F=(T=await An({provider:"openai",providerOptions:D,schema:Ig}))!=null?T:{},re=_u(this.modelId),Z=(S=F.forceReasoning)!=null?S:re.isReasoningModel;d!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:B,warnings:L}=bg({prompt:t,systemMessageMode:(P=F.systemMessageMode)!=null?P:Z?"developer":re.systemMessageMode});$.push(...L);const W=(M=F.strictJsonSchema)!=null?M:!0,z={model:this.modelId,logit_bias:F.logitBias,logprobs:F.logprobs===!0||typeof F.logprobs=="number"?!0:void 0,top_logprobs:typeof F.logprobs=="number"?F.logprobs:typeof F.logprobs=="boolean"&&F.logprobs?0:void 0,user:F.user,parallel_tool_calls:F.parallelToolCalls,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:W,name:(ee=v.name)!=null?ee:"response",description:v.description}}:{type:"json_object"}:void 0,stop:x,seed:g,verbosity:F.textVerbosity,max_completion_tokens:F.maxCompletionTokens,store:F.store,metadata:F.metadata,prediction:F.prediction,reasoning_effort:F.reasoningEffort,service_tier:F.serviceTier,prompt_cache_key:F.promptCacheKey,prompt_cache_options:F.promptCacheOptions,prompt_cache_retention:F.promptCacheRetention,safety_identifier:F.safetyIdentifier,messages:B};Z?((F.reasoningEffort!=="none"||!re.supportsNonReasoningParameters)&&(z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),z.top_p!=null&&(z.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),z.logprobs!=null&&(z.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),z.frequency_penalty!=null&&(z.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),z.presence_penalty!=null&&(z.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),z.logit_bias!=null&&(z.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),z.top_logprobs!=null&&(z.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),z.max_tokens!=null&&(z.max_completion_tokens==null&&(z.max_completion_tokens=z.max_tokens),z.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&z.temperature!=null&&(z.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),F.serviceTier==="flex"&&!re.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),z.service_tier=void 0),F.serviceTier==="priority"&&!re.supportsPriorityProcessing&&($.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"}),z.service_tier=void 0);const{tools:we,toolChoice:G,toolWarnings:me}=Sg({tools:E,toolChoice:A});return{args:{...z,tools:we,tool_choice:G},warnings:[...$,...me]}}async doGenerate(t){var r,i,c,d,f,m,x;const{args:v,warnings:g}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:D}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:v,failedResponseHandler:En,successfulResponseHandler:mr(Ag),abortSignal:t.abortSignal,fetch:this.config.fetch}),T=A.choices[0],S=[],P=T.message.content;P!=null&&P.length>0&&S.push({type:"text",text:P});for(const $ of(r=T.message.tool_calls)!=null?r:[])S.push({type:"tool-call",toolCallId:(i=$.id)!=null?i:rn(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=T.message.annotations)!=null?c:[])S.push({type:"source",sourceType:"url",id:rn(),url:$.url_citation.url,title:$.url_citation.title});const M=(d=A.usage)==null?void 0:d.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const ee={openai:{}};return M?.accepted_prediction_tokens!=null&&(ee.openai.acceptedPredictionTokens=M?.accepted_prediction_tokens),M?.rejected_prediction_tokens!=null&&(ee.openai.rejectedPredictionTokens=M?.rejected_prediction_tokens),((m=T.logprobs)==null?void 0:m.content)!=null&&(ee.openai.logprobs=T.logprobs.content),{content:S,finishReason:{unified:Ma(T.finish_reason),raw:(x=T.finish_reason)!=null?x:void 0},usage:Ra(A.usage),request:{body:v},response:{...mi(A),headers:E,body:D},warnings:g,providerMetadata:ee}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/chat/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Eg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:P=>"error"in P?P.error:void 0,isOutputChunk:Ng,url:d,requestBodyValues:c,responseHeaders:f}),v=[];let g={unified:"other",raw:void 0},E,A=!1,D=!1;const T={openai:{}};return{stream:x.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:i})},transform(P,M){var ee,$,F,re,Z,B,L,W,z,we,G,me,fe;if(t.includeRawChunks&&M.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:P.error});return}const te=P.value;if("error"in te){g={unified:"error",raw:void 0},M.enqueue({type:"error",error:te.error});return}if(!A){const le=mi(te);Object.values(le).some(Boolean)&&(A=!0,M.enqueue({type:"response-metadata",...mi(te)}))}te.usage!=null&&(E=te.usage,((ee=te.usage.completion_tokens_details)==null?void 0:ee.accepted_prediction_tokens)!=null&&(T.openai.acceptedPredictionTokens=($=te.usage.completion_tokens_details)==null?void 0:$.accepted_prediction_tokens),((F=te.usage.completion_tokens_details)==null?void 0:F.rejected_prediction_tokens)!=null&&(T.openai.rejectedPredictionTokens=(re=te.usage.completion_tokens_details)==null?void 0:re.rejected_prediction_tokens));const q=te.choices[0];if(q?.finish_reason!=null&&(g={unified:Ma(q.finish_reason),raw:q.finish_reason}),((Z=q?.logprobs)==null?void 0:Z.content)!=null&&(T.openai.logprobs=q.logprobs.content),q?.delta==null)return;const ke=q.delta;if(ke.content!=null&&(D||(M.enqueue({type:"text-start",id:"0"}),D=!0),M.enqueue({type:"text-delta",id:"0",delta:ke.content})),ke.tool_calls!=null)for(const le of ke.tool_calls){const Te=le.index;if(v[Te]==null){if(le.type!=null&&le.type!=="function")throw new fi({data:le,message:"Expected 'function' type."});if(le.id==null)throw new fi({data:le,message:"Expected 'id' to be a string."});if(((B=le.function)==null?void 0:B.name)==null)throw new fi({data:le,message:"Expected 'function.name' to be a string."});M.enqueue({type:"tool-input-start",id:le.id,toolName:le.function.name}),v[Te]={id:le.id,type:"function",function:{name:le.function.name,arguments:(L=le.function.arguments)!=null?L:""},hasFinished:!1};const xe=v[Te];((W=xe.function)==null?void 0:W.name)!=null&&((z=xe.function)==null?void 0:z.arguments)!=null&&xe.function.arguments.length>0&&M.enqueue({type:"tool-input-delta",id:xe.id,delta:xe.function.arguments});continue}const Je=v[Te];Je.hasFinished||(((we=le.function)==null?void 0:we.arguments)!=null&&(Je.function.arguments+=(me=(G=le.function)==null?void 0:G.arguments)!=null?me:""),M.enqueue({type:"tool-input-delta",id:Je.id,delta:(fe=le.function.arguments)!=null?fe:""}))}if(ke.annotations!=null)for(const le of ke.annotations)M.enqueue({type:"source",sourceType:"url",id:rn(),url:le.url_citation.url,title:le.url_citation.title})},flush(P){var M;D&&P.enqueue({type:"text-end",id:"0"});for(const ee of v)ee.hasFinished||(P.enqueue({type:"tool-input-end",id:ee.id}),P.enqueue({type:"tool-call",toolCallId:(M=ee.id)!=null?M:rn(),toolName:ee.function.name,input:ee.function.arguments}),ee.hasFinished=!0);P.enqueue({type:"finish",finishReason:g,usage:Ra(E),...T!=null?{providerMetadata:T}:{}})}})),request:{body:c},response:{headers:f}}}};function Ng(t){return"error"in t?!1:t.choices.some(r=>{const i=r.delta;return i?.content!=null&&i.content.length>0||i?.tool_calls!=null&&i.tool_calls.length>0||i?.annotations!=null&&i.annotations.length>0})}function Da(t){var r,i,c,d;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=(i=t.completion_tokens)!=null?i:0;return{inputTokens:{total:(c=t.prompt_tokens)!=null?c:void 0,noCache:f,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:(d=t.completion_tokens)!=null?d:void 0,text:m,reasoning:void 0},raw:t}}function Og({prompt:t,user:r="user",assistant:i="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
46
46
 
47
- `,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Mp({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const m=f.map(g=>{switch(g.type){case"text":return g.text}}).filter(Boolean).join("");c+=`${r}:
47
+ `,t=t.slice(1));for(const{role:d,content:f}of t)switch(d){case"system":throw new Up({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}:
48
48
  ${m}
49
49
 
50
- `;break}case"assistant":{const m=f.map(g=>{switch(g.type){case"text":return g.text;case"tool-call":throw new Bn({functionality:"tool-call messages"})}}).join("");c+=`${o}:
50
+ `;break}case"assistant":{const m=f.map(x=>{switch(x.type){case"text":return x.text;case"tool-call":throw new Mn({functionality:"tool-call messages"})}}).join("");c+=`${i}:
51
51
  ${m}
52
52
 
53
- `;break}case"tool":throw new Bn({functionality:"tool messages"});default:{const m=u;throw new Error(`Unsupported role: ${m}`)}}return c+=`${o}:
53
+ `;break}case"tool":throw new Mn({functionality:"tool messages"});default:{const m=d;throw new Error(`Unsupported role: ${m}`)}}return c+=`${i}:
54
54
  `,{prompt:c,stopSequences:[`
55
- ${r}:`]}}function ka({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"other"}}var vg=Ue(()=>Fe(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({text:w(),finish_reason:w(),logprobs:N({tokens:le(w()),token_logprobs:le(j()),top_logprobs:le(yt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Cg=Ue(()=>Fe(it([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:le(N({text:w(),finish_reason:w().nullish(),index:j(),logprobs:N({tokens:le(w()),token_logprobs:le(j()),top_logprobs:le(yt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Ko]))),Ma=Ue(()=>Fe(N({echo:Dt().optional(),logitBias:yt(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:it([Dt(),j()]).optional()}))),bg=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:g,responseFormat:v,tools:x,toolChoice:E,seed:A,providerOptions:M}){const T=[],S={...await In({provider:"openai",providerOptions:M,schema:Ma}),...await In({provider:this.providerOptionsName,providerOptions:M,schema:Ma})};u!=null&&T.push({type:"unsupported",feature:"topK"}),x?.length&&T.push({type:"unsupported",feature:"tools"}),E!=null&&T.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&T.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:B,stopSequences:D}=_g({prompt:t}),ne=[...D??[],...g??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,logprobs:S?.logprobs===!0?0:S?.logprobs===!1?void 0:S?.logprobs,suffix:S.suffix,user:S.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:B,stop:ne.length>0?ne:void 0},warnings:T}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:m}=await jn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:o,failedResponseHandler:Sn,successfulResponseHandler:mr(vg),abortSignal:t.abortSignal,fetch:this.config.fetch}),g=f.choices[0],v={openai:{}};return g.logprobs!=null&&(v.openai.logprobs=g.logprobs),{content:[{type:"text",text:g.text}],usage:Oa(f.usage),finishReason:{unified:Ra(g.finish_reason),raw:(r=g.finish_reason)!=null?r:void 0},request:{body:o},response:{...ka(f),headers:u,body:m},providerMetadata:v,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 jn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:Sn,successfulResponseHandler:Yo(Cg),abortSignal:t.abortSignal,fetch:this.config.fetch});let m={unified:"other",raw:void 0};const g={openai:{}};let v,x=!0;return{stream:f.pipeThrough(new TransformStream({start(E){E.enqueue({type:"stream-start",warnings:o})},transform(E,A){if(t.includeRawChunks&&A.enqueue({type:"raw",rawValue:E.rawValue}),!E.success){m={unified:"error",raw:void 0},A.enqueue({type:"error",error:E.error});return}const M=E.value;if("error"in M){m={unified:"error",raw:void 0},A.enqueue({type:"error",error:M.error});return}x&&(x=!1,A.enqueue({type:"response-metadata",...ka(M)}),A.enqueue({type:"text-start",id:"0"})),M.usage!=null&&(v=M.usage);const T=M.choices[0];T?.finish_reason!=null&&(m={unified:Ra(T.finish_reason),raw:T.finish_reason}),T?.logprobs!=null&&(g.openai.logprobs=T.logprobs),T?.text!=null&&T.text.length>0&&A.enqueue({type:"text-delta",id:"0",delta:T.text})},flush(E){x||E.enqueue({type:"text-end",id:"0"}),E.enqueue({type:"finish",finishReason:m,providerMetadata:g,usage:Oa(v)})}})),request:{body:c},response:{headers:u}}}},Ag=Ue(()=>Fe(N({dimensions:j().optional(),user:w().optional()}))),Eg=Ue(()=>Fe(N({data:le(N({embedding:le(j())})),usage:N({prompt_tokens:j()}).nullish()}))),Ig=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 Fp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await In({provider:"openai",providerOptions:c,schema:Ag}))!=null?u:{},{responseHeaders:m,value:g,rawValue:v}=await jn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:En(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:Sn,successfulResponseHandler:mr(Eg),abortSignal:o,fetch:this.config.fetch});return{warnings:[],embeddings:g.data.map(x=>x.embedding),usage:g.usage?{tokens:g.usage.prompt_tokens}:void 0,response:{headers:m,body:v}}}},Da=Ue(()=>Fe(N({created:j().nullish(),data:le(N({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:N({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:N({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),Sg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},Tg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function Ng(t){return Tg.some(r=>t.startsWith(r))}var mu=N({quality:Ee(["standard","hd","low","medium","high","auto"]).optional(),background:Ee(["transparent","opaque","auto"]).optional(),outputFormat:Ee(["png","jpeg","webp"]).optional(),outputCompression:j().int().min(0).max(100).optional(),user:w().optional()}),Og=Ue(()=>Fe(mu.extend({style:Ee(["vivid","natural"]).optional(),moderation:Ee(["auto","low"]).optional()}))),kg=Ue(()=>Fe(mu.extend({inputFidelity:Ee(["high","low"]).optional()}))),Rg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Sg[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:g,headers:v,abortSignal:x}){var E,A,M,T,S,B,D,ne,z,Z,re;const $=[];f!=null&&$.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&$.push({type:"unsupported",feature:"seed"});const P=(M=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?M:new Date;if(r!=null){const ee=(T=await In({provider:"openai",providerOptions:g,schema:kg}))!=null?T:{},{value:Y,responseHeaders:ue}=await du({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:En(this.config.headers(),v),formData:Wp({model:this.modelId,prompt:t,image:await Promise.all(r.map(ge=>ge.type==="file"?new Blob([ge.data instanceof Uint8Array?new Blob([ge.data],{type:ge.mediaType}):new Blob([Ho(ge.data)],{type:ge.mediaType})],{type:ge.mediaType}):ru(ge.url))),mask:o!=null?await Mg(o):void 0,n:c,size:u,quality:ee.quality,background:ee.background,output_format:ee.outputFormat,output_compression:ee.outputCompression,input_fidelity:ee.inputFidelity,user:ee.user}),failedResponseHandler:Sn,successfulResponseHandler:mr(Da),abortSignal:x,fetch:this.config.fetch});return{images:Y.data.map(ge=>ge.b64_json),warnings:$,usage:Y.usage!=null?{inputTokens:(S=Y.usage.input_tokens)!=null?S:void 0,outputTokens:(B=Y.usage.output_tokens)!=null?B:void 0,totalTokens:(D=Y.usage.total_tokens)!=null?D:void 0}:void 0,response:{timestamp:P,modelId:this.modelId,headers:ue},providerMetadata:{openai:{images:Y.data.map((ge,Te)=>{var H,ye,he,Se,We,me;return{...ge.revised_prompt?{revisedPrompt:ge.revised_prompt}:{},created:(H=Y.created)!=null?H:void 0,size:(ye=Y.size)!=null?ye:void 0,quality:(he=Y.quality)!=null?he:void 0,background:(Se=Y.background)!=null?Se:void 0,outputFormat:(We=Y.output_format)!=null?We:void 0,...Pa((me=Y.usage)==null?void 0:me.input_tokens_details,Te,Y.data.length)}})}}}}const L=(ne=await In({provider:"openai",providerOptions:g,schema:Og}))!=null?ne:{},{value:G,responseHeaders:U}=await jn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:En(this.config.headers(),v),body:{model:this.modelId,prompt:t,n:c,size:u,quality:L.quality,style:L.style,background:L.background,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression,user:L.user,...Ng(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:Sn,successfulResponseHandler:mr(Da),abortSignal:x,fetch:this.config.fetch});return{images:G.data.map(ee=>ee.b64_json),warnings:$,usage:G.usage!=null?{inputTokens:(z=G.usage.input_tokens)!=null?z:void 0,outputTokens:(Z=G.usage.output_tokens)!=null?Z:void 0,totalTokens:(re=G.usage.total_tokens)!=null?re:void 0}:void 0,response:{timestamp:P,modelId:this.modelId,headers:U},providerMetadata:{openai:{images:G.data.map((ee,Y)=>{var ue,ge,Te,H,ye,he;return{...ee.revised_prompt?{revisedPrompt:ee.revised_prompt}:{},created:(ue=G.created)!=null?ue:void 0,size:(ge=G.size)!=null?ge:void 0,quality:(Te=G.quality)!=null?Te:void 0,background:(H=G.background)!=null?H:void 0,outputFormat:(ye=G.output_format)!=null?ye:void 0,...Pa((he=G.usage)==null?void 0:he.input_tokens_details,Y,G.data.length)}})}}}}};function Pa(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 Mg(t){if(!t)return;if(t.type==="url")return ru(t.url);const r=t.data instanceof Uint8Array?t.data:Ho(t.data);return new Blob([r],{type:t.mediaType})}var gu=Ue(()=>Fe(N({callId:w(),operation:pt("type",[N({type:q("create_file"),path:w(),diff:w()}),N({type:q("delete_file"),path:w()}),N({type:q("update_file"),path:w(),diff:w()})])}))),xu=Ue(()=>Fe(N({status:Ee(["completed","failed"]),output:w().optional()}))),Dg=Ln({id:"openai.apply_patch",inputSchema:gu,outputSchema:xu}),Pg=Dg,Bg=Ue(()=>Fe(N({code:w().nullish(),containerId:w()}))),Lg=Ue(()=>Fe(N({outputs:le(pt("type",[N({type:q("logs"),logs:w()}),N({type:q("image"),url:w()})])).nullish()}))),Fg=Ue(()=>Fe(N({container:it([w(),N({fileIds:le(w()).optional()})]).optional()}))),Ug=Ln({id:"openai.code_interpreter",inputSchema:Bg,outputSchema:Lg}),zg=(t={})=>Ug(t),Vg=Ue(()=>Fe(N({name:w(),description:w().optional(),format:it([N({type:q("grammar"),syntax:Ee(["regex","lark"]),definition:w()}),N({type:q("text")})]).optional()}))),Zg=Ue(()=>Fe(w())),$g=lg({id:"openai.custom",inputSchema:Zg}),jg=t=>$g(t),yu=N({key:w(),type:Ee(["eq","ne","gt","gte","lt","lte","in","nin"]),value:it([w(),j(),Dt(),le(w())])}),wu=N({type:Ee(["and","or"]),filters:le(it([yu,$o(()=>wu)]))}),Hg=Ue(()=>Fe(N({vectorStoreIds:le(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:it([yu,wu]).optional()}))),Wg=Ue(()=>Fe(N({queries:le(w()),results:le(N({attributes:yt(w(),An()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),Gg=Ln({id:"openai.file_search",inputSchema:N({}),outputSchema:Wg}),Xg=Ue(()=>Fe(N({background:Ee(["auto","opaque","transparent"]).optional(),inputFidelity:Ee(["low","high"]).optional(),inputImageMask:N({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Ee(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ee(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ee(["auto","low","medium","high"]).optional(),size:Ee(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),qg=Ue(()=>Fe(N({}))),Yg=Ue(()=>Fe(N({result:w()}))),Kg=Ln({id:"openai.image_generation",inputSchema:qg,outputSchema:Yg}),Jg=(t={})=>Kg(t),_u=Ue(()=>Fe(N({action:N({type:q("exec"),command:le(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:yt(w(),w()).optional()})}))),vu=Ue(()=>Fe(N({output:w()}))),Qg=Ln({id:"openai.local_shell",inputSchema:_u,outputSchema:vu}),Cu=Ue(()=>Fe(N({action:N({commands:le(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),To=Ue(()=>Fe(N({output:le(N({stdout:w(),stderr:w(),outcome:pt("type",[N({type:q("timeout")}),N({type:q("exit"),exitCode:j()})])}))}))),e2=le(pt("type",[N({type:q("skillReference"),skillId:w(),version:w().optional()}),N({type:q("inline"),name:w(),description:w(),source:N({type:q("base64"),mediaType:q("application/zip"),data:w()})})])).optional(),t2=Ue(()=>Fe(N({environment:it([N({type:q("containerAuto"),fileIds:le(w()).optional(),memoryLimit:Ee(["1g","4g","16g","64g"]).optional(),networkPolicy:pt("type",[N({type:q("disabled")}),N({type:q("allowlist"),allowedDomains:le(w()),domainSecrets:le(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:e2}),N({type:q("containerReference"),containerId:w()}),N({type:q("local").optional(),skills:le(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),n2=Ln({id:"openai.shell",inputSchema:Cu,outputSchema:To}),r2=Ue(()=>Fe(N({execution:Ee(["server","client"]).optional(),description:w().optional(),parameters:yt(w(),An()).optional()}))),No=Ue(()=>Fe(N({arguments:An().optional(),call_id:w().nullish()}))),Oo=Ue(()=>Fe(N({tools:le(yt(w(),An()))}))),i2=Ln({id:"openai.tool_search",inputSchema:No,outputSchema:Oo}),o2=(t={})=>i2(t),s2=Ue(()=>Fe(N({externalWebAccess:Dt().optional(),filters:N({allowedDomains:le(w()).optional()}).optional(),searchContextSize:Ee(["low","medium","high"]).optional(),userLocation:N({type:q("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),a2=Ue(()=>Fe(N({}))),l2=Ue(()=>Fe(N({action:pt("type",[N({type:q("search"),query:w().optional(),queries:le(w()).optional()}),N({type:q("openPage"),url:w().nullish()}),N({type:q("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:le(pt("type",[N({type:q("url"),url:w()}),N({type:q("api"),name:w()})])).optional()}))),c2=Ln({id:"openai.web_search",inputSchema:a2,outputSchema:l2}),u2=(t={})=>c2(t),d2=Ue(()=>Fe(N({searchContextSize:Ee(["low","medium","high"]).optional(),userLocation:N({type:q("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),f2=Ue(()=>Fe(N({}))),h2=Ue(()=>Fe(N({action:pt("type",[N({type:q("search"),query:w().optional()}),N({type:q("openPage"),url:w().nullish()}),N({type:q("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),p2=Ln({id:"openai.web_search_preview",inputSchema:f2,outputSchema:h2}),ko=$o(()=>it([w(),j(),Dt(),yc(),le(ko),yt(w(),ko)])),m2=Ue(()=>Fe(N({serverLabel:w(),allowedTools:it([le(w()),N({readOnly:Dt().optional(),toolNames:le(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:yt(w(),w()).optional(),requireApproval:it([Ee(["always","never"]),N({never:N({toolNames:le(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."))),g2=Ue(()=>Fe(N({}))),x2=Ue(()=>Fe(N({type:q("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:it([w(),ko]).optional()}))),y2=Ln({id:"openai.mcp",inputSchema:g2,outputSchema:x2}),w2=t=>y2(t),_2={applyPatch:Pg,customTool:jg,codeInterpreter:zg,fileSearch:Gg,imageGeneration:Jg,localShell:Qg,shell:n2,webSearchPreview:p2,webSearch:u2,mcp:w2,toolSearch:o2};function Ba(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,g=(o=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?o:0,v=(u=(c=t.output_tokens_details)==null?void 0:c.reasoning_tokens)!=null?u:0;return{inputTokens:{total:f,noCache:f-g,cacheRead:g,cacheWrite:void 0},outputTokens:{total:m,text:m-v,reasoning:v},raw:t}}function v2(t){return JSON.stringify(t===void 0?{}:t)}function La(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function C2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,passThroughUnsupportedFiles:f=!1,store:m,hasConversation:g=!1,hasPreviousResponseId:v=!1,hasLocalShellTool:x=!1,hasShellTool:E=!1,hasApplyPatchTool:A=!1,customProviderToolNames:M}){var T,S,B,D,ne,z,Z,re,$,P,L,G,U,ee,Y,ue,ge,Te,H,ye,he,Se,We;let me=[];const Oe=[],Me=new Set;for(const{role:Je,content:be}of t)switch(Je){case"system":{switch(o){case"system":{me.push({role:"system",content:be});break}case"developer":{me.push({role:"developer",content:be});break}case"remove":{Oe.push({type:"other",message:"system messages are removed for this model"});break}default:{const ke=o;throw new Error(`Unsupported system message mode: ${ke}`)}}break}case"user":{me.push({role:"user",content:be.map((ke,te)=>{var Ie,Ae,fe;switch(ke.type){case"text":return{type:"input_text",text:ke.text};case"file":{const K=ke.mediaType==="image/*"?"image/jpeg":ke.mediaType;if(K.startsWith("image/"))return{type:"input_image",...ke.data instanceof URL?{image_url:ke.data.toString()}:typeof ke.data=="string"&&La(ke.data,u)?{file_id:ke.data}:{image_url:`data:${K};base64,${Nr(ke.data)}`},detail:(Ae=(Ie=ke.providerOptions)==null?void 0:Ie[c])==null?void 0:Ae.imageDetail};if(ke.data instanceof URL)return{type:"input_file",file_url:ke.data.toString()};if(K!=="application/pdf"&&!f)throw new Bn({functionality:`file part media type ${K}`});return{type:"input_file",...typeof ke.data=="string"&&La(ke.data,u)?{file_id:ke.data}:{filename:(fe=ke.filename)!=null?fe:K==="application/pdf"?`part-${te}.pdf`:`part-${te}`,file_data:`data:${K};base64,${Nr(ke.data)}`}}}}})});break}case"assistant":{const ke={};for(const te of be)switch(te.type){case"text":{const Ie=(T=te.providerOptions)==null?void 0:T[c],Ae=Ie?.itemId,fe=Ie?.phase;if(g&&Ae!=null)break;if(m&&Ae!=null){me.push({type:"item_reference",id:Ae});break}me.push({role:"assistant",content:[{type:"output_text",text:te.text}],id:Ae,...fe!=null&&{phase:fe}});break}case"tool-call":{const Ie=(z=(B=(S=te.providerOptions)==null?void 0:S[c])==null?void 0:B.itemId)!=null?z:(ne=(D=te.providerMetadata)==null?void 0:D[c])==null?void 0:ne.itemId,Ae=(L=(re=(Z=te.providerOptions)==null?void 0:Z[c])==null?void 0:re.namespace)!=null?L:(P=($=te.providerMetadata)==null?void 0:$[c])==null?void 0:P.namespace;if(g&&Ie!=null)break;const fe=r.toProviderToolName(te.toolName);if(fe==="tool_search"){if(m&&Ie!=null){me.push({type:"item_reference",id:Ie});break}const xe=typeof te.input=="string"?await cu({text:te.input,schema:No}):await Pt({value:te.input,schema:No}),et=xe.call_id!=null?"client":"server";me.push({type:"tool_search_call",id:Ie??te.toolCallId,execution:et,call_id:(G=xe.call_id)!=null?G:null,status:"completed",arguments:xe.arguments});break}if(te.providerExecuted){m&&Ie!=null&&me.push({type:"item_reference",id:Ie});break}if(v&&m&&Ie!=null)break;const K=x&&fe==="local_shell"||E&&fe==="shell"||A&&fe==="apply_patch"||((U=M?.has(fe))!=null?U:!1);if(m&&Ie!=null&&K){me.push({type:"item_reference",id:Ie});break}if(x&&fe==="local_shell"){const xe=await Pt({value:te.input,schema:_u});me.push({type:"local_shell_call",call_id:te.toolCallId,id:Ie,action:{type:"exec",command:xe.action.command,timeout_ms:xe.action.timeoutMs,user:xe.action.user,working_directory:xe.action.workingDirectory,env:xe.action.env}});break}if(E&&fe==="shell"){const xe=await Pt({value:te.input,schema:Cu});me.push({type:"shell_call",call_id:te.toolCallId,id:Ie,status:"completed",action:{commands:xe.action.commands,timeout_ms:xe.action.timeoutMs,max_output_length:xe.action.maxOutputLength}});break}if(A&&fe==="apply_patch"){const xe=await Pt({value:te.input,schema:gu});me.push({type:"apply_patch_call",call_id:xe.callId,id:Ie,status:"completed",operation:xe.operation});break}if(M?.has(fe)){me.push({type:"custom_tool_call",call_id:te.toolCallId,name:fe,input:typeof te.input=="string"?te.input:JSON.stringify(te.input),id:Ie});break}me.push({type:"function_call",call_id:te.toolCallId,name:fe,arguments:v2(te.input),...Ae!=null&&{namespace:Ae}});break}case"tool-result":{if(te.output.type==="execution-denied"||te.output.type==="json"&&typeof te.output.value=="object"&&te.output.value!=null&&"type"in te.output.value&&te.output.value.type==="execution-denied"||g)break;const Ie=r.toProviderToolName(te.toolName);if(Ie==="tool_search"){const Ae=(ue=(Y=(ee=te.providerOptions)==null?void 0:ee[c])==null?void 0:Y.itemId)!=null?ue:te.toolCallId;if(m)me.push({type:"item_reference",id:Ae});else if(te.output.type==="json"){const fe=await Pt({value:te.output.value,schema:Oo});me.push({type:"tool_search_output",id:Ae,execution:"server",call_id:null,status:"completed",tools:fe.tools})}break}if(E&&Ie==="shell"){if(te.output.type==="json"){const Ae=await Pt({value:te.output.value,schema:To});me.push({type:"shell_call_output",call_id:te.toolCallId,output:Ae.output.map(fe=>({stdout:fe.stdout,stderr:fe.stderr,outcome:fe.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:fe.outcome.exitCode}}))})}break}if(m){const Ae=(H=(Te=(ge=te.providerOptions)==null?void 0:ge[c])==null?void 0:Te.itemId)!=null?H:te.toolCallId;me.push({type:"item_reference",id:Ae})}else Oe.push({type:"other",message:`Results for OpenAI tool ${te.toolName} are not sent to the API when store is false`});break}case"reasoning":{const Ie=await In({provider:c,providerOptions:te.providerOptions,schema:b2}),Ae=Ie?.itemId;if((g||v)&&Ae!=null)break;if(Ae!=null){const fe=ke[Ae];if(m)fe===void 0&&(me.push({type:"item_reference",id:Ae}),ke[Ae]={type:"reasoning",id:Ae,summary:[]});else{const K=[];te.text.length>0?K.push({type:"summary_text",text:te.text}):fe!==void 0&&Oe.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(te)}.`}),fe===void 0?(ke[Ae]={type:"reasoning",id:Ae,encrypted_content:Ie?.reasoningEncryptedContent,summary:K},me.push(ke[Ae])):(fe.summary.push(...K),Ie?.reasoningEncryptedContent!=null&&(fe.encrypted_content=Ie.reasoningEncryptedContent))}}else{const fe=Ie?.reasoningEncryptedContent;if(fe!=null){const K=[];te.text.length>0&&K.push({type:"summary_text",text:te.text}),me.push({type:"reasoning",encrypted_content:fe,summary:K})}else Oe.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(te)}.`})}break}}break}case"tool":{for(const ke of be){if(ke.type==="tool-approval-response"){const fe=ke;if(Me.has(fe.approvalId))continue;Me.add(fe.approvalId),m&&me.push({type:"item_reference",id:fe.approvalId}),me.push({type:"mcp_approval_response",approval_request_id:fe.approvalId,approve:fe.approved});continue}const te=ke.output;if(te.type==="execution-denied"&&((he=(ye=te.providerOptions)==null?void 0:ye.openai)==null?void 0:he.approvalId))continue;const Ie=r.toProviderToolName(ke.toolName);if(Ie==="tool_search"&&te.type==="json"){const fe=await Pt({value:te.value,schema:Oo});me.push({type:"tool_search_output",execution:"client",call_id:ke.toolCallId,status:"completed",tools:fe.tools});continue}if(x&&Ie==="local_shell"&&te.type==="json"){const fe=await Pt({value:te.value,schema:vu});me.push({type:"local_shell_call_output",call_id:ke.toolCallId,output:fe.output});continue}if(E&&Ie==="shell"&&te.type==="json"){const fe=await Pt({value:te.value,schema:To});me.push({type:"shell_call_output",call_id:ke.toolCallId,output:fe.output.map(K=>({stdout:K.stdout,stderr:K.stderr,outcome:K.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:K.outcome.exitCode}}))});continue}if(A&&ke.toolName==="apply_patch"&&te.type==="json"){const fe=await Pt({value:te.value,schema:xu});me.push({type:"apply_patch_call_output",call_id:ke.toolCallId,status:fe.status,output:fe.output});continue}if(M?.has(Ie)){let fe;switch(te.type){case"text":case"error-text":fe=te.value;break;case"execution-denied":fe=(Se=te.reason)!=null?Se:"Tool execution denied.";break;case"json":case"error-json":fe=JSON.stringify(te.value);break;case"content":fe=te.value.map(K=>{var xe,et,we,kt,Bt;switch(K.type){case"text":return{type:"input_text",text:K.text};case"image-data":return{type:"input_image",image_url:`data:${K.mediaType};base64,${K.data}`,detail:(et=(xe=K.providerOptions)==null?void 0:xe[c])==null?void 0:et.imageDetail};case"image-url":return{type:"input_image",image_url:K.url,detail:(kt=(we=K.providerOptions)==null?void 0:we[c])==null?void 0:kt.imageDetail};case"file-data":return{type:"input_file",filename:(Bt=K.filename)!=null?Bt:"data",file_data:`data:${K.mediaType};base64,${K.data}`};case"file-url":return{type:"input_file",file_url:K.url};default:Oe.push({type:"other",message:`unsupported custom tool content part type: ${K.type}`});return}}).filter(ba);break;default:fe=""}me.push({type:"custom_tool_call_output",call_id:ke.toolCallId,output:fe});continue}let Ae;switch(te.type){case"text":case"error-text":Ae=te.value;break;case"execution-denied":Ae=(We=te.reason)!=null?We:"Tool execution denied.";break;case"json":case"error-json":Ae=JSON.stringify(te.value);break;case"content":Ae=te.value.map(fe=>{var K,xe,et,we,kt;switch(fe.type){case"text":return{type:"input_text",text:fe.text};case"image-data":return{type:"input_image",image_url:`data:${fe.mediaType};base64,${fe.data}`,detail:(xe=(K=fe.providerOptions)==null?void 0:K[c])==null?void 0:xe.imageDetail};case"image-url":return{type:"input_image",image_url:fe.url,detail:(we=(et=fe.providerOptions)==null?void 0:et[c])==null?void 0:we.imageDetail};case"file-data":return{type:"input_file",filename:(kt=fe.filename)!=null?kt:"data",file_data:`data:${fe.mediaType};base64,${fe.data}`};case"file-url":return{type:"input_file",file_url:fe.url};default:{Oe.push({type:"other",message:`unsupported tool content part type: ${fe.type}`});return}}}).filter(ba);break}me.push({type:"function_call_output",call_id:ke.toolCallId,output:Ae})}break}default:{const ke=Je;throw new Error(`Unsupported role: ${ke}`)}}return!m&&me.some(Je=>"type"in Je&&Je.type==="reasoning"&&Je.encrypted_content==null)&&(Oe.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),me=me.filter(Je=>!("type"in Je)||Je.type!=="reasoning"||Je.encrypted_content!=null)),{input:me,warnings:Oe}}var b2=N({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function ho({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 ei=$o(()=>it([w(),j(),Dt(),yc(),le(ei),yt(w(),ei.optional())])),A2=Ue(()=>Fe(it([N({type:q("response.output_text.delta"),item_id:w(),delta:w(),logprobs:le(N({token:w(),logprob:j(),top_logprobs:le(N({token:w(),logprob:j()}))})).nullish()}),N({type:Ee(["response.completed","response.incomplete"]),response:N({incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}),service_tier:w().nullish()})}),N({type:q("response.failed"),response:N({error:N({code:w().nullish(),message:w()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).nullish(),service_tier:w().nullish()})}),N({type:q("response.created"),response:N({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),N({type:q("response.output_item.added"),output_index:j(),item:pt("type",[N({type:q("message"),id:w(),phase:Ee(["commentary","final_answer"]).nullish()}),N({type:q("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:q("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),namespace:w().nullish()}),N({type:q("web_search_call"),id:w(),status:w()}),N({type:q("computer_call"),id:w(),status:w()}),N({type:q("file_search_call"),id:w()}),N({type:q("image_generation_call"),id:w()}),N({type:q("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:le(pt("type",[N({type:q("logs"),logs:w()}),N({type:q("image"),url:w()})])).nullable(),status:w()}),N({type:q("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),N({type:q("mcp_list_tools"),id:w()}),N({type:q("mcp_approval_request"),id:w()}),N({type:q("apply_patch_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed"]),operation:pt("type",[N({type:q("create_file"),path:w(),diff:w()}),N({type:q("delete_file"),path:w()}),N({type:q("update_file"),path:w(),diff:w()})])}),N({type:q("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),N({type:q("shell_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),action:N({commands:le(w())})}),N({type:q("shell_call_output"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),output:le(N({stdout:w(),stderr:w(),outcome:pt("type",[N({type:q("timeout")}),N({type:q("exit"),exit_code:j()})])}))}),N({type:q("tool_search_call"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),arguments:An()}),N({type:q("tool_search_output"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),tools:le(yt(w(),ei.optional()))})])}),N({type:q("response.output_item.done"),output_index:j(),item:pt("type",[N({type:q("message"),id:w(),phase:Ee(["commentary","final_answer"]).nullish()}),N({type:q("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:q("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:q("completed"),namespace:w().nullish()}),N({type:q("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:q("completed")}),N({type:q("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:le(pt("type",[N({type:q("logs"),logs:w()}),N({type:q("image"),url:w()})])).nullable()}),N({type:q("image_generation_call"),id:w(),result:w()}),N({type:q("web_search_call"),id:w(),status:w(),action:pt("type",[N({type:q("search"),query:w().nullish(),queries:le(w()).nullish(),sources:le(pt("type",[N({type:q("url"),url:w()}),N({type:q("api"),name:w()})])).nullish()}),N({type:q("open_page"),url:w().nullish()}),N({type:q("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:q("file_search_call"),id:w(),queries:le(w()),results:le(N({attributes:yt(w(),it([w(),j(),Dt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:q("local_shell_call"),id:w(),call_id:w(),action:N({type:q("exec"),command:le(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:yt(w(),w()).optional()})}),N({type:q("computer_call"),id:w(),status:q("completed")}),N({type:q("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:it([w(),N({type:w().optional(),code:it([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:q("mcp_list_tools"),id:w(),server_label:w(),tools:le(N({name:w(),description:w().optional(),input_schema:xr(),annotations:yt(w(),An()).optional()})),error:it([w(),N({type:w().optional(),code:it([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:q("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:q("apply_patch_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed"]),operation:pt("type",[N({type:q("create_file"),path:w(),diff:w()}),N({type:q("delete_file"),path:w()}),N({type:q("update_file"),path:w(),diff:w()})])}),N({type:q("shell_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),action:N({commands:le(w())})}),N({type:q("shell_call_output"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),output:le(N({stdout:w(),stderr:w(),outcome:pt("type",[N({type:q("timeout")}),N({type:q("exit"),exit_code:j()})])}))}),N({type:q("tool_search_call"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),arguments:An()}),N({type:q("tool_search_output"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),tools:le(yt(w(),ei.optional()))})])}),N({type:q("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:q("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:q("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),N({type:q("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:q("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),N({type:q("response.output_text.annotation.added"),annotation:pt("type",[N({type:q("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:q("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:q("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:q("file_path"),file_id:w(),index:j()})])}),N({type:q("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),N({type:q("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),N({type:q("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),N({type:q("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),N({type:q("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),N({type:q("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),E2=Ue(()=>Fe(N({id:w().optional(),created_at:j().optional(),error:N({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:le(pt("type",[N({type:q("message"),role:q("assistant"),id:w(),phase:Ee(["commentary","final_answer"]).nullish(),content:le(N({type:q("output_text"),text:w(),logprobs:le(N({token:w(),logprob:j(),top_logprobs:le(N({token:w(),logprob:j()}))})).nullish(),annotations:le(pt("type",[N({type:q("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:q("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:q("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:q("file_path"),file_id:w(),index:j()})]))}))}),N({type:q("web_search_call"),id:w(),status:w(),action:pt("type",[N({type:q("search"),query:w().nullish(),queries:le(w()).nullish(),sources:le(pt("type",[N({type:q("url"),url:w()}),N({type:q("api"),name:w()})])).nullish()}),N({type:q("open_page"),url:w().nullish()}),N({type:q("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:q("file_search_call"),id:w(),queries:le(w()),results:le(N({attributes:yt(w(),it([w(),j(),Dt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:q("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:le(pt("type",[N({type:q("logs"),logs:w()}),N({type:q("image"),url:w()})])).nullable()}),N({type:q("image_generation_call"),id:w(),result:w()}),N({type:q("local_shell_call"),id:w(),call_id:w(),action:N({type:q("exec"),command:le(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:yt(w(),w()).optional()})}),N({type:q("function_call"),call_id:w(),name:w(),arguments:w(),id:w(),namespace:w().nullish()}),N({type:q("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),N({type:q("computer_call"),id:w(),status:w().optional()}),N({type:q("reasoning"),id:w(),encrypted_content:w().nullish(),summary:le(N({type:q("summary_text"),text:w()}))}),N({type:q("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:it([w(),N({type:w().optional(),code:it([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:q("mcp_list_tools"),id:w(),server_label:w(),tools:le(N({name:w(),description:w().optional(),input_schema:xr(),annotations:yt(w(),An()).optional()})),error:it([w(),N({type:w().optional(),code:it([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:q("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:q("apply_patch_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed"]),operation:pt("type",[N({type:q("create_file"),path:w(),diff:w()}),N({type:q("delete_file"),path:w()}),N({type:q("update_file"),path:w(),diff:w()})])}),N({type:q("shell_call"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),action:N({commands:le(w())})}),N({type:q("shell_call_output"),id:w(),call_id:w(),status:Ee(["in_progress","completed","incomplete"]),output:le(N({stdout:w(),stderr:w(),outcome:pt("type",[N({type:q("timeout")}),N({type:q("exit"),exit_code:j()})])}))}),N({type:q("tool_search_call"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),arguments:An()}),N({type:q("tool_search_output"),id:w(),execution:Ee(["server","client"]),call_id:w().nullable(),status:Ee(["in_progress","completed","incomplete"]),tools:le(yt(w(),ei.optional()))})])).optional(),service_tier:w().nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).optional()}))),bu=20,Fa=Ue(()=>Fe(N({conversation:w().nullish(),include:le(Ee(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:it([Dt(),j().min(1).max(bu)]).optional(),maxToolCalls:j().nullish(),metadata:xr().nullish(),parallelToolCalls:Dt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheRetention:Ee(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Ee(["auto","flex","priority","default"]).nullish(),store:Dt().nullish(),passThroughUnsupportedFiles:Dt().optional(),strictJsonSchema:Dt().nullish(),textVerbosity:Ee(["low","medium","high"]).nullish(),truncation:Ee(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Ee(["system","developer","remove"]).optional(),forceReasoning:Dt().optional(),allowedTools:N({toolNames:le(w()).min(1),mode:Ee(["auto","required"]).optional()}).optional()})));async function I2({tools:t,toolChoice:r,allowedTools:o,toolNameMapping:c,customProviderToolNames:u}){var f,m,g;t=t?.length?t:void 0;const v=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:v};const x=[],E=new Map,A=u??new Set;for(const T of t)switch(T.type){case"function":{const S=(f=T.providerOptions)==null?void 0:f.openai,B=S2({tool:T,options:S}),D=S?.namespace;if(D==null)x.push(B);else{let ne=E.get(D.name);if(ne==null)ne={type:"namespace",name:D.name,description:D.description,tools:[]},E.set(D.name,ne),x.push(ne);else if(ne.description!==D.description)throw new Bn({functionality:`conflicting descriptions for OpenAI tool namespace "${D.name}"`});ne.tools.push(B)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Pt({value:T.args,schema:Hg});x.push({type:"file_search",vector_store_ids:S.vectorStoreIds,max_num_results:S.maxNumResults,ranking_options:S.ranking?{ranker:S.ranking.ranker,score_threshold:S.ranking.scoreThreshold}:void 0,filters:S.filters});break}case"openai.local_shell":{x.push({type:"local_shell"});break}case"openai.shell":{const S=await Pt({value:T.args,schema:t2});x.push({type:"shell",...S.environment&&{environment:T2(S.environment)}});break}case"openai.apply_patch":{x.push({type:"apply_patch"});break}case"openai.web_search_preview":{const S=await Pt({value:T.args,schema:d2});x.push({type:"web_search_preview",search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.web_search":{const S=await Pt({value:T.args,schema:s2});x.push({type:"web_search",filters:S.filters!=null?{allowed_domains:S.filters.allowedDomains}:void 0,external_web_access:S.externalWebAccess,search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.code_interpreter":{const S=await Pt({value:T.args,schema:Fg});x.push({type:"code_interpreter",container:S.container==null?{type:"auto",file_ids:void 0}:typeof S.container=="string"?S.container:{type:"auto",file_ids:S.container.fileIds}});break}case"openai.image_generation":{const S=await Pt({value:T.args,schema:Xg});x.push({type:"image_generation",background:S.background,input_fidelity:S.inputFidelity,input_image_mask:S.inputImageMask?{file_id:S.inputImageMask.fileId,image_url:S.inputImageMask.imageUrl}:void 0,model:S.model,moderation:S.moderation,partial_images:S.partialImages,quality:S.quality,output_compression:S.outputCompression,output_format:S.outputFormat,size:S.size});break}case"openai.mcp":{const S=await Pt({value:T.args,schema:m2}),B=z=>({tool_names:z.toolNames}),D=S.requireApproval,ne=D==null?void 0:typeof D=="string"?D:D.never!=null?{never:B(D.never)}:void 0;x.push({type:"mcp",server_label:S.serverLabel,allowed_tools:Array.isArray(S.allowedTools)?S.allowedTools:S.allowedTools?{read_only:S.allowedTools.readOnly,tool_names:S.allowedTools.toolNames}:void 0,authorization:S.authorization,connector_id:S.connectorId,headers:S.headers,require_approval:ne??"never",server_description:S.serverDescription,server_url:S.serverUrl});break}case"openai.custom":{const S=await Pt({value:T.args,schema:Vg});x.push({type:"custom",name:S.name,description:S.description,format:S.format}),A.add(S.name);break}case"openai.tool_search":{const S=await Pt({value:T.args,schema:r2});x.push({type:"tool_search",...S.execution!=null?{execution:S.execution}:{},...S.description!=null?{description:S.description}:{},...S.parameters!=null?{parameters:S.parameters}:{}});break}}break}default:v.push({type:"unsupported",feature:`function tool ${T}`});break}if(o!=null)return{tools:x,toolChoice:{type:"allowed_tools",mode:(m=o.mode)!=null?m:"auto",tools:o.toolNames.map(T=>{var S;return{type:"function",name:(S=c?.toProviderToolName(T))!=null?S:T}})},toolWarnings:v};if(r==null)return{tools:x,toolChoice:void 0,toolWarnings:v};const M=r.type;switch(M){case"auto":case"none":case"required":return{tools:x,toolChoice:M,toolWarnings:v};case"tool":{const T=(g=c?.toProviderToolName(r.toolName))!=null?g:r.toolName;return{tools:x,toolChoice:T==="code_interpreter"||T==="file_search"||T==="image_generation"||T==="web_search_preview"||T==="web_search"||T==="mcp"||T==="apply_patch"?{type:T}:A.has(T)?{type:"custom",name:T}:{type:"function",name:T},toolWarnings:v}}default:{const T=M;throw new Bn({functionality:`tool choice type: ${T}`})}}}function S2({tool:t,options:r}){const o=r?.deferLoading;return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema,...t.strict!=null?{strict:t.strict}:{},...o!=null?{defer_loading:o}:{}}}function T2(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:N2(o.skills)}}return{type:"local",skills:t.skills}}function N2(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 Ua(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 O2=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:g,prompt:v,providerOptions:x,tools:E,toolChoice:A,responseFormat:M}){var T,S,B,D,ne,z,Z,re,$,P,L;const G=[],U=pu(this.modelId);u!=null&&G.push({type:"unsupported",feature:"topK"}),g!=null&&G.push({type:"unsupported",feature:"seed"}),f!=null&&G.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&G.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&G.push({type:"unsupported",feature:"stopSequences"});const ee=this.config.provider.includes("azure")?"azure":"openai";let Y=await In({provider:ee,providerOptions:x,schema:Fa});Y==null&&ee!=="openai"&&(Y=await In({provider:"openai",providerOptions:x,schema:Fa}));const ue=(T=Y?.forceReasoning)!=null?T:U.isReasoningModel;Y?.conversation&&Y?.previousResponseId&&G.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const ge=Vp({tools:E,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","openai.tool_search":"tool_search"},resolveProviderToolName:K=>K.id==="openai.custom"?K.args.name:void 0}),Te=new Set,{tools:H,toolChoice:ye,toolWarnings:he}=await I2({tools:E,toolChoice:A,allowedTools:(S=Y?.allowedTools)!=null?S:void 0,toolNameMapping:ge,customProviderToolNames:Te}),{input:Se,warnings:We}=await C2({prompt:v,toolNameMapping:ge,systemMessageMode:(B=Y?.systemMessageMode)!=null?B:ue?"developer":U.systemMessageMode,providerOptionsName:ee,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(D=Y?.passThroughUnsupportedFiles)!=null?D:!1,store:(ne=Y?.store)!=null?ne:!0,hasConversation:Y?.conversation!=null,hasPreviousResponseId:Y?.previousResponseId!=null,hasLocalShellTool:Je("openai.local_shell"),hasShellTool:Je("openai.shell"),hasApplyPatchTool:Je("openai.apply_patch"),customProviderToolNames:Te.size>0?Te:void 0});G.push(...We);const me=(z=Y?.strictJsonSchema)!=null?z:!0;let Oe=Y?.include;function Me(K){Oe==null?Oe=[K]:Oe.includes(K)||(Oe=[...Oe,K])}function Je(K){return E?.find(xe=>xe.type==="provider"&&xe.id===K)!=null}const be=typeof Y?.logprobs=="number"?Y?.logprobs:Y?.logprobs===!0?bu:void 0;be&&Me("message.output_text.logprobs");const ke=(Z=E?.find(K=>K.type==="provider"&&(K.id==="openai.web_search"||K.id==="openai.web_search_preview")))==null?void 0:Z.name;ke&&Me("web_search_call.action.sources"),Je("openai.code_interpreter")&&Me("code_interpreter_call.outputs");const te=Y?.store;te===!1&&ue&&Me("reasoning.encrypted_content");const Ie={model:this.modelId,input:Se,temperature:r,top_p:c,max_output_tokens:t,...(M?.type==="json"||Y?.textVerbosity)&&{text:{...M?.type==="json"&&{format:M.schema!=null?{type:"json_schema",strict:me,name:(re=M.name)!=null?re:"response",description:M.description,schema:M.schema}:{type:"json_object"}},...Y?.textVerbosity&&{verbosity:Y.textVerbosity}}},conversation:Y?.conversation,max_tool_calls:Y?.maxToolCalls,metadata:Y?.metadata,parallel_tool_calls:Y?.parallelToolCalls,previous_response_id:Y?.previousResponseId,store:te,user:Y?.user,instructions:Y?.instructions,service_tier:Y?.serviceTier,include:Oe,prompt_cache_key:Y?.promptCacheKey,prompt_cache_retention:Y?.promptCacheRetention,safety_identifier:Y?.safetyIdentifier,top_logprobs:be,truncation:Y?.truncation,...ue&&(Y?.reasoningEffort!=null||Y?.reasoningSummary!=null)&&{reasoning:{...Y?.reasoningEffort!=null&&{effort:Y.reasoningEffort},...Y?.reasoningSummary!=null&&{summary:Y.reasoningSummary}}}};ue?Y?.reasoningEffort==="none"&&U.supportsNonReasoningParameters||(Ie.temperature!=null&&(Ie.temperature=void 0,G.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Ie.top_p!=null&&(Ie.top_p=void 0,G.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(Y?.reasoningEffort!=null&&G.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),Y?.reasoningSummary!=null&&G.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),Y?.serviceTier==="flex"&&!U.supportsFlexProcessing&&(G.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Ie.service_tier),Y?.serviceTier==="priority"&&!U.supportsPriorityProcessing&&(G.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 Ie.service_tier);const Ae=(L=(P=($=E?.find(K=>K.type==="provider"&&K.id==="openai.shell"))==null?void 0:$.args)==null?void 0:P.environment)==null?void 0:L.type,fe=Ae==="containerAuto"||Ae==="containerReference";return{webSearchToolName:ke,args:{...Ie,tools:H,tool_choice:ye},warnings:[...G,...he],store:te,toolNameMapping:ge,providerOptionsName:ee,isShellProviderExecuted:fe}}async doGenerate(t){var r,o,c,u,f,m,g,v,x,E,A,M,T,S,B,D,ne,z,Z,re,$,P,L,G,U,ee,Y,ue;const{args:ge,warnings:Te,webSearchToolName:H,toolNameMapping:ye,providerOptionsName:he,isShellProviderExecuted:Se}=await this.getArgs(t),We=this.config.url({path:"/responses",modelId:this.modelId}),me=Ua(t.prompt),{responseHeaders:Oe,value:Me,rawValue:Je}=await jn({url:We,headers:En(this.config.headers(),t.headers),body:ge,failedResponseHandler:Sn,successfulResponseHandler:mr(E2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Me.error)throw new sn({message:Me.error.message,url:We,requestBodyValues:ge,statusCode:400,responseHeaders:Oe,responseBody:Je,isRetryable:!1});const be=[],ke=[];let te=!1;const Ie=[];for(const K of Me.output)switch(K.type){case"reasoning":{K.summary.length===0&&K.summary.push({type:"summary_text",text:""});for(const xe of K.summary)be.push({type:"reasoning",text:xe.text,providerMetadata:{[he]:{itemId:K.id,reasoningEncryptedContent:(r=K.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{be.push({type:"tool-call",toolCallId:K.id,toolName:ye.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),be.push({type:"tool-result",toolCallId:K.id,toolName:ye.toCustomToolName("image_generation"),result:{result:K.result}});break}case"tool_search_call":{const xe=(o=K.call_id)!=null?o:K.id,et=K.execution==="server";et&&Ie.push(xe),be.push({type:"tool-call",toolCallId:xe,toolName:ye.toCustomToolName("tool_search"),input:JSON.stringify({arguments:K.arguments,call_id:K.call_id}),...et?{providerExecuted:!0}:{},providerMetadata:{[he]:{itemId:K.id}}});break}case"tool_search_output":{const xe=(u=(c=K.call_id)!=null?c:Ie.shift())!=null?u:K.id;be.push({type:"tool-result",toolCallId:xe,toolName:ye.toCustomToolName("tool_search"),result:{tools:K.tools},providerMetadata:{[he]:{itemId:K.id}}});break}case"local_shell_call":{be.push({type:"tool-call",toolCallId:K.call_id,toolName:ye.toCustomToolName("local_shell"),input:JSON.stringify({action:K.action}),providerMetadata:{[he]:{itemId:K.id}}});break}case"shell_call":{be.push({type:"tool-call",toolCallId:K.call_id,toolName:ye.toCustomToolName("shell"),input:JSON.stringify({action:{commands:K.action.commands}}),...Se&&{providerExecuted:!0},providerMetadata:{[he]:{itemId:K.id}}});break}case"shell_call_output":{be.push({type:"tool-result",toolCallId:K.call_id,toolName:ye.toCustomToolName("shell"),result:{output:K.output.map(xe=>({stdout:xe.stdout,stderr:xe.stderr,outcome:xe.outcome.type==="exit"?{type:"exit",exitCode:xe.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const xe of K.content){(m=(f=t.providerOptions)==null?void 0:f[he])!=null&&m.logprobs&&xe.logprobs&&ke.push(xe.logprobs);const et={itemId:K.id,...K.phase!=null&&{phase:K.phase},...xe.annotations.length>0&&{annotations:xe.annotations}};be.push({type:"text",text:xe.text,providerMetadata:{[he]:et}});for(const we of xe.annotations)we.type==="url_citation"?be.push({type:"source",sourceType:"url",id:(x=(v=(g=this.config).generateId)==null?void 0:v.call(g))!=null?x:Qt(),url:we.url,title:we.title}):we.type==="file_citation"?be.push({type:"source",sourceType:"document",id:(M=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?M:Qt(),mediaType:"text/plain",title:we.filename,filename:we.filename,providerMetadata:{[he]:{type:we.type,fileId:we.file_id,index:we.index}}}):we.type==="container_file_citation"?be.push({type:"source",sourceType:"document",id:(B=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?B:Qt(),mediaType:"text/plain",title:we.filename,filename:we.filename,providerMetadata:{[he]:{type:we.type,fileId:we.file_id,containerId:we.container_id}}}):we.type==="file_path"&&be.push({type:"source",sourceType:"document",id:(z=(ne=(D=this.config).generateId)==null?void 0:ne.call(D))!=null?z:Qt(),mediaType:"application/octet-stream",title:we.file_id,filename:we.file_id,providerMetadata:{[he]:{type:we.type,fileId:we.file_id,index:we.index}}})}break}case"function_call":{te=!0,be.push({type:"tool-call",toolCallId:K.call_id,toolName:K.name,input:K.arguments,providerMetadata:{[he]:{itemId:K.id,...K.namespace!=null&&{namespace:K.namespace}}}});break}case"custom_tool_call":{te=!0;const xe=ye.toCustomToolName(K.name);be.push({type:"tool-call",toolCallId:K.call_id,toolName:xe,input:JSON.stringify(K.input),providerMetadata:{[he]:{itemId:K.id}}});break}case"web_search_call":{be.push({type:"tool-call",toolCallId:K.id,toolName:ye.toCustomToolName(H??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),be.push({type:"tool-result",toolCallId:K.id,toolName:ye.toCustomToolName(H??"web_search"),result:Va(K.action)});break}case"mcp_call":{const xe=K.approval_request_id!=null&&(Z=me[K.approval_request_id])!=null?Z:K.id,et=`mcp.${K.name}`;be.push({type:"tool-call",toolCallId:xe,toolName:et,input:K.arguments,providerExecuted:!0,dynamic:!0}),be.push({type:"tool-result",toolCallId:xe,toolName:et,result:{type:"call",serverLabel:K.server_label,name:K.name,arguments:K.arguments,...K.output!=null?{output:K.output}:{},...K.error!=null?{error:K.error}:{}},providerMetadata:{[he]:{itemId:K.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const xe=(re=K.approval_request_id)!=null?re:K.id,et=(L=(P=($=this.config).generateId)==null?void 0:P.call($))!=null?L:Qt(),we=`mcp.${K.name}`;be.push({type:"tool-call",toolCallId:et,toolName:we,input:K.arguments,providerExecuted:!0,dynamic:!0}),be.push({type:"tool-approval-request",approvalId:xe,toolCallId:et});break}case"computer_call":{be.push({type:"tool-call",toolCallId:K.id,toolName:ye.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),be.push({type:"tool-result",toolCallId:K.id,toolName:ye.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:K.status||"completed"}});break}case"file_search_call":{be.push({type:"tool-call",toolCallId:K.id,toolName:ye.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),be.push({type:"tool-result",toolCallId:K.id,toolName:ye.toCustomToolName("file_search"),result:{queries:K.queries,results:(U=(G=K.results)==null?void 0:G.map(xe=>({attributes:xe.attributes,fileId:xe.file_id,filename:xe.filename,score:xe.score,text:xe.text})))!=null?U:null}});break}case"code_interpreter_call":{be.push({type:"tool-call",toolCallId:K.id,toolName:ye.toCustomToolName("code_interpreter"),input:JSON.stringify({code:K.code,containerId:K.container_id}),providerExecuted:!0}),be.push({type:"tool-result",toolCallId:K.id,toolName:ye.toCustomToolName("code_interpreter"),result:{outputs:K.outputs}});break}case"apply_patch_call":{be.push({type:"tool-call",toolCallId:K.call_id,toolName:ye.toCustomToolName("apply_patch"),input:JSON.stringify({callId:K.call_id,operation:K.operation}),providerMetadata:{[he]:{itemId:K.id}}});break}}const Ae={[he]:{responseId:Me.id,...ke.length>0?{logprobs:ke}:{},...typeof Me.service_tier=="string"?{serviceTier:Me.service_tier}:{}}},fe=Me.usage;return{content:be,finishReason:{unified:ho({finishReason:(ee=Me.incomplete_details)==null?void 0:ee.reason,hasFunctionCall:te}),raw:(ue=(Y=Me.incomplete_details)==null?void 0:Y.reason)!=null?ue:void 0},usage:Ba(fe),request:{body:ge},response:{id:Me.id,timestamp:new Date(Me.created_at*1e3),modelId:Me.model,headers:Oe,body:Je},providerMetadata:Ae,warnings:Te}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:m,isShellProviderExecuted:g}=await this.getArgs(t),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:x,value:E}=await jn({url:v,headers:En(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:Sn,successfulResponseHandler:Yo(A2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=this,M=Ua(t.prompt),T=new Map;let S={unified:"other",raw:void 0},B;const D=[];let ne=null;const z={},Z=[];let re,$=!1;const P={};let L;const G=[];return{stream:E.pipeThrough(new TransformStream({start(U){U.enqueue({type:"stream-start",warnings:o})},transform(U,ee){var Y,ue,ge,Te,H,ye,he,Se,We,me,Oe,Me,Je,be,ke,te,Ie,Ae,fe,K,xe,et,we,kt,Bt,Tn,It,Qe,je,Nn,Ce,Un,Hn,Yt,Wn,zt,ir,ln;if(t.includeRawChunks&&ee.enqueue({type:"raw",rawValue:U.rawValue}),!U.success){const se=R2(U.rawValue)?M2({value:U.rawValue,cause:U.error,url:v,requestBodyValues:r,responseHeaders:x}):U.error;S={unified:"error",raw:void 0},ee.enqueue({type:"error",error:se});return}const k=U.value;if(za(k)){if(k.item.type==="function_call")z[k.output_index]={toolName:k.item.name,toolCallId:k.item.call_id},ee.enqueue({type:"tool-input-start",id:k.item.call_id,toolName:k.item.name});else if(k.item.type==="custom_tool_call"){const se=u.toCustomToolName(k.item.name);z[k.output_index]={toolName:se,toolCallId:k.item.call_id},ee.enqueue({type:"tool-input-start",id:k.item.call_id,toolName:se})}else if(k.item.type==="web_search_call")z[k.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:k.item.id},ee.enqueue({type:"tool-input-start",id:k.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),ee.enqueue({type:"tool-input-end",id:k.item.id}),ee.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(k.item.type==="computer_call")z[k.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:k.item.id},ee.enqueue({type:"tool-input-start",id:k.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(k.item.type==="code_interpreter_call")z[k.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:k.item.id,codeInterpreter:{containerId:k.item.container_id}},ee.enqueue({type:"tool-input-start",id:k.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),ee.enqueue({type:"tool-input-delta",id:k.item.id,delta:`{"containerId":"${k.item.container_id}","code":"`});else if(k.item.type==="file_search_call")ee.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(k.item.type==="image_generation_call")ee.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(k.item.type==="tool_search_call"){const se=k.item.id,Ye=u.toCustomToolName("tool_search"),bt=k.item.execution==="server";z[k.output_index]={toolName:Ye,toolCallId:se,toolSearchExecution:(Y=k.item.execution)!=null?Y:"server"},bt&&ee.enqueue({type:"tool-input-start",id:se,toolName:Ye,providerExecuted:!0})}else if(k.item.type!=="tool_search_output"){if(!(k.item.type==="mcp_call"||k.item.type==="mcp_list_tools"||k.item.type==="mcp_approval_request"))if(k.item.type==="apply_patch_call"){const{call_id:se,operation:Ye}=k.item;if(z[k.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:se,applyPatch:{hasDiff:Ye.type==="delete_file",endEmitted:Ye.type==="delete_file"}},ee.enqueue({type:"tool-input-start",id:se,toolName:u.toCustomToolName("apply_patch")}),Ye.type==="delete_file"){const bt=JSON.stringify({callId:se,operation:Ye});ee.enqueue({type:"tool-input-delta",id:se,delta:bt}),ee.enqueue({type:"tool-input-end",id:se})}else ee.enqueue({type:"tool-input-delta",id:se,delta:`{"callId":"${fr(se)}","operation":{"type":"${fr(Ye.type)}","path":"${fr(Ye.path)}","diff":"`})}else k.item.type==="shell_call"?z[k.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:k.item.call_id}:k.item.type==="shell_call_output"||(k.item.type==="message"?(Z.splice(0,Z.length),re=(ue=k.item.phase)!=null?ue:void 0,ee.enqueue({type:"text-start",id:k.item.id,providerMetadata:{[m]:{itemId:k.item.id,...k.item.phase!=null&&{phase:k.item.phase}}}})):za(k)&&k.item.type==="reasoning"&&(P[k.item.id]={encryptedContent:k.item.encrypted_content,summaryParts:{0:"active"}},ee.enqueue({type:"reasoning-start",id:`${k.item.id}:0`,providerMetadata:{[m]:{itemId:k.item.id,reasoningEncryptedContent:(ge=k.item.encrypted_content)!=null?ge:null}}})))}}else if(P2(k)){if(k.item.type==="message"){const se=(Te=k.item.phase)!=null?Te:re;re=void 0,ee.enqueue({type:"text-end",id:k.item.id,providerMetadata:{[m]:{itemId:k.item.id,...se!=null&&{phase:se},...Z.length>0&&{annotations:Z}}}})}else if(k.item.type==="function_call")z[k.output_index]=void 0,$=!0,ee.enqueue({type:"tool-input-end",id:k.item.call_id,...k.item.namespace!=null&&{providerMetadata:{[m]:{namespace:k.item.namespace}}}}),ee.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:k.item.name,input:k.item.arguments,providerMetadata:{[m]:{itemId:k.item.id,...k.item.namespace!=null&&{namespace:k.item.namespace}}}});else if(k.item.type==="custom_tool_call"){z[k.output_index]=void 0,$=!0;const se=u.toCustomToolName(k.item.name);ee.enqueue({type:"tool-input-end",id:k.item.call_id}),ee.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:se,input:JSON.stringify(k.item.input),providerMetadata:{[m]:{itemId:k.item.id}}})}else if(k.item.type==="web_search_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Va(k.item.action)});else if(k.item.type==="computer_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-input-end",id:k.item.id}),ee.enqueue({type:"tool-call",toolCallId:k.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ee.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:k.item.status||"completed"}});else if(k.item.type==="file_search_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:k.item.queries,results:(ye=(H=k.item.results)==null?void 0:H.map(se=>({attributes:se.attributes,fileId:se.file_id,filename:se.filename,score:se.score,text:se.text})))!=null?ye:null}});else if(k.item.type==="code_interpreter_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:k.item.outputs}});else if(k.item.type==="image_generation_call")ee.enqueue({type:"tool-result",toolCallId:k.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:k.item.result}});else if(k.item.type==="tool_search_call"){const se=z[k.output_index],Ye=k.item.execution==="server";if(se!=null){const bt=Ye?se.toolCallId:(he=k.item.call_id)!=null?he:k.item.id;Ye?G.push(bt):ee.enqueue({type:"tool-input-start",id:bt,toolName:se.toolName}),ee.enqueue({type:"tool-input-end",id:bt}),ee.enqueue({type:"tool-call",toolCallId:bt,toolName:se.toolName,input:JSON.stringify({arguments:k.item.arguments,call_id:Ye?null:bt}),...Ye?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:k.item.id}}})}z[k.output_index]=void 0}else if(k.item.type==="tool_search_output"){const se=(We=(Se=k.item.call_id)!=null?Se:G.shift())!=null?We:k.item.id;ee.enqueue({type:"tool-result",toolCallId:se,toolName:u.toCustomToolName("tool_search"),result:{tools:k.item.tools},providerMetadata:{[m]:{itemId:k.item.id}}})}else if(k.item.type==="mcp_call"){z[k.output_index]=void 0;const se=(me=k.item.approval_request_id)!=null?me:void 0,Ye=se!=null&&(Me=(Oe=T.get(se))!=null?Oe:M[se])!=null?Me:k.item.id,bt=`mcp.${k.item.name}`;ee.enqueue({type:"tool-call",toolCallId:Ye,toolName:bt,input:k.item.arguments,providerExecuted:!0,dynamic:!0}),ee.enqueue({type:"tool-result",toolCallId:Ye,toolName:bt,result:{type:"call",serverLabel:k.item.server_label,name:k.item.name,arguments:k.item.arguments,...k.item.output!=null?{output:k.item.output}:{},...k.item.error!=null?{error:k.item.error}:{}},providerMetadata:{[m]:{itemId:k.item.id}}})}else if(k.item.type==="mcp_list_tools")z[k.output_index]=void 0;else if(k.item.type==="apply_patch_call"){const se=z[k.output_index];se?.applyPatch&&!se.applyPatch.endEmitted&&k.item.operation.type!=="delete_file"&&(se.applyPatch.hasDiff||ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:fr(k.item.operation.diff)}),ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:'"}}'}),ee.enqueue({type:"tool-input-end",id:se.toolCallId}),se.applyPatch.endEmitted=!0),se&&k.item.status==="completed"&&ee.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:k.item.call_id,operation:k.item.operation}),providerMetadata:{[m]:{itemId:k.item.id}}}),z[k.output_index]=void 0}else if(k.item.type==="mcp_approval_request"){z[k.output_index]=void 0;const se=(ke=(be=(Je=A.config).generateId)==null?void 0:be.call(Je))!=null?ke:Qt(),Ye=(te=k.item.approval_request_id)!=null?te:k.item.id;T.set(Ye,se);const bt=`mcp.${k.item.name}`;ee.enqueue({type:"tool-call",toolCallId:se,toolName:bt,input:k.item.arguments,providerExecuted:!0,dynamic:!0}),ee.enqueue({type:"tool-approval-request",approvalId:Ye,toolCallId:se})}else if(k.item.type==="local_shell_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:k.item.action.command,timeoutMs:k.item.action.timeout_ms,user:k.item.action.user,workingDirectory:k.item.action.working_directory,env:k.item.action.env}}),providerMetadata:{[m]:{itemId:k.item.id}}});else if(k.item.type==="shell_call")z[k.output_index]=void 0,ee.enqueue({type:"tool-call",toolCallId:k.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:k.item.action.commands}}),...g&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:k.item.id}}});else if(k.item.type==="shell_call_output")ee.enqueue({type:"tool-result",toolCallId:k.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:k.item.output.map(se=>({stdout:se.stdout,stderr:se.stderr,outcome:se.outcome.type==="exit"?{type:"exit",exitCode:se.outcome.exit_code}:{type:"timeout"}}))}});else if(k.item.type==="reasoning"){const se=P[k.item.id],Ye=Object.entries(se.summaryParts).filter(([bt,mt])=>mt==="active"||mt==="can-conclude").map(([bt])=>bt);for(const bt of Ye)ee.enqueue({type:"reasoning-end",id:`${k.item.id}:${bt}`,providerMetadata:{[m]:{itemId:k.item.id,reasoningEncryptedContent:(Ie=k.item.encrypted_content)!=null?Ie:null}}});delete P[k.item.id]}}else if(U2(k)){const se=z[k.output_index];se!=null&&ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:k.delta})}else if(z2(k)){const se=z[k.output_index];se!=null&&ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:k.delta})}else if(j2(k)){const se=z[k.output_index];se?.applyPatch&&(ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:fr(k.delta)}),se.applyPatch.hasDiff=!0)}else if(H2(k)){const se=z[k.output_index];se?.applyPatch&&!se.applyPatch.endEmitted&&(se.applyPatch.hasDiff||(ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:fr(k.diff)}),se.applyPatch.hasDiff=!0),ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:'"}}'}),ee.enqueue({type:"tool-input-end",id:se.toolCallId}),se.applyPatch.endEmitted=!0)}else if(V2(k))ee.enqueue({type:"tool-result",toolCallId:k.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:k.partial_image_b64},preliminary:!0});else if(Z2(k)){const se=z[k.output_index];se!=null&&ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:fr(k.delta)})}else if($2(k)){const se=z[k.output_index];se!=null&&(ee.enqueue({type:"tool-input-delta",id:se.toolCallId,delta:'"}'}),ee.enqueue({type:"tool-input-end",id:se.toolCallId}),ee.enqueue({type:"tool-call",toolCallId:se.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:k.code,containerId:se.codeInterpreter.containerId}),providerExecuted:!0}))}else if(F2(k))ne=k.response.id,ee.enqueue({type:"response-metadata",id:k.response.id,timestamp:new Date(k.response.created_at*1e3),modelId:k.response.model});else if(k2(k))ee.enqueue({type:"text-delta",id:k.item_id,delta:k.delta}),(fe=(Ae=t.providerOptions)==null?void 0:Ae[m])!=null&&fe.logprobs&&k.logprobs&&D.push(k.logprobs);else if(k.type==="response.reasoning_summary_part.added"){if(k.summary_index>0){const se=P[k.item_id];se.summaryParts[k.summary_index]="active";for(const Ye of Object.keys(se.summaryParts))se.summaryParts[Ye]==="can-conclude"&&(ee.enqueue({type:"reasoning-end",id:`${k.item_id}:${Ye}`,providerMetadata:{[m]:{itemId:k.item_id}}}),se.summaryParts[Ye]="concluded");ee.enqueue({type:"reasoning-start",id:`${k.item_id}:${k.summary_index}`,providerMetadata:{[m]:{itemId:k.item_id,reasoningEncryptedContent:(xe=(K=P[k.item_id])==null?void 0:K.encryptedContent)!=null?xe:null}}})}}else if(k.type==="response.reasoning_summary_text.delta")ee.enqueue({type:"reasoning-delta",id:`${k.item_id}:${k.summary_index}`,delta:k.delta,providerMetadata:{[m]:{itemId:k.item_id}}});else if(k.type==="response.reasoning_summary_part.done")f?(ee.enqueue({type:"reasoning-end",id:`${k.item_id}:${k.summary_index}`,providerMetadata:{[m]:{itemId:k.item_id}}}),P[k.item_id].summaryParts[k.summary_index]="concluded"):P[k.item_id].summaryParts[k.summary_index]="can-conclude";else if(B2(k))S={unified:ho({finishReason:(et=k.response.incomplete_details)==null?void 0:et.reason,hasFunctionCall:$}),raw:(kt=(we=k.response.incomplete_details)==null?void 0:we.reason)!=null?kt:void 0},B=k.response.usage,typeof k.response.service_tier=="string"&&(L=k.response.service_tier);else if(L2(k)){const se=(Bt=k.response.incomplete_details)==null?void 0:Bt.reason;S={unified:se?ho({finishReason:se,hasFunctionCall:$}):"error",raw:se??"error"},B=(Tn=k.response.usage)!=null?Tn:void 0}else W2(k)?(Z.push(k.annotation),k.annotation.type==="url_citation"?ee.enqueue({type:"source",sourceType:"url",id:(je=(Qe=(It=A.config).generateId)==null?void 0:Qe.call(It))!=null?je:Qt(),url:k.annotation.url,title:k.annotation.title}):k.annotation.type==="file_citation"?ee.enqueue({type:"source",sourceType:"document",id:(Un=(Ce=(Nn=A.config).generateId)==null?void 0:Ce.call(Nn))!=null?Un:Qt(),mediaType:"text/plain",title:k.annotation.filename,filename:k.annotation.filename,providerMetadata:{[m]:{type:k.annotation.type,fileId:k.annotation.file_id,index:k.annotation.index}}}):k.annotation.type==="container_file_citation"?ee.enqueue({type:"source",sourceType:"document",id:(Wn=(Yt=(Hn=A.config).generateId)==null?void 0:Yt.call(Hn))!=null?Wn:Qt(),mediaType:"text/plain",title:k.annotation.filename,filename:k.annotation.filename,providerMetadata:{[m]:{type:k.annotation.type,fileId:k.annotation.file_id,containerId:k.annotation.container_id}}}):k.annotation.type==="file_path"&&ee.enqueue({type:"source",sourceType:"document",id:(ln=(ir=(zt=A.config).generateId)==null?void 0:ir.call(zt))!=null?ln:Qt(),mediaType:"application/octet-stream",title:k.annotation.file_id,filename:k.annotation.file_id,providerMetadata:{[m]:{type:k.annotation.type,fileId:k.annotation.file_id,index:k.annotation.index}}})):G2(k)&&ee.enqueue({type:"error",error:k})},flush(U){const ee={[m]:{responseId:ne,...D.length>0?{logprobs:D}:{},...L!==void 0?{serviceTier:L}:{}}};U.enqueue({type:"finish",finishReason:S,usage:Ba(B),providerMetadata:ee})}})),request:{body:r},response:{headers:x}}}};function k2(t){return t.type==="response.output_text.delta"}function R2(t){const r=D2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function M2({value:t,cause:r,url:o,requestBodyValues:c,responseHeaders:u}){return new sn({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:o,requestBodyValues:c,responseHeaders:u,responseBody:JSON.stringify(t),cause:r,data:t,isRetryable:!1})}function D2(t){return typeof t=="object"&&t!=null?t:void 0}function P2(t){return t.type==="response.output_item.done"}function B2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function L2(t){return t.type==="response.failed"}function F2(t){return t.type==="response.created"}function U2(t){return t.type==="response.function_call_arguments.delta"}function z2(t){return t.type==="response.custom_tool_call_input.delta"}function V2(t){return t.type==="response.image_generation_call.partial_image"}function Z2(t){return t.type==="response.code_interpreter_call_code.delta"}function $2(t){return t.type==="response.code_interpreter_call_code.done"}function j2(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function H2(t){return t.type==="response.apply_patch_call_operation_diff.done"}function za(t){return t.type==="response.output_item.added"}function W2(t){return t.type==="response.output_text.annotation.added"}function G2(t){return t.type==="error"}function Va(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.queries!=null&&{queries:t.queries}},...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 fr(t){return JSON.stringify(t).slice(1,-1)}var X2=Ue(()=>Fe(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),q2=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 g=[],v=await In({provider:"openai",providerOptions:m,schema:X2}),x={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:u};if(o&&(["mp3","opus","aac","flac","wav","pcm"].includes(o)?x.response_format=o:g.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),v){const E={};for(const A in E){const M=E[A];M!==void 0&&(x[A]=M)}}return f&&g.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:x,warnings:g}}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:g,responseHeaders:v,rawValue:x}=await jn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:f,failedResponseHandler:Sn,successfulResponseHandler:dg(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:g,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:v,body:x}}}},Y2=Ue(()=>Fe(N({text:w(),language:w().nullish(),duration:j().nullish(),words:le(N({word:w(),start:j(),end:j()})).nullish(),segments:le(N({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:le(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),K2=Ue(()=>Fe(N({include:le(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:le(Ee(["word","segment"])).default(["segment"]).optional()}))),Za={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"},J2=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 In({provider:"openai",providerOptions:o,schema:K2}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([Ho(t)]);f.append("model",this.modelId);const g=um(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${g}`),u){const v={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[x,E]of Object.entries(v))if(E!=null)if(Array.isArray(E))for(const A of E)f.append(`${x}[]`,String(A));else f.append(x,String(E))}return{formData:f,warnings:c}}async doGenerate(t){var r,o,c,u,f,m,g,v;const x=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{formData:E,warnings:A}=await this.getArgs(t),{value:M,responseHeaders:T,rawValue:S}=await du({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),formData:E,failedResponseHandler:Sn,successfulResponseHandler:mr(Y2),abortSignal:t.abortSignal,fetch:this.config.fetch}),B=M.language!=null&&M.language in Za?Za[M.language]:void 0;return{text:M.text,segments:(g=(m=(u=M.segments)==null?void 0:u.map(D=>({text:D.text,startSecond:D.start,endSecond:D.end})))!=null?m:(f=M.words)==null?void 0:f.map(D=>({text:D.word,startSecond:D.start,endSecond:D.end})))!=null?g:[],language:B,durationInSeconds:(v=M.duration)!=null?v:void 0,warnings:A,response:{timestamp:x,modelId:this.modelId,headers:T,body:S}}}},Q2="3.0.78";function Au(t={}){var r,o;const c=(r=fg(cm({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>iu({Authorization:`Bearer ${lm({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${Q2}`),m=B=>new wg(B,{provider:`${u}.chat`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),g=B=>new bg(B,{provider:`${u}.completion`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),v=B=>new Ig(B,{provider:`${u}.embedding`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),x=B=>new Rg(B,{provider:`${u}.image`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),E=B=>new J2(B,{provider:`${u}.transcription`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),A=B=>new q2(B,{provider:`${u}.speech`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch}),M=B=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(B)},T=B=>new O2(B,{provider:`${u}.responses`,url:({path:D})=>`${c}${D}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(B){return M(B)};return S.specificationVersion="v3",S.languageModel=M,S.chat=m,S.completion=g,S.responses=T,S.embedding=v,S.embeddingModel=v,S.textEmbedding=v,S.textEmbeddingModel=v,S.image=x,S.imageModel=x,S.transcription=E,S.transcriptionModel=E,S.speech=A,S.speechModel=A,S.tools=_2,S}Au();const ex={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 tx{constructor(r={}){this.option=r}async traverse(r){const o=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",o),(async()=>{let u,f,m,g,v;for await(const x of r.fullStream)switch(this.option.debug&&console.log("【stream-debug】 "+(new Date().getTime()/1e3).toString().slice(-6)+x.type,x),x.type){case"start":u=_.reactive({running:!0,steps:[]}),o.value=u,this.option.onStart?.(u);break;case"start-step":f=_.reactive({running:!0,contents:[],request:x.request}),u.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.reactive({type:"reasoning",id:x.id,running:!0,text:""}),f.contents.push(m),this.option.onReasoning?.(m);break;case"reasoning-delta":m.text+=x.text;break;case"reasoning-end":m.running=!1;break;case"text-start":g=_.reactive({type:"text",id:x.id,running:!0,text:""}),f.contents.push(g),this.option.onText?.(g);break;case"text-delta":g.text+=x.text;break;case"text-end":g.running=!1;break;case"tool-input-start":v=_.reactive({type:"tool",running:!0,id:x.id,toolCallId:x.id,title:"",toolName:x.toolName,dynamic:x.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(v),this.option.onTool?.(v);break;case"tool-input-delta":v.inputStr+=x.delta;break;case"tool-input-end":break;case"tool-call":v.input=x.input;break;case"tool-result":v.output=x.output,v.running=!1;break;case"tool-error":v.error=x.error,v.running=!1;break;case"finish-step":f.running=!1,f.finishReason=x.finishReason,f.usage=x.usage;break;case"finish":u.running=!1,u.finishReason=x.finishReason,u.totalUsage=x.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":u&&(u.running=!1,u.error=x.error,u.finishReason="error"),this.option.onFinish?.();break;case"abort":u&&(u.running=!1,u.error={message:x.reason},u.finishReason="other"),this.option.onFinish?.();break}})(),o}}function nx(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 x=t.slice(o).trim();x&&r.push({type:"markdown",content:x});break}const m=t.slice(o,u).trim();m&&r.push({type:"markdown",content:m});const g=t.indexOf("```",u+f);let v;g===-1?(v=t.slice(u+f).trim(),o=t.length):(v=t.slice(u+f,g).trim(),o=g+3),r.push({type:"schema-card",content:v})}return r}class rx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
55
+ ${r}:`]}}function Pa({id:t,model:r,created:i}){return{id:t??void 0,modelId:r??void 0,timestamp:i!=null?new Date(i*1e3):void 0}}function Ba(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 kg=Fe(()=>Le(N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),Rg=Fe(()=>Le(st([N({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(N({text:w(),finish_reason:w().nullish(),index:j(),logprobs:N({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(wt(w(),j())).nullish()}).nullish()})),usage:N({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Qi]))),La=Fe(()=>Le(N({echo:Mt().optional(),logitBias:wt(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:st([Mt(),j()]).optional()}))),Mg=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:i,topP:c,topK:d,frequencyPenalty:f,presencePenalty:m,stopSequences:x,responseFormat:v,tools:g,toolChoice:E,seed:A,providerOptions:D}){const T=[],S={...await An({provider:"openai",providerOptions:D,schema:La}),...await An({provider:this.providerOptionsName,providerOptions:D,schema:La})};d!=null&&T.push({type:"unsupported",feature:"topK"}),g?.length&&T.push({type:"unsupported",feature:"tools"}),E!=null&&T.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&T.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:P,stopSequences:M}=Og({prompt:t}),ee=[...M??[],...x??[]];return{args:{model:this.modelId,echo:S.echo,logit_bias:S.logitBias,logprobs:S?.logprobs===!0?0:S?.logprobs===!1?void 0:S?.logprobs,suffix:S.suffix,user:S.user,max_tokens:r,temperature:i,top_p:c,frequency_penalty:f,presence_penalty:m,seed:A,prompt:P,stop:ee.length>0?ee:void 0},warnings:T}}async doGenerate(t){var r;const{args:i,warnings:c}=await this.getArgs(t),{responseHeaders:d,value:f,rawValue:m}=await Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:i,failedResponseHandler:En,successfulResponseHandler:mr(kg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=f.choices[0],v={openai:{}};return x.logprobs!=null&&(v.openai.logprobs=x.logprobs),{content:[{type:"text",text:x.text}],usage:Da(f.usage),finishReason:{unified:Ba(x.finish_reason),raw:(r=x.finish_reason)!=null?r:void 0},request:{body:i},response:{...Pa(f),headers:d,body:m},providerMetadata:v,warnings:c}}async doStream(t){const{args:r,warnings:i}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},d=this.config.url({path:"/completions",modelId:this.modelId}),{responseHeaders:f,value:m}=await Zn({url:d,headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ji(Rg),abortSignal:t.abortSignal,fetch:this.config.fetch}),x=await es({stream:m,getError:T=>"error"in T?T.error:void 0,isOutputChunk:Dg,url:d,requestBodyValues:c,responseHeaders:f});let v={unified:"other",raw:void 0};const g={openai:{}};let E,A=!0;return{stream:x.pipeThrough(new TransformStream({start(T){T.enqueue({type:"stream-start",warnings:i})},transform(T,S){if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:T.rawValue}),!T.success){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:T.error});return}const P=T.value;if("error"in P){v={unified:"error",raw:void 0},S.enqueue({type:"error",error:P.error});return}A&&(A=!1,S.enqueue({type:"response-metadata",...Pa(P)}),S.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(E=P.usage);const M=P.choices[0];M?.finish_reason!=null&&(v={unified:Ba(M.finish_reason),raw:M.finish_reason}),M?.logprobs!=null&&(g.openai.logprobs=M.logprobs),M?.text!=null&&M.text.length>0&&S.enqueue({type:"text-delta",id:"0",delta:M.text})},flush(T){A||T.enqueue({type:"text-end",id:"0"}),T.enqueue({type:"finish",finishReason:v,providerMetadata:g,usage:Da(E)})}})),request:{body:c},response:{headers:f}}}};function Dg(t){return!("error"in t)&&t.choices.some(r=>r.text.length>0)}var Pg=Fe(()=>Le(N({dimensions:j().optional(),user:w().optional()}))),Bg=Fe(()=>Le(N({data:ue(N({embedding:ue(j())})),usage:N({prompt_tokens:j()}).nullish()}))),Lg=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:i,providerOptions:c}){var d;if(t.length>this.maxEmbeddingsPerCall)throw new jp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(d=await An({provider:"openai",providerOptions:c,schema:Pg}))!=null?d:{},{responseHeaders:m,value:x,rawValue:v}=await Zn({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:bn(this.config.headers(),r),body:{model:this.modelId,input:t,encoding_format:"float",dimensions:f.dimensions,user:f.user},failedResponseHandler:En,successfulResponseHandler:mr(Bg),abortSignal:i,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:v}}}},Fa=Fe(()=>Le(N({created:j().nullish(),data:ue(N({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:N({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:N({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),Fg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},Ug=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1","gpt-image-2"];function zg(t){return Ug.some(r=>t.startsWith(r))}var vu=N({quality:Ae(["standard","hd","low","medium","high","auto"]).optional(),background:Ae(["transparent","opaque","auto"]).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),outputCompression:j().int().min(0).max(100).optional(),user:w().optional()}),Vg=Fe(()=>Le(vu.extend({style:Ae(["vivid","natural"]).optional(),moderation:Ae(["auto","low"]).optional()}))),Zg=Fe(()=>Le(vu.extend({inputFidelity:Ae(["high","low"]).optional()}))),$g=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=Fg[this.modelId])!=null?t:1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:r,mask:i,n:c,size:d,aspectRatio:f,seed:m,providerOptions:x,headers:v,abortSignal:g}){var E,A,D,T,S,P,M,ee,$,F,re;const Z=[];f!=null&&Z.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&Z.push({type:"unsupported",feature:"seed"});const B=(D=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?D:new Date;if(r!=null){const we=(T=await An({provider:"openai",providerOptions:x,schema:Zg}))!=null?T:{},{value:G,responseHeaders:me}=await xu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:bn(this.config.headers(),v),formData:Jp({model:this.modelId,prompt:t,image:await Promise.all(r.map(fe=>fe.type==="file"?new Blob([fe.data instanceof Uint8Array?new Blob([fe.data],{type:fe.mediaType}):new Blob([qi(fe.data)],{type:fe.mediaType})],{type:fe.mediaType}):lu(fe.url))),mask:i!=null?await jg(i):void 0,n:c,size:d,quality:we.quality,background:we.background,output_format:we.outputFormat,output_compression:we.outputCompression,input_fidelity:we.inputFidelity,user:we.user}),failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:G.data.map(fe=>fe.b64_json),warnings:Z,usage:G.usage!=null?{inputTokens:(S=G.usage.input_tokens)!=null?S:void 0,outputTokens:(P=G.usage.output_tokens)!=null?P:void 0,totalTokens:(M=G.usage.total_tokens)!=null?M:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:me},providerMetadata:{openai:{images:G.data.map((fe,te)=>{var q,ke,le,Te,Je,xe;return{...fe.revised_prompt?{revisedPrompt:fe.revised_prompt}:{},created:(q=G.created)!=null?q:void 0,size:(ke=G.size)!=null?ke:void 0,quality:(le=G.quality)!=null?le:void 0,background:(Te=G.background)!=null?Te:void 0,outputFormat:(Je=G.output_format)!=null?Je:void 0,...Ua((xe=G.usage)==null?void 0:xe.input_tokens_details,te,G.data.length)}})}}}}const L=(ee=await An({provider:"openai",providerOptions:x,schema:Vg}))!=null?ee:{},{value:W,responseHeaders:z}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:bn(this.config.headers(),v),body:{model:this.modelId,prompt:t,n:c,size:d,quality:L.quality,style:L.style,background:L.background,moderation:L.moderation,output_format:L.outputFormat,output_compression:L.outputCompression,user:L.user,...zg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:En,successfulResponseHandler:mr(Fa),abortSignal:g,fetch:this.config.fetch});return{images:W.data.map(we=>we.b64_json),warnings:Z,usage:W.usage!=null?{inputTokens:($=W.usage.input_tokens)!=null?$:void 0,outputTokens:(F=W.usage.output_tokens)!=null?F:void 0,totalTokens:(re=W.usage.total_tokens)!=null?re:void 0}:void 0,response:{timestamp:B,modelId:this.modelId,headers:z},providerMetadata:{openai:{images:W.data.map((we,G)=>{var me,fe,te,q,ke,le;return{...we.revised_prompt?{revisedPrompt:we.revised_prompt}:{},created:(me=W.created)!=null?me:void 0,size:(fe=W.size)!=null?fe:void 0,quality:(te=W.quality)!=null?te:void 0,background:(q=W.background)!=null?q:void 0,outputFormat:(ke=W.output_format)!=null?ke:void 0,...Ua((le=W.usage)==null?void 0:le.input_tokens_details,G,W.data.length)}})}}}}};function Ua(t,r,i){if(t==null)return{};const c={};if(t.image_tokens!=null){const d=Math.floor(t.image_tokens/i),f=t.image_tokens-d*(i-1);c.imageTokens=r===i-1?f:d}if(t.text_tokens!=null){const d=Math.floor(t.text_tokens/i),f=t.text_tokens-d*(i-1);c.textTokens=r===i-1?f:d}return c}async function jg(t){if(!t)return;if(t.type==="url")return lu(t.url);const r=t.data instanceof Uint8Array?t.data:qi(t.data);return new Blob([r],{type:t.mediaType})}var Cu=Fe(()=>Le(N({callId:w(),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}))),bu=Fe(()=>Le(N({status:Ae(["completed","failed"]),output:w().optional()}))),Hg=Dn({id:"openai.apply_patch",inputSchema:Cu,outputSchema:bu}),Wg=Hg,Gg=Fe(()=>Le(N({code:w().nullish(),containerId:w()}))),qg=Fe(()=>Le(N({outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullish()}))),Xg=Fe(()=>Le(N({container:st([w(),N({fileIds:ue(w()).optional()})]).optional()}))),Yg=Dn({id:"openai.code_interpreter",inputSchema:Gg,outputSchema:qg}),Kg=(t={})=>Yg(t),Jg=Fe(()=>Le(N({name:w(),description:w().optional(),format:st([N({type:Y("grammar"),syntax:Ae(["regex","lark"]),definition:w()}),N({type:Y("text")})]).optional()}))),Qg=Fe(()=>Le(w())),e2=pg({id:"openai.custom",inputSchema:Qg}),t2=t=>e2(t),Au=N({key:w(),type:Ae(["eq","ne","gt","gte","lt","lte","in","nin"]),value:st([w(),j(),Mt(),ue(w())])}),Eu=N({type:Ae(["and","or"]),filters:ue(st([Au,Wi(()=>Eu)]))}),n2=Fe(()=>Le(N({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:N({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:st([Au,Eu]).optional()}))),r2=Fe(()=>Le(N({queries:ue(w()),results:ue(N({attributes:wt(w(),Cn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),o2=Dn({id:"openai.file_search",inputSchema:N({}),outputSchema:r2}),i2=Fe(()=>Le(N({background:Ae(["auto","opaque","transparent"]).optional(),inputFidelity:Ae(["low","high"]).optional(),inputImageMask:N({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Ae(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Ae(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Ae(["auto","low","medium","high"]).optional(),size:Ae(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),s2=Fe(()=>Le(N({}))),a2=Fe(()=>Le(N({result:w()}))),l2=Dn({id:"openai.image_generation",inputSchema:s2,outputSchema:a2}),c2=(t={})=>l2(t),Iu=Fe(()=>Le(N({action:N({type:Y("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:wt(w(),w()).optional()})}))),Su=Fe(()=>Le(N({output:w()}))),u2=Dn({id:"openai.local_shell",inputSchema:Iu,outputSchema:Su}),Tu=Fe(()=>Le(N({action:N({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),ki=Fe(()=>Le(N({output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exitCode:j()})])}))}))),d2=ue(mt("type",[N({type:Y("skillReference"),skillId:w(),version:w().optional()}),N({type:Y("inline"),name:w(),description:w(),source:N({type:Y("base64"),mediaType:Y("application/zip"),data:w()})})])).optional(),f2=Fe(()=>Le(N({environment:st([N({type:Y("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Ae(["1g","4g","16g","64g"]).optional(),networkPolicy:mt("type",[N({type:Y("disabled")}),N({type:Y("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(N({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:d2}),N({type:Y("containerReference"),containerId:w()}),N({type:Y("local").optional(),skills:ue(N({name:w(),description:w(),path:w()})).optional()})]).optional()}))),h2=Dn({id:"openai.shell",inputSchema:Tu,outputSchema:ki}),p2=Fe(()=>Le(N({execution:Ae(["server","client"]).optional(),description:w().optional(),parameters:wt(w(),Cn()).optional()}))),Ri=Fe(()=>Le(N({arguments:Cn().optional(),call_id:w().nullish()}))),Mi=Fe(()=>Le(N({tools:ue(wt(w(),Cn()))}))),m2=Dn({id:"openai.tool_search",inputSchema:Ri,outputSchema:Mi}),g2=(t={})=>m2(t),x2=Fe(()=>Le(N({externalWebAccess:Mt().optional(),filters:N({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),y2=Fe(()=>Le(N({}))),w2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional(),queries:ue(w()).optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).optional()}))),_2=Dn({id:"openai.web_search",inputSchema:y2,outputSchema:w2}),v2=(t={})=>_2(t),C2=Fe(()=>Le(N({searchContextSize:Ae(["low","medium","high"]).optional(),userLocation:N({type:Y("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),b2=Fe(()=>Le(N({}))),A2=Fe(()=>Le(N({action:mt("type",[N({type:Y("search"),query:w().optional()}),N({type:Y("openPage"),url:w().nullish()}),N({type:Y("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),E2=Dn({id:"openai.web_search_preview",inputSchema:b2,outputSchema:A2}),Di=Wi(()=>st([w(),j(),Mt(),bc(),ue(Di),wt(w(),Di)])),I2=Fe(()=>Le(N({serverLabel:w(),allowedTools:st([ue(w()),N({readOnly:Mt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:wt(w(),w()).optional(),requireApproval:st([Ae(["always","never"]),N({never:N({toolNames:ue(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."))),S2=Fe(()=>Le(N({}))),T2=Fe(()=>Le(N({type:Y("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:st([w(),Di]).optional()}))),N2=Dn({id:"openai.mcp",inputSchema:S2,outputSchema:T2}),O2=t=>N2(t),k2={applyPatch:Wg,customTool:t2,codeInterpreter:Kg,fileSearch:o2,imageGeneration:c2,localShell:u2,shell:h2,webSearchPreview:E2,webSearch:v2,mcp:O2,toolSearch:g2};function za(t){var r,i,c,d,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=t.input_tokens,v=t.output_tokens,g=(i=(r=t.input_tokens_details)==null?void 0:r.cached_tokens)!=null?i:0,E=(d=(c=t.input_tokens_details)==null?void 0:c.cache_write_tokens)!=null?d:void 0,A=(m=(f=t.output_tokens_details)==null?void 0:f.reasoning_tokens)!=null?m:0;return{inputTokens:{total:x,noCache:x-g-(E??0),cacheRead:g,cacheWrite:E},outputTokens:{total:v,text:v-A,reasoning:A},raw:t}}function R2(t){return JSON.stringify(t===void 0?{}:t)}function Nr(t,r){var i;return(i=t?.[r])==null?void 0:i.promptCacheBreakpoint}function Va(t,r){return r?r.some(i=>t.startsWith(i)):!1}async function M2({prompt:t,toolNameMapping:r,systemMessageMode:i,providerOptionsName:c,fileIdPrefixes:d,passThroughUnsupportedFiles:f=!1,store:m,hasConversation:x=!1,hasPreviousResponseId:v=!1,hasLocalShellTool:g=!1,hasShellTool:E=!1,hasApplyPatchTool:A=!1,customProviderToolNames:D}){var T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe,te,q,ke,le,Te,Je;let xe=[];const $e=[],Ue=new Set;for(const{role:Ze,content:qe,providerOptions:ze}of t)switch(Ze){case"system":{switch(i){case"system":{const ie=Nr(ze,c);xe.push({role:"system",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"developer":{const ie=Nr(ze,c);xe.push({role:"developer",content:ie==null?qe:[{type:"input_text",text:qe,prompt_cache_breakpoint:ie}]});break}case"remove":{$e.push({type:"other",message:"system messages are removed for this model"});break}default:{const ie=i;throw new Error(`Unsupported system message mode: ${ie}`)}}break}case"user":{xe.push({role:"user",content:qe.map((ie,de)=>{var _e,Pe,ae;switch(ie.type){case"text":{const J=Nr(ie.providerOptions,c);return{type:"input_text",text:ie.text,...J!=null&&{prompt_cache_breakpoint:J}}}case"file":{const J=Nr(ie.providerOptions,c),ye=ie.mediaType==="image/*"?"image/jpeg":ie.mediaType;if(ye.startsWith("image/"))return{type:"input_image",...ie.data instanceof URL?{image_url:ie.data.toString()}:typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{image_url:`data:${ye};base64,${kr(ie.data)}`},detail:(Pe=(_e=ie.providerOptions)==null?void 0:_e[c])==null?void 0:Pe.imageDetail,...J!=null&&{prompt_cache_breakpoint:J}};if(ie.data instanceof URL)return{type:"input_file",file_url:ie.data.toString(),...J!=null&&{prompt_cache_breakpoint:J}};if(ye!=="application/pdf"&&!f)throw new Mn({functionality:`file part media type ${ye}`});return{type:"input_file",...typeof ie.data=="string"&&Va(ie.data,d)?{file_id:ie.data}:{filename:(ae=ie.filename)!=null?ae:ye==="application/pdf"?`part-${de}.pdf`:`part-${de}`,file_data:`data:${ye};base64,${kr(ie.data)}`},...J!=null&&{prompt_cache_breakpoint:J}}}}})});break}case"assistant":{const ie={};for(const de of qe)switch(de.type){case"text":{const _e=(T=de.providerOptions)==null?void 0:T[c],Pe=_e?.itemId,ae=_e?.phase;if(x&&Pe!=null)break;if(m&&Pe!=null){xe.push({type:"item_reference",id:Pe});break}xe.push({role:"assistant",content:[{type:"output_text",text:de.text}],id:Pe,...ae!=null&&{phase:ae}});break}case"tool-call":{const _e=($=(P=(S=de.providerOptions)==null?void 0:S[c])==null?void 0:P.itemId)!=null?$:(ee=(M=de.providerMetadata)==null?void 0:M[c])==null?void 0:ee.itemId,Pe=(L=(re=(F=de.providerOptions)==null?void 0:F[c])==null?void 0:re.namespace)!=null?L:(B=(Z=de.providerMetadata)==null?void 0:Z[c])==null?void 0:B.namespace;if(x&&_e!=null)break;const ae=r.toProviderToolName(de.toolName);if(ae==="tool_search"){if(m&&_e!=null){xe.push({type:"item_reference",id:_e});break}const ye=typeof de.input=="string"?await mu({text:de.input,schema:Ri}):await Dt({value:de.input,schema:Ri}),Se=ye.call_id!=null?"client":"server";xe.push({type:"tool_search_call",id:_e??de.toolCallId,execution:Se,call_id:(W=ye.call_id)!=null?W:null,status:"completed",arguments:ye.arguments});break}if(de.providerExecuted){m&&_e!=null&&xe.push({type:"item_reference",id:_e});break}if(v&&m&&_e!=null)break;const J=g&&ae==="local_shell"||E&&ae==="shell"||A&&ae==="apply_patch"||((z=D?.has(ae))!=null?z:!1);if(m&&_e!=null&&J){xe.push({type:"item_reference",id:_e});break}if(g&&ae==="local_shell"){const ye=await Dt({value:de.input,schema:Iu});xe.push({type:"local_shell_call",call_id:de.toolCallId,id:_e,action:{type:"exec",command:ye.action.command,timeout_ms:ye.action.timeoutMs,user:ye.action.user,working_directory:ye.action.workingDirectory,env:ye.action.env}});break}if(E&&ae==="shell"){const ye=await Dt({value:de.input,schema:Tu});xe.push({type:"shell_call",call_id:de.toolCallId,id:_e,status:"completed",action:{commands:ye.action.commands,timeout_ms:ye.action.timeoutMs,max_output_length:ye.action.maxOutputLength}});break}if(A&&ae==="apply_patch"){const ye=await Dt({value:de.input,schema:Cu});xe.push({type:"apply_patch_call",call_id:ye.callId,id:_e,status:"completed",operation:ye.operation});break}if(D?.has(ae)){xe.push({type:"custom_tool_call",call_id:de.toolCallId,name:ae,input:typeof de.input=="string"?de.input:JSON.stringify(de.input),id:_e});break}xe.push({type:"function_call",call_id:de.toolCallId,name:ae,arguments:R2(de.input),...Pe!=null&&{namespace:Pe}});break}case"tool-result":{if(de.output.type==="execution-denied"||de.output.type==="json"&&typeof de.output.value=="object"&&de.output.value!=null&&"type"in de.output.value&&de.output.value.type==="execution-denied"||x)break;const _e=r.toProviderToolName(de.toolName);if(_e==="tool_search"){const Pe=(me=(G=(we=de.providerOptions)==null?void 0:we[c])==null?void 0:G.itemId)!=null?me:de.toolCallId;if(m)xe.push({type:"item_reference",id:Pe});else if(de.output.type==="json"){const ae=await Dt({value:de.output.value,schema:Mi});xe.push({type:"tool_search_output",id:Pe,execution:"server",call_id:null,status:"completed",tools:ae.tools})}break}if(E&&_e==="shell"){if(de.output.type==="json"){const Pe=await Dt({value:de.output.value,schema:ki});xe.push({type:"shell_call_output",call_id:de.toolCallId,output:Pe.output.map(ae=>({stdout:ae.stdout,stderr:ae.stderr,outcome:ae.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ae.outcome.exitCode}}))})}break}if(m){const Pe=(q=(te=(fe=de.providerOptions)==null?void 0:fe[c])==null?void 0:te.itemId)!=null?q:de.toolCallId;xe.push({type:"item_reference",id:Pe})}else $e.push({type:"other",message:`Results for OpenAI tool ${de.toolName} are not sent to the API when store is false`});break}case"reasoning":{const _e=await An({provider:c,providerOptions:de.providerOptions,schema:D2}),Pe=_e?.itemId;if((x||v)&&Pe!=null)break;if(Pe!=null){const ae=ie[Pe];if(m)ae===void 0&&(xe.push({type:"item_reference",id:Pe}),ie[Pe]={type:"reasoning",id:Pe,summary:[]});else{const J=[];de.text.length>0?J.push({type:"summary_text",text:de.text}):ae!==void 0&&$e.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(de)}.`}),ae===void 0?(ie[Pe]={type:"reasoning",id:Pe,encrypted_content:_e?.reasoningEncryptedContent,summary:J},xe.push(ie[Pe])):(ae.summary.push(...J),_e?.reasoningEncryptedContent!=null&&(ae.encrypted_content=_e.reasoningEncryptedContent))}}else{const ae=_e?.reasoningEncryptedContent;if(ae!=null){const J=[];de.text.length>0&&J.push({type:"summary_text",text:de.text}),xe.push({type:"reasoning",encrypted_content:ae,summary:J})}else $e.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(de)}.`})}break}}break}case"tool":{for(const ie of qe){if(ie.type==="tool-approval-response"){const ae=ie;if(Ue.has(ae.approvalId))continue;Ue.add(ae.approvalId),m&&xe.push({type:"item_reference",id:ae.approvalId}),xe.push({type:"mcp_approval_response",approval_request_id:ae.approvalId,approve:ae.approved});continue}const de=ie.output;if(de.type==="execution-denied"&&((le=(ke=de.providerOptions)==null?void 0:ke.openai)==null?void 0:le.approvalId))continue;const _e=r.toProviderToolName(ie.toolName);if(_e==="tool_search"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Mi});xe.push({type:"tool_search_output",execution:"client",call_id:ie.toolCallId,status:"completed",tools:ae.tools});continue}if(g&&_e==="local_shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:Su});xe.push({type:"local_shell_call_output",call_id:ie.toolCallId,output:ae.output});continue}if(E&&_e==="shell"&&de.type==="json"){const ae=await Dt({value:de.value,schema:ki});xe.push({type:"shell_call_output",call_id:ie.toolCallId,output:ae.output.map(J=>({stdout:J.stdout,stderr:J.stderr,outcome:J.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:J.outcome.exitCode}}))});continue}if(A&&ie.toolName==="apply_patch"&&de.type==="json"){const ae=await Dt({value:de.value,schema:bu});xe.push({type:"apply_patch_call_output",call_id:ie.toolCallId,status:ae.status,output:ae.output});continue}if(D?.has(_e)){let ae;switch(de.type){case"text":case"error-text":ae=de.value;break;case"execution-denied":ae=(Te=de.reason)!=null?Te:"Tool call execution denied.";break;case"json":case"error-json":ae=JSON.stringify(de.value);break;case"content":ae=de.value.map(J=>{var ye,Se,Ve,St,vt;const et=Nr(J.providerOptions,c);switch(J.type){case"text":return{type:"input_text",text:J.text,...et!=null&&{prompt_cache_breakpoint:et}};case"image-data":return{type:"input_image",image_url:`data:${J.mediaType};base64,${J.data}`,detail:(Se=(ye=J.providerOptions)==null?void 0:ye[c])==null?void 0:Se.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"image-url":return{type:"input_image",image_url:J.url,detail:(St=(Ve=J.providerOptions)==null?void 0:Ve[c])==null?void 0:St.imageDetail,...et!=null&&{prompt_cache_breakpoint:et}};case"file-data":return{type:"input_file",filename:(vt=J.filename)!=null?vt:"data",file_data:`data:${J.mediaType};base64,${J.data}`,...et!=null&&{prompt_cache_breakpoint:et}};case"file-url":return{type:"input_file",file_url:J.url,...et!=null&&{prompt_cache_breakpoint:et}};default:$e.push({type:"other",message:`unsupported custom tool content part type: ${J.type}`});return}}).filter(Ia);break;default:ae=""}xe.push({type:"custom_tool_call_output",call_id:ie.toolCallId,output:ae});continue}let Pe;switch(de.type){case"text":case"error-text":Pe=de.value;break;case"execution-denied":Pe=(Je=de.reason)!=null?Je:"Tool call execution denied.";break;case"json":case"error-json":Pe=JSON.stringify(de.value);break;case"content":Pe=de.value.map(ae=>{var J,ye,Se,Ve,St;const vt=Nr(ae.providerOptions,c);switch(ae.type){case"text":return{type:"input_text",text:ae.text,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-data":return{type:"input_image",image_url:`data:${ae.mediaType};base64,${ae.data}`,detail:(ye=(J=ae.providerOptions)==null?void 0:J[c])==null?void 0:ye.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"image-url":return{type:"input_image",image_url:ae.url,detail:(Ve=(Se=ae.providerOptions)==null?void 0:Se[c])==null?void 0:Ve.imageDetail,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-data":return{type:"input_file",filename:(St=ae.filename)!=null?St:"data",file_data:`data:${ae.mediaType};base64,${ae.data}`,...vt!=null&&{prompt_cache_breakpoint:vt}};case"file-url":return{type:"input_file",file_url:ae.url,...vt!=null&&{prompt_cache_breakpoint:vt}};default:{$e.push({type:"other",message:`unsupported tool content part type: ${ae.type}`});return}}}).filter(Ia);break}xe.push({type:"function_call_output",call_id:ie.toolCallId,output:Pe})}break}default:{const ie=Ze;throw new Error(`Unsupported role: ${ie}`)}}return!m&&xe.some(Ze=>"type"in Ze&&Ze.type==="reasoning"&&Ze.encrypted_content==null)&&($e.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),xe=xe.filter(Ze=>!("type"in Ze)||Ze.type!=="reasoning"||Ze.encrypted_content!=null)),{input:xe,warnings:$e}}var D2=N({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function gi({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 ro=Wi(()=>st([w(),j(),Mt(),bc(),ue(ro),wt(w(),ro.optional())])),P2=N({type:Y("error"),sequence_number:j(),error:N({type:w(),code:w(),message:w(),param:w().nullish()})}),B2=N({type:Y("error"),sequence_number:j(),code:w().nullish(),message:w(),param:w().nullish()}),L2=Fe(()=>Le(st([N({type:Y("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish()}),N({type:Ae(["response.completed","response.incomplete"]),response:N({incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.failed"),sequence_number:j(),response:N({error:N({code:w().nullish(),message:w()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).nullish(),reasoning:N({context:w().nullish()}).nullish(),service_tier:w().nullish()})}),N({type:Y("response.created"),response:N({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),N({type:Y("response.output_item.added"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),namespace:w().nullish()}),N({type:Y("web_search_call"),id:w(),status:w()}),N({type:Y("computer_call"),id:w(),status:w()}),N({type:Y("file_search_call"),id:w()}),N({type:Y("image_generation_call"),id:w()}),N({type:Y("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable(),status:w()}),N({type:Y("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w()}),N({type:Y("mcp_approval_request"),id:w()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.output_item.done"),output_index:j(),item:mt("type",[N({type:Y("message"),id:w(),phase:Ae(["commentary","final_answer"]).nullish()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish()}),N({type:Y("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:Y("completed"),namespace:w().nullish()}),N({type:Y("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:Y("completed")}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("computer_call"),id:w(),status:Y("completed")}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])}),N({type:Y("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),N({type:Y("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),N({type:Y("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),N({type:Y("response.output_text.annotation.added"),annotation:mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})])}),N({type:Y("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),N({type:Y("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),N({type:Y("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),N({type:Y("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),N({type:Y("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),P2,B2,N({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),F2=Fe(()=>Le(N({id:w().optional(),created_at:j().optional(),error:N({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(mt("type",[N({type:Y("message"),role:Y("assistant"),id:w(),phase:Ae(["commentary","final_answer"]).nullish(),content:ue(N({type:Y("output_text"),text:w(),logprobs:ue(N({token:w(),logprob:j(),top_logprobs:ue(N({token:w(),logprob:j()}))})).nullish(),annotations:ue(mt("type",[N({type:Y("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),N({type:Y("file_citation"),file_id:w(),filename:w(),index:j()}),N({type:Y("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),N({type:Y("file_path"),file_id:w(),index:j()})]))}))}),N({type:Y("web_search_call"),id:w(),status:w(),action:mt("type",[N({type:Y("search"),query:w().nullish(),queries:ue(w()).nullish(),sources:ue(mt("type",[N({type:Y("url"),url:w()}),N({type:Y("api"),name:w()})])).nullish()}),N({type:Y("open_page"),url:w().nullish()}),N({type:Y("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),N({type:Y("file_search_call"),id:w(),queries:ue(w()),results:ue(N({attributes:wt(w(),st([w(),j(),Mt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),N({type:Y("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(mt("type",[N({type:Y("logs"),logs:w()}),N({type:Y("image"),url:w()})])).nullable()}),N({type:Y("image_generation_call"),id:w(),result:w()}),N({type:Y("local_shell_call"),id:w(),call_id:w(),action:N({type:Y("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:wt(w(),w()).optional()})}),N({type:Y("function_call"),call_id:w(),name:w(),arguments:w(),id:w(),namespace:w().nullish()}),N({type:Y("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),N({type:Y("computer_call"),id:w(),status:w().optional()}),N({type:Y("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(N({type:Y("summary_text"),text:w()}))}),N({type:Y("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),N({type:Y("mcp_list_tools"),id:w(),server_label:w(),tools:ue(N({name:w(),description:w().optional(),input_schema:xr(),annotations:wt(w(),Cn()).optional()})),error:st([w(),N({type:w().optional(),code:st([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),N({type:Y("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),N({type:Y("apply_patch_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed"]),operation:mt("type",[N({type:Y("create_file"),path:w(),diff:w()}),N({type:Y("delete_file"),path:w()}),N({type:Y("update_file"),path:w(),diff:w()})])}),N({type:Y("shell_call"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),action:N({commands:ue(w())})}),N({type:Y("shell_call_output"),id:w(),call_id:w(),status:Ae(["in_progress","completed","incomplete"]),output:ue(N({stdout:w(),stderr:w(),outcome:mt("type",[N({type:Y("timeout")}),N({type:Y("exit"),exit_code:j()})])}))}),N({type:Y("tool_search_call"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),arguments:Cn()}),N({type:Y("tool_search_output"),id:w(),execution:Ae(["server","client"]),call_id:w().nullable(),status:Ae(["in_progress","completed","incomplete"]),tools:ue(wt(w(),ro.optional()))})])).optional(),service_tier:w().nullish(),reasoning:N({context:w().nullish()}).nullish(),incomplete_details:N({reason:w()}).nullish(),usage:N({input_tokens:j(),input_tokens_details:N({cached_tokens:j().nullish(),cache_write_tokens:j().nullish(),orchestration_input_tokens:j().nullish(),orchestration_input_cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:N({reasoning_tokens:j().nullish(),orchestration_output_tokens:j().nullish()}).nullish()}).optional()}))),Nu=20,Za=Fe(()=>Le(N({conversation:w().nullish(),include:ue(Ae(["reasoning.encrypted_content","file_search_call.results","web_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:st([Mt(),j().min(1).max(Nu)]).optional(),maxToolCalls:j().nullish(),metadata:xr().nullish(),parallelToolCalls:Mt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheOptions:N({mode:Ae(["implicit","explicit"]).optional(),ttl:Y("30m").optional()}).optional(),promptCacheRetention:Ae(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningMode:Ae(["standard","pro"]).optional(),reasoningContext:Ae(["auto","current_turn","all_turns"]).optional(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Ae(["auto","flex","priority","default"]).nullish(),store:Mt().nullish(),passThroughUnsupportedFiles:Mt().optional(),strictJsonSchema:Mt().nullish(),textVerbosity:Ae(["low","medium","high"]).nullish(),truncation:Ae(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Ae(["system","developer","remove"]).optional(),forceReasoning:Mt().optional(),allowedTools:N({toolNames:ue(w()).min(1),mode:Ae(["auto","required"]).optional()}).optional()})));async function U2({tools:t,toolChoice:r,allowedTools:i,toolNameMapping:c,customProviderToolNames:d}){var f,m,x;t=t?.length?t:void 0;const v=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:v};const g=[],E=new Map,A=d??new Set;for(const T of t)switch(T.type){case"function":{const S=(f=T.providerOptions)==null?void 0:f.openai,P=z2({tool:T,options:S}),M=S?.namespace;if(M==null)g.push(P);else{let ee=E.get(M.name);if(ee==null)ee={type:"namespace",name:M.name,description:M.description,tools:[]},E.set(M.name,ee),g.push(ee);else if(ee.description!==M.description)throw new Mn({functionality:`conflicting descriptions for OpenAI tool namespace "${M.name}"`});ee.tools.push(P)}break}case"provider":{switch(T.id){case"openai.file_search":{const S=await Dt({value:T.args,schema:n2});g.push({type:"file_search",vector_store_ids:S.vectorStoreIds,max_num_results:S.maxNumResults,ranking_options:S.ranking?{ranker:S.ranking.ranker,score_threshold:S.ranking.scoreThreshold}:void 0,filters:S.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const S=await Dt({value:T.args,schema:f2});g.push({type:"shell",...S.environment&&{environment:V2(S.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const S=await Dt({value:T.args,schema:C2});g.push({type:"web_search_preview",search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.web_search":{const S=await Dt({value:T.args,schema:x2});g.push({type:"web_search",filters:S.filters!=null?{allowed_domains:S.filters.allowedDomains}:void 0,external_web_access:S.externalWebAccess,search_context_size:S.searchContextSize,user_location:S.userLocation});break}case"openai.code_interpreter":{const S=await Dt({value:T.args,schema:Xg});g.push({type:"code_interpreter",container:S.container==null?{type:"auto",file_ids:void 0}:typeof S.container=="string"?S.container:{type:"auto",file_ids:S.container.fileIds}});break}case"openai.image_generation":{const S=await Dt({value:T.args,schema:i2});g.push({type:"image_generation",background:S.background,input_fidelity:S.inputFidelity,input_image_mask:S.inputImageMask?{file_id:S.inputImageMask.fileId,image_url:S.inputImageMask.imageUrl}:void 0,model:S.model,moderation:S.moderation,partial_images:S.partialImages,quality:S.quality,output_compression:S.outputCompression,output_format:S.outputFormat,size:S.size});break}case"openai.mcp":{const S=await Dt({value:T.args,schema:I2}),P=$=>({tool_names:$.toolNames}),M=S.requireApproval,ee=M==null?void 0:typeof M=="string"?M:M.never!=null?{never:P(M.never)}:void 0;g.push({type:"mcp",server_label:S.serverLabel,allowed_tools:Array.isArray(S.allowedTools)?S.allowedTools:S.allowedTools?{read_only:S.allowedTools.readOnly,tool_names:S.allowedTools.toolNames}:void 0,authorization:S.authorization,connector_id:S.connectorId,headers:S.headers,require_approval:ee??"never",server_description:S.serverDescription,server_url:S.serverUrl});break}case"openai.custom":{const S=await Dt({value:T.args,schema:Jg});g.push({type:"custom",name:S.name,description:S.description,format:S.format}),A.add(S.name);break}case"openai.tool_search":{const S=await Dt({value:T.args,schema:p2});g.push({type:"tool_search",...S.execution!=null?{execution:S.execution}:{},...S.description!=null?{description:S.description}:{},...S.parameters!=null?{parameters:S.parameters}:{}});break}}break}default:v.push({type:"unsupported",feature:`function tool ${T}`});break}if(i!=null)return{tools:g,toolChoice:{type:"allowed_tools",mode:(m=i.mode)!=null?m:"auto",tools:i.toolNames.map(T=>{var S;return{type:"function",name:(S=c?.toProviderToolName(T))!=null?S:T}})},toolWarnings:v};if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:v};const D=r.type;switch(D){case"auto":case"none":case"required":return{tools:g,toolChoice:D,toolWarnings:v};case"tool":{const T=(x=c?.toProviderToolName(r.toolName))!=null?x:r.toolName;return{tools:g,toolChoice:T==="code_interpreter"||T==="file_search"||T==="image_generation"||T==="web_search_preview"||T==="web_search"||T==="mcp"||T==="apply_patch"?{type:T}:A.has(T)?{type:"custom",name:T}:{type:"function",name:T},toolWarnings:v}}default:{const T=D;throw new Mn({functionality:`tool choice type: ${T}`})}}}function z2({tool:t,options:r}){const i=r?.deferLoading;return{type:"function",name:t.name,description:t.description,parameters:t.inputSchema,...t.strict!=null?{strict:t.strict}:{},...i!=null?{defer_loading:i}:{}}}function V2(t){if(t.type==="containerReference")return{type:"container_reference",container_id:t.containerId};if(t.type==="containerAuto"){const i=t;return{type:"container_auto",file_ids:i.fileIds,memory_limit:i.memoryLimit,network_policy:i.networkPolicy==null?void 0:i.networkPolicy.type==="disabled"?{type:"disabled"}:{type:"allowlist",allowed_domains:i.networkPolicy.allowedDomains,domain_secrets:i.networkPolicy.domainSecrets},skills:Z2(i.skills)}}return{type:"local",skills:t.skills}}function Z2(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 $a(t){var r,i;const c={};for(const d of t)if(d.role==="assistant")for(const f of d.content){if(f.type!=="tool-call")continue;const m=(i=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:i.approvalRequestId;m!=null&&(c[m]=f.toolCallId)}return c}var $2=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:i,topP:c,topK:d,presencePenalty:f,frequencyPenalty:m,seed:x,prompt:v,providerOptions:g,tools:E,toolChoice:A,responseFormat:D}){var T,S,P,M,ee,$,F,re,Z,B,L;const W=[],z=_u(this.modelId);d!=null&&W.push({type:"unsupported",feature:"topK"}),x!=null&&W.push({type:"unsupported",feature:"seed"}),f!=null&&W.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&W.push({type:"unsupported",feature:"frequencyPenalty"}),i!=null&&W.push({type:"unsupported",feature:"stopSequences"});const we=this.config.provider.includes("azure")?"azure":"openai";let G=await An({provider:we,providerOptions:g,schema:Za});G==null&&we!=="openai"&&(G=await An({provider:"openai",providerOptions:g,schema:Za}));const me=(T=G?.forceReasoning)!=null?T:z.isReasoningModel;G?.conversation&&G?.previousResponseId&&W.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const fe=Gp({tools:E,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","openai.tool_search":"tool_search"},resolveProviderToolName:ae=>ae.id==="openai.custom"?ae.args.name:void 0}),te=new Set,{tools:q,toolChoice:ke,toolWarnings:le}=await U2({tools:E,toolChoice:A,allowedTools:(S=G?.allowedTools)!=null?S:void 0,toolNameMapping:fe,customProviderToolNames:te}),{input:Te,warnings:Je}=await M2({prompt:v,toolNameMapping:fe,systemMessageMode:(P=G?.systemMessageMode)!=null?P:me?"developer":z.systemMessageMode,providerOptionsName:we,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:(M=G?.passThroughUnsupportedFiles)!=null?M:!1,store:(ee=G?.store)!=null?ee:!0,hasConversation:G?.conversation!=null,hasPreviousResponseId:G?.previousResponseId!=null,hasLocalShellTool:Ze("openai.local_shell"),hasShellTool:Ze("openai.shell"),hasApplyPatchTool:Ze("openai.apply_patch"),customProviderToolNames:te.size>0?te:void 0});W.push(...Je);const xe=($=G?.strictJsonSchema)!=null?$:!0;let $e=G?.include;function Ue(ae){$e==null?$e=[ae]:$e.includes(ae)||($e=[...$e,ae])}function Ze(ae){return E?.find(J=>J.type==="provider"&&J.id===ae)!=null}const qe=typeof G?.logprobs=="number"?G?.logprobs:G?.logprobs===!0?Nu:void 0;qe&&Ue("message.output_text.logprobs");const ze=(F=E?.find(ae=>ae.type==="provider"&&(ae.id==="openai.web_search"||ae.id==="openai.web_search_preview")))==null?void 0:F.name;ze&&Ue("web_search_call.action.sources"),Ze("openai.code_interpreter")&&Ue("code_interpreter_call.outputs");const ie=G?.store;ie===!1&&me&&Ue("reasoning.encrypted_content");const de={model:this.modelId,input:Te,temperature:r,top_p:c,max_output_tokens:t,...(D?.type==="json"||G?.textVerbosity)&&{text:{...D?.type==="json"&&{format:D.schema!=null?{type:"json_schema",strict:xe,name:(re=D.name)!=null?re:"response",description:D.description,schema:D.schema}:{type:"json_object"}},...G?.textVerbosity&&{verbosity:G.textVerbosity}}},conversation:G?.conversation,max_tool_calls:G?.maxToolCalls,metadata:G?.metadata,parallel_tool_calls:G?.parallelToolCalls,previous_response_id:G?.previousResponseId,store:ie,user:G?.user,instructions:G?.instructions,service_tier:G?.serviceTier,include:$e,prompt_cache_key:G?.promptCacheKey,prompt_cache_options:G?.promptCacheOptions,prompt_cache_retention:G?.promptCacheRetention,safety_identifier:G?.safetyIdentifier,top_logprobs:qe,truncation:G?.truncation,...me&&(G?.reasoningEffort!=null||G?.reasoningSummary!=null||G?.reasoningMode!=null||G?.reasoningContext!=null)&&{reasoning:{...G?.reasoningEffort!=null&&{effort:G.reasoningEffort},...G?.reasoningSummary!=null&&{summary:G.reasoningSummary},...G?.reasoningMode!=null&&{mode:G.reasoningMode},...G?.reasoningContext!=null&&{context:G.reasoningContext}}}};me?G?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(de.temperature!=null&&(de.temperature=void 0,W.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),de.top_p!=null&&(de.top_p=void 0,W.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(G?.reasoningEffort!=null&&W.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),G?.reasoningSummary!=null&&W.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"}),G?.reasoningMode!=null&&W.push({type:"unsupported",feature:"reasoningMode",details:"reasoningMode is not supported for non-reasoning models"}),G?.reasoningContext!=null&&W.push({type:"unsupported",feature:"reasoningContext",details:"reasoningContext is not supported for non-reasoning models"})),G?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(W.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete de.service_tier),G?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(W.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 de.service_tier);const _e=(L=(B=(Z=E?.find(ae=>ae.type==="provider"&&ae.id==="openai.shell"))==null?void 0:Z.args)==null?void 0:B.environment)==null?void 0:L.type,Pe=_e==="containerAuto"||_e==="containerReference";return{webSearchToolName:ze,args:{...de,tools:q,tool_choice:ke},warnings:[...W,...le],store:ie,toolNameMapping:fe,providerOptionsName:we,isShellProviderExecuted:Pe}}async doGenerate(t){var r,i,c,d,f,m,x,v,g,E,A,D,T,S,P,M,ee,$,F,re,Z,B,L,W,z,we,G,me,fe;const{args:te,warnings:q,webSearchToolName:ke,toolNameMapping:le,providerOptionsName:Te,isShellProviderExecuted:Je}=await this.getArgs(t),xe=this.config.url({path:"/responses",modelId:this.modelId}),$e=$a(t.prompt),{responseHeaders:Ue,value:Ze,rawValue:qe}=await Zn({url:xe,headers:bn(this.config.headers(),t.headers),body:te,failedResponseHandler:En,successfulResponseHandler:mr(F2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Ze.error)throw new Kt({message:Ze.error.message,url:xe,requestBodyValues:te,statusCode:400,responseHeaders:Ue,responseBody:qe,isRetryable:!1});const ze=[],ie=[];let de=!1;const _e=[];for(const J of Ze.output)switch(J.type){case"reasoning":{J.summary.length===0&&J.summary.push({type:"summary_text",text:""});for(const ye of J.summary)ze.push({type:"reasoning",text:ye.text,providerMetadata:{[Te]:{itemId:J.id,reasoningEncryptedContent:(r=J.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("image_generation"),result:{result:J.result}});break}case"tool_search_call":{const ye=(i=J.call_id)!=null?i:J.id,Se=J.execution==="server";Se&&_e.push(ye),ze.push({type:"tool-call",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),input:JSON.stringify({arguments:J.arguments,call_id:J.call_id}),...Se?{providerExecuted:!0}:{},providerMetadata:{[Te]:{itemId:J.id}}});break}case"tool_search_output":{const ye=(d=(c=J.call_id)!=null?c:_e.shift())!=null?d:J.id;ze.push({type:"tool-result",toolCallId:ye,toolName:le.toCustomToolName("tool_search"),result:{tools:J.tools},providerMetadata:{[Te]:{itemId:J.id}}});break}case"local_shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("local_shell"),input:JSON.stringify({action:J.action}),providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),input:JSON.stringify({action:{commands:J.action.commands}}),...Je&&{providerExecuted:!0},providerMetadata:{[Te]:{itemId:J.id}}});break}case"shell_call_output":{ze.push({type:"tool-result",toolCallId:J.call_id,toolName:le.toCustomToolName("shell"),result:{output:J.output.map(ye=>({stdout:ye.stdout,stderr:ye.stderr,outcome:ye.outcome.type==="exit"?{type:"exit",exitCode:ye.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const ye of J.content){(m=(f=t.providerOptions)==null?void 0:f[Te])!=null&&m.logprobs&&ye.logprobs&&ie.push(ye.logprobs);const Se={itemId:J.id,...J.phase!=null&&{phase:J.phase},...ye.annotations.length>0&&{annotations:ye.annotations}};ze.push({type:"text",text:ye.text,providerMetadata:{[Te]:Se}});for(const Ve of ye.annotations)Ve.type==="url_citation"?ze.push({type:"source",sourceType:"url",id:(g=(v=(x=this.config).generateId)==null?void 0:v.call(x))!=null?g:rn(),url:Ve.url,title:Ve.title}):Ve.type==="file_citation"?ze.push({type:"source",sourceType:"document",id:(D=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?D:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}}):Ve.type==="container_file_citation"?ze.push({type:"source",sourceType:"document",id:(P=(S=(T=this.config).generateId)==null?void 0:S.call(T))!=null?P:rn(),mediaType:"text/plain",title:Ve.filename,filename:Ve.filename,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,containerId:Ve.container_id}}}):Ve.type==="file_path"&&ze.push({type:"source",sourceType:"document",id:($=(ee=(M=this.config).generateId)==null?void 0:ee.call(M))!=null?$:rn(),mediaType:"application/octet-stream",title:Ve.file_id,filename:Ve.file_id,providerMetadata:{[Te]:{type:Ve.type,fileId:Ve.file_id,index:Ve.index}}})}break}case"function_call":{de=!0,ze.push({type:"tool-call",toolCallId:J.call_id,toolName:J.name,input:J.arguments,providerMetadata:{[Te]:{itemId:J.id,...J.namespace!=null&&{namespace:J.namespace}}}});break}case"custom_tool_call":{de=!0;const ye=le.toCustomToolName(J.name);ze.push({type:"tool-call",toolCallId:J.call_id,toolName:ye,input:JSON.stringify(J.input),providerMetadata:{[Te]:{itemId:J.id}}});break}case"web_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName(ke??"web_search"),result:Ga(J.action)});break}case"mcp_call":{const ye=J.approval_request_id!=null&&(F=$e[J.approval_request_id])!=null?F:J.id,Se=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:ye,toolName:Se,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-result",toolCallId:ye,toolName:Se,result:{type:"call",serverLabel:J.server_label,name:J.name,arguments:J.arguments,...J.output!=null?{output:J.output}:{},...J.error!=null?{error:J.error}:{}},providerMetadata:{[Te]:{itemId:J.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const ye=(re=J.approval_request_id)!=null?re:J.id,Se=(L=(B=(Z=this.config).generateId)==null?void 0:B.call(Z))!=null?L:rn(),Ve=`mcp.${J.name}`;ze.push({type:"tool-call",toolCallId:Se,toolName:Ve,input:J.arguments,providerExecuted:!0,dynamic:!0}),ze.push({type:"tool-approval-request",approvalId:ye,toolCallId:Se});break}case"computer_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:J.status||"completed"}});break}case"file_search_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("file_search"),result:{queries:J.queries,results:(z=(W=J.results)==null?void 0:W.map(ye=>({attributes:ye.attributes,fileId:ye.file_id,filename:ye.filename,score:ye.score,text:ye.text})))!=null?z:null}});break}case"code_interpreter_call":{ze.push({type:"tool-call",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),input:JSON.stringify({code:J.code,containerId:J.container_id}),providerExecuted:!0}),ze.push({type:"tool-result",toolCallId:J.id,toolName:le.toCustomToolName("code_interpreter"),result:{outputs:J.outputs}});break}case"apply_patch_call":{ze.push({type:"tool-call",toolCallId:J.call_id,toolName:le.toCustomToolName("apply_patch"),input:JSON.stringify({callId:J.call_id,operation:J.operation}),providerMetadata:{[Te]:{itemId:J.id}}});break}}const Pe={[Te]:{responseId:Ze.id,...ie.length>0?{logprobs:ie}:{},...typeof Ze.service_tier=="string"?{serviceTier:Ze.service_tier}:{},...((we=Ze.reasoning)==null?void 0:we.context)!=null?{reasoningContext:Ze.reasoning.context}:{}}},ae=Ze.usage;return{content:ze,finishReason:{unified:gi({finishReason:(G=Ze.incomplete_details)==null?void 0:G.reason,hasFunctionCall:de}),raw:(fe=(me=Ze.incomplete_details)==null?void 0:me.reason)!=null?fe:void 0},usage:za(ae),request:{body:te},response:{id:Ze.id,timestamp:new Date(Ze.created_at*1e3),modelId:Ze.model,headers:Ue,body:qe},providerMetadata:Pe,warnings:q}}async doStream(t){const{args:r,warnings:i,webSearchToolName:c,toolNameMapping:d,store:f,providerOptionsName:m,isShellProviderExecuted:x}=await this.getArgs(t),v=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:g,value:E}=await Zn({url:v,headers:bn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:En,successfulResponseHandler:Ji(L2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=await es({stream:E,getError:fe=>Wa(fe)||ja(fe)&&fe.response.error!=null?fe:void 0,isOutputChunk:ix,url:v,requestBodyValues:r,responseHeaders:g}),D=this,T=$a(t.prompt),S=new Map;let P={unified:"other",raw:void 0},M;const ee=[];let $=null;const F={},re=[];let Z,B=!1;const L={};let W,z;const we=[];let G=!1;return{stream:A.pipeThrough(new TransformStream({start(fe){fe.enqueue({type:"stream-start",warnings:i})},transform(fe,te){var q,ke,le,Te,Je,xe,$e,Ue,Ze,qe,ze,ie,de,_e,Pe,ae,J,ye,Se,Ve,St,vt,et,nt,Xe,In,be,Bn,$n,qt,jn,Ft,rr,sn,At,or,Ln,wr,gt,ge;if(t.includeRawChunks&&te.enqueue({type:"raw",rawValue:fe.rawValue}),!fe.success){const ne=H2(fe.rawValue)?W2({value:fe.rawValue,cause:fe.error,url:v,requestBodyValues:r,responseHeaders:g}):fe.error;P={unified:"error",raw:void 0},te.enqueue({type:"error",error:ne});return}const O=fe.value;if(Ha(O)){if(O.item.type==="function_call")F[O.output_index]={toolName:O.item.name,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:O.item.name});else if(O.item.type==="custom_tool_call"){const ne=d.toCustomToolName(O.item.name);F[O.output_index]={toolName:ne,toolCallId:O.item.call_id},te.enqueue({type:"tool-input-start",id:O.item.call_id,toolName:ne})}else if(O.item.type==="web_search_call")F[O.output_index]={toolName:d.toCustomToolName(c??"web_search"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName(c??"web_search"),providerExecuted:!0}),te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(O.item.type==="computer_call")F[O.output_index]={toolName:d.toCustomToolName("computer_use"),toolCallId:O.item.id},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("computer_use"),providerExecuted:!0});else if(O.item.type==="code_interpreter_call")F[O.output_index]={toolName:d.toCustomToolName("code_interpreter"),toolCallId:O.item.id,codeInterpreter:{containerId:O.item.container_id}},te.enqueue({type:"tool-input-start",id:O.item.id,toolName:d.toCustomToolName("code_interpreter"),providerExecuted:!0}),te.enqueue({type:"tool-input-delta",id:O.item.id,delta:`{"containerId":"${O.item.container_id}","code":"`});else if(O.item.type==="file_search_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(O.item.type==="tool_search_call"){const ne=O.item.id,Me=d.toCustomToolName("tool_search"),Ee=O.item.execution==="server";F[O.output_index]={toolName:Me,toolCallId:ne,toolSearchExecution:(q=O.item.execution)!=null?q:"server"},Ee&&te.enqueue({type:"tool-input-start",id:ne,toolName:Me,providerExecuted:!0})}else if(O.item.type!=="tool_search_output"){if(!(O.item.type==="mcp_call"||O.item.type==="mcp_list_tools"||O.item.type==="mcp_approval_request"))if(O.item.type==="apply_patch_call"){const{call_id:ne,operation:Me}=O.item;if(F[O.output_index]={toolName:d.toCustomToolName("apply_patch"),toolCallId:ne,applyPatch:{hasDiff:Me.type==="delete_file",endEmitted:Me.type==="delete_file"}},te.enqueue({type:"tool-input-start",id:ne,toolName:d.toCustomToolName("apply_patch")}),Me.type==="delete_file"){const Ee=JSON.stringify({callId:ne,operation:Me});te.enqueue({type:"tool-input-delta",id:ne,delta:Ee}),te.enqueue({type:"tool-input-end",id:ne})}else te.enqueue({type:"tool-input-delta",id:ne,delta:`{"callId":"${fr(ne)}","operation":{"type":"${fr(Me.type)}","path":"${fr(Me.path)}","diff":"`})}else O.item.type==="shell_call"?F[O.output_index]={toolName:d.toCustomToolName("shell"),toolCallId:O.item.call_id}:O.item.type==="shell_call_output"||(O.item.type==="message"?(re.splice(0,re.length),Z=(ke=O.item.phase)!=null?ke:void 0,te.enqueue({type:"text-start",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...O.item.phase!=null&&{phase:O.item.phase}}}})):Ha(O)&&O.item.type==="reasoning"&&(L[O.item.id]={encryptedContent:O.item.encrypted_content,summaryParts:{0:"active"}},te.enqueue({type:"reasoning-start",id:`${O.item.id}:0`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(le=O.item.encrypted_content)!=null?le:null}}})))}}else if(q2(O)){if(O.item.type==="message"){const ne=(Te=O.item.phase)!=null?Te:Z;Z=void 0,te.enqueue({type:"text-end",id:O.item.id,providerMetadata:{[m]:{itemId:O.item.id,...ne!=null&&{phase:ne},...re.length>0&&{annotations:re}}}})}else if(O.item.type==="function_call")F[O.output_index]=void 0,B=!0,te.enqueue({type:"tool-input-end",id:O.item.call_id,...O.item.namespace!=null&&{providerMetadata:{[m]:{namespace:O.item.namespace}}}}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:O.item.name,input:O.item.arguments,providerMetadata:{[m]:{itemId:O.item.id,...O.item.namespace!=null&&{namespace:O.item.namespace}}}});else if(O.item.type==="custom_tool_call"){F[O.output_index]=void 0,B=!0;const ne=d.toCustomToolName(O.item.name);te.enqueue({type:"tool-input-end",id:O.item.call_id}),te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:ne,input:JSON.stringify(O.item.input),providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="web_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName(c??"web_search"),result:Ga(O.item.action)});else if(O.item.type==="computer_call")F[O.output_index]=void 0,te.enqueue({type:"tool-input-end",id:O.item.id}),te.enqueue({type:"tool-call",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:O.item.status||"completed"}});else if(O.item.type==="file_search_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("file_search"),result:{queries:O.item.queries,results:(xe=(Je=O.item.results)==null?void 0:Je.map(ne=>({attributes:ne.attributes,fileId:ne.file_id,filename:ne.filename,score:ne.score,text:ne.text})))!=null?xe:null}});else if(O.item.type==="code_interpreter_call")F[O.output_index]=void 0,te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("code_interpreter"),result:{outputs:O.item.outputs}});else if(O.item.type==="image_generation_call")te.enqueue({type:"tool-result",toolCallId:O.item.id,toolName:d.toCustomToolName("image_generation"),result:{result:O.item.result}});else if(O.item.type==="tool_search_call"){const ne=F[O.output_index],Me=O.item.execution==="server";if(ne!=null){const Ee=Me?ne.toolCallId:($e=O.item.call_id)!=null?$e:O.item.id;Me?we.push(Ee):te.enqueue({type:"tool-input-start",id:Ee,toolName:ne.toolName}),te.enqueue({type:"tool-input-end",id:Ee}),te.enqueue({type:"tool-call",toolCallId:Ee,toolName:ne.toolName,input:JSON.stringify({arguments:O.item.arguments,call_id:Me?null:Ee}),...Me?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:O.item.id}}})}F[O.output_index]=void 0}else if(O.item.type==="tool_search_output"){const ne=(Ze=(Ue=O.item.call_id)!=null?Ue:we.shift())!=null?Ze:O.item.id;te.enqueue({type:"tool-result",toolCallId:ne,toolName:d.toCustomToolName("tool_search"),result:{tools:O.item.tools},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_call"){F[O.output_index]=void 0;const ne=(qe=O.item.approval_request_id)!=null?qe:void 0,Me=ne!=null&&(ie=(ze=S.get(ne))!=null?ze:T[ne])!=null?ie:O.item.id,Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:Me,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-result",toolCallId:Me,toolName:Ee,result:{type:"call",serverLabel:O.item.server_label,name:O.item.name,arguments:O.item.arguments,...O.item.output!=null?{output:O.item.output}:{},...O.item.error!=null?{error:O.item.error}:{}},providerMetadata:{[m]:{itemId:O.item.id}}})}else if(O.item.type==="mcp_list_tools")F[O.output_index]=void 0;else if(O.item.type==="apply_patch_call"){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&O.item.operation.type!=="delete_file"&&(ne.applyPatch.hasDiff||te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.item.operation.diff)}),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0),ne&&O.item.status==="completed"&&te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("apply_patch"),input:JSON.stringify({callId:O.item.call_id,operation:O.item.operation}),providerMetadata:{[m]:{itemId:O.item.id}}}),F[O.output_index]=void 0}else if(O.item.type==="mcp_approval_request"){F[O.output_index]=void 0;const ne=(Pe=(_e=(de=D.config).generateId)==null?void 0:_e.call(de))!=null?Pe:rn(),Me=(ae=O.item.approval_request_id)!=null?ae:O.item.id;S.set(Me,ne);const Ee=`mcp.${O.item.name}`;te.enqueue({type:"tool-call",toolCallId:ne,toolName:Ee,input:O.item.arguments,providerExecuted:!0,dynamic:!0}),te.enqueue({type:"tool-approval-request",approvalId:Me,toolCallId:ne})}else if(O.item.type==="local_shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:O.item.action.command,timeoutMs:O.item.action.timeout_ms,user:O.item.action.user,workingDirectory:O.item.action.working_directory,env:O.item.action.env}}),providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call")F[O.output_index]=void 0,te.enqueue({type:"tool-call",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),input:JSON.stringify({action:{commands:O.item.action.commands}}),...x&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:O.item.id}}});else if(O.item.type==="shell_call_output")te.enqueue({type:"tool-result",toolCallId:O.item.call_id,toolName:d.toCustomToolName("shell"),result:{output:O.item.output.map(ne=>({stdout:ne.stdout,stderr:ne.stderr,outcome:ne.outcome.type==="exit"?{type:"exit",exitCode:ne.outcome.exit_code}:{type:"timeout"}}))}});else if(O.item.type==="reasoning"){const ne=L[O.item.id],Me=Object.entries(ne.summaryParts).filter(([Ee,Oe])=>Oe==="active"||Oe==="can-conclude").map(([Ee])=>Ee);for(const Ee of Me)te.enqueue({type:"reasoning-end",id:`${O.item.id}:${Ee}`,providerMetadata:{[m]:{itemId:O.item.id,reasoningEncryptedContent:(J=O.item.encrypted_content)!=null?J:null}}});delete L[O.item.id]}}else if(K2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(J2(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:O.delta})}else if(nx(O)){const ne=F[O.output_index];ne?.applyPatch&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)}),ne.applyPatch.hasDiff=!0)}else if(rx(O)){const ne=F[O.output_index];ne?.applyPatch&&!ne.applyPatch.endEmitted&&(ne.applyPatch.hasDiff||(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.diff)}),ne.applyPatch.hasDiff=!0),te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),ne.applyPatch.endEmitted=!0)}else if(Q2(O))te.enqueue({type:"tool-result",toolCallId:O.item_id,toolName:d.toCustomToolName("image_generation"),result:{result:O.partial_image_b64},preliminary:!0});else if(ex(O)){const ne=F[O.output_index];ne!=null&&te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:fr(O.delta)})}else if(tx(O)){const ne=F[O.output_index];ne!=null&&(te.enqueue({type:"tool-input-delta",id:ne.toolCallId,delta:'"}'}),te.enqueue({type:"tool-input-end",id:ne.toolCallId}),te.enqueue({type:"tool-call",toolCallId:ne.toolCallId,toolName:d.toCustomToolName("code_interpreter"),input:JSON.stringify({code:O.code,containerId:ne.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Y2(O))$=O.response.id,te.enqueue({type:"response-metadata",id:O.response.id,timestamp:new Date(O.response.created_at*1e3),modelId:O.response.model});else if(j2(O))te.enqueue({type:"text-delta",id:O.item_id,delta:O.delta}),(Se=(ye=t.providerOptions)==null?void 0:ye[m])!=null&&Se.logprobs&&O.logprobs&&ee.push(O.logprobs);else if(O.type==="response.reasoning_summary_part.added"){if(O.summary_index>0){const ne=L[O.item_id];ne.summaryParts[O.summary_index]="active";for(const Me of Object.keys(ne.summaryParts))ne.summaryParts[Me]==="can-conclude"&&(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${Me}`,providerMetadata:{[m]:{itemId:O.item_id}}}),ne.summaryParts[Me]="concluded");te.enqueue({type:"reasoning-start",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id,reasoningEncryptedContent:(St=(Ve=L[O.item_id])==null?void 0:Ve.encryptedContent)!=null?St:null}}})}}else if(O.type==="response.reasoning_summary_text.delta")te.enqueue({type:"reasoning-delta",id:`${O.item_id}:${O.summary_index}`,delta:O.delta,providerMetadata:{[m]:{itemId:O.item_id}}});else if(O.type==="response.reasoning_summary_part.done")f?(te.enqueue({type:"reasoning-end",id:`${O.item_id}:${O.summary_index}`,providerMetadata:{[m]:{itemId:O.item_id}}}),L[O.item_id].summaryParts[O.summary_index]="concluded"):L[O.item_id].summaryParts[O.summary_index]="can-conclude";else if(X2(O))P={unified:gi({finishReason:(vt=O.response.incomplete_details)==null?void 0:vt.reason,hasFunctionCall:B}),raw:(nt=(et=O.response.incomplete_details)==null?void 0:et.reason)!=null?nt:void 0},M=O.response.usage,typeof O.response.service_tier=="string"&&(W=O.response.service_tier),((Xe=O.response.reasoning)==null?void 0:Xe.context)!=null&&(z=O.response.reasoning.context);else if(ja(O)){const ne=(In=O.response.incomplete_details)==null?void 0:In.reason;P={unified:ne?gi({finishReason:ne,hasFunctionCall:B}):"error",raw:ne??"error"},M=(be=O.response.usage)!=null?be:void 0,((Bn=O.response.reasoning)==null?void 0:Bn.context)!=null&&(z=O.response.reasoning.context),!G&&O.response.error!=null&&(G=!0,te.enqueue({type:"error",error:{type:"response.failed",sequence_number:O.sequence_number,response:{error:O.response.error,incomplete_details:O.response.incomplete_details,service_tier:O.response.service_tier}}}))}else ox(O)?(re.push(O.annotation),O.annotation.type==="url_citation"?te.enqueue({type:"source",sourceType:"url",id:(jn=(qt=($n=D.config).generateId)==null?void 0:qt.call($n))!=null?jn:rn(),url:O.annotation.url,title:O.annotation.title}):O.annotation.type==="file_citation"?te.enqueue({type:"source",sourceType:"document",id:(sn=(rr=(Ft=D.config).generateId)==null?void 0:rr.call(Ft))!=null?sn:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}}):O.annotation.type==="container_file_citation"?te.enqueue({type:"source",sourceType:"document",id:(Ln=(or=(At=D.config).generateId)==null?void 0:or.call(At))!=null?Ln:rn(),mediaType:"text/plain",title:O.annotation.filename,filename:O.annotation.filename,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,containerId:O.annotation.container_id}}}):O.annotation.type==="file_path"&&te.enqueue({type:"source",sourceType:"document",id:(ge=(gt=(wr=D.config).generateId)==null?void 0:gt.call(wr))!=null?ge:rn(),mediaType:"application/octet-stream",title:O.annotation.file_id,filename:O.annotation.file_id,providerMetadata:{[m]:{type:O.annotation.type,fileId:O.annotation.file_id,index:O.annotation.index}}})):Wa(O)&&(G=!0,P={unified:"error",raw:"error"},te.enqueue({type:"error",error:O}))},flush(fe){const te={[m]:{responseId:$,...ee.length>0?{logprobs:ee}:{},...W!==void 0?{serviceTier:W}:{},...z!==void 0?{reasoningContext:z}:{}}};fe.enqueue({type:"finish",finishReason:P,usage:za(M),providerMetadata:te})}})),request:{body:r},response:{headers:g}}}};function j2(t){return t.type==="response.output_text.delta"}function H2(t){const r=G2(t);return r!=null&&Array.isArray(r.choices)&&typeof r.type!="string"}function W2({value:t,cause:r,url:i,requestBodyValues:c,responseHeaders:d}){return new Kt({message:"Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.",url:i,requestBodyValues:c,responseHeaders:d,responseBody:JSON.stringify(t),cause:r,data:t,isRetryable:!1})}function G2(t){return typeof t=="object"&&t!=null?t:void 0}function q2(t){return t.type==="response.output_item.done"}function X2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function ja(t){return t.type==="response.failed"}function Y2(t){return t.type==="response.created"}function K2(t){return t.type==="response.function_call_arguments.delta"}function J2(t){return t.type==="response.custom_tool_call_input.delta"}function Q2(t){return t.type==="response.image_generation_call.partial_image"}function ex(t){return t.type==="response.code_interpreter_call_code.delta"}function tx(t){return t.type==="response.code_interpreter_call_code.done"}function nx(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function rx(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Ha(t){return t.type==="response.output_item.added"}function ox(t){return t.type==="response.output_text.annotation.added"}function Wa(t){return t.type==="error"}function ix(t){return!(t.type==="response.created"||t.type==="response.failed"||t.type==="error"||t.type==="unknown_chunk")}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.queries!=null&&{queries:t.queries}},...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 fr(t){return JSON.stringify(t).slice(1,-1)}var sx=Fe(()=>Le(N({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),ax=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:i="mp3",speed:c,instructions:d,language:f,providerOptions:m}){const x=[],v=await An({provider:"openai",providerOptions:m,schema:sx}),g={model:this.modelId,input:t,voice:r,response_format:"mp3",speed:c,instructions:d};if(i&&(["mp3","opus","aac","flac","wav","pcm"].includes(i)?g.response_format=i:x.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${i}. Using mp3 instead.`})),v){const E={};for(const A in E){const D=E[A];D!==void 0&&(g[A]=D)}}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,i,c;const d=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{requestBody:f,warnings:m}=await this.getArgs(t),{value:x,responseHeaders:v,rawValue:g}=await Zn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:f,failedResponseHandler:En,successfulResponseHandler:xg(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:x,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:d,modelId:this.modelId,headers:v,body:g}}}},lx=Fe(()=>Le(N({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(N({word:w(),start:j(),end:j()})).nullish(),segments:ue(N({id:j(),seek:j(),start:j(),end:j(),text:w(),tokens:ue(j()),temperature:j(),avg_logprob:j(),compression_ratio:j(),no_speech_prob:j()})).nullish()}))),cx=Fe(()=>Le(N({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Ae(["word","segment"])).default(["segment"]).optional()}))),qa={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"},ux=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:i}){const c=[],d=await An({provider:"openai",providerOptions:i,schema:cx}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([qi(t)]);f.append("model",this.modelId);const x=gm(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${x}`),d){const v={include:d.include,language:d.language,prompt:d.prompt,response_format:["gpt-4o-transcribe","gpt-4o-mini-transcribe"].includes(this.modelId)?"json":"verbose_json",temperature:d.temperature,timestamp_granularities:d.timestampGranularities};for(const[g,E]of Object.entries(v))if(E!=null)if(Array.isArray(E))for(const A of E)f.append(`${g}[]`,String(A));else f.append(g,String(E))}return{formData:f,warnings:c}}async doGenerate(t){var r,i,c,d,f,m,x,v;const g=(c=(i=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:i.call(r))!=null?c:new Date,{formData:E,warnings:A}=await this.getArgs(t),{value:D,responseHeaders:T,rawValue:S}=await xu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),formData:E,failedResponseHandler:En,successfulResponseHandler:mr(lx),abortSignal:t.abortSignal,fetch:this.config.fetch}),P=D.language!=null&&D.language in qa?qa[D.language]:void 0;return{text:D.text,segments:(x=(m=(d=D.segments)==null?void 0:d.map(M=>({text:M.text,startSecond:M.start,endSecond:M.end})))!=null?m:(f=D.words)==null?void 0:f.map(M=>({text:M.word,startSecond:M.start,endSecond:M.end})))!=null?x:[],language:P,durationInSeconds:(v=D.duration)!=null?v:void 0,warnings:A,response:{timestamp:g,modelId:this.modelId,headers:T,body:S}}}},dx="3.0.84";function Ou(t={}){var r,i;const c=(r=yg(mm({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",d=(i=t.name)!=null?i:"openai",f=()=>cu({Authorization:`Bearer ${pm({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${dx}`),m=P=>new Tg(P,{provider:`${d}.chat`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),x=P=>new Mg(P,{provider:`${d}.completion`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),v=P=>new Lg(P,{provider:`${d}.embedding`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),g=P=>new $g(P,{provider:`${d}.image`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),E=P=>new ux(P,{provider:`${d}.transcription`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),A=P=>new ax(P,{provider:`${d}.speech`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch}),D=P=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return T(P)},T=P=>new $2(P,{provider:`${d}.responses`,url:({path:M})=>`${c}${M}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),S=function(P){return D(P)};return S.specificationVersion="v3",S.languageModel=D,S.chat=m,S.completion=x,S.responses=T,S.embedding=v,S.embeddingModel=v,S.textEmbedding=v,S.textEmbeddingModel=v,S.image=g,S.imageModel=g,S.transcription=E,S.transcriptionModel=E,S.speech=A,S.speechModel=A,S.tools=k2,S}Ou();const fx={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 hx{constructor(r={}){this.option=r}async traverse(r){const i=_.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",i),(async()=>{let d,f,m,x,v;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":d=_.reactive({running:!0,steps:[]}),i.value=d,this.option.onStart?.(d);break;case"start-step":f=_.reactive({running:!0,contents:[],request:g.request}),d.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":m=_.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=_.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(v),this.option.onTool?.(v);break;case"tool-input-delta":v.inputStr+=g.delta;break;case"tool-input-end":break;case"tool-call":v.input=g.input;break;case"tool-result":v.output=g.output,v.running=!1;break;case"tool-error":v.error=g.error,v.running=!1;break;case"finish-step":f.running=!1,f.finishReason=g.finishReason,f.usage=g.usage;break;case"finish":d.running=!1,d.finishReason=g.finishReason,d.totalUsage=g.totalUsage,this.option.onFinish?.();break;case"source":case"file":break;case"error":d&&(d.running=!1,d.error=g.error,d.finishReason="error"),this.option.onFinish?.();break;case"abort":d&&(d.running=!1,d.error={message:g.reason},d.finishReason="other"),this.option.onFinish?.();break}})(),i}}function px(t){const r=[];let i=0;for(;i<t.length;){const c="```schemaJson",d=t.indexOf(c,i),f=c.length;if(d===-1){const g=t.slice(i).trim();g&&r.push({type:"markdown",content:g});break}const m=t.slice(i,d).trim();m&&r.push({type:"markdown",content:m});const x=t.indexOf("```",d+f);let v;x===-1?(v=t.slice(d+f).trim(),i=t.length):(v=t.slice(d+f,x).trim(),i=x+3),r.push({type:"schema-card",content:v})}return r}class mx{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
56
56
  当前时间:${new Date().toLocaleDateString()}。
57
57
  ${this.staticPrompt}
58
58
  ${this.skillMetaPrompt}
59
59
  ${this.tempPrompt}
60
- `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const po={model:"deepseek-ai/DeepSeek-V3",maxSteps:30,extraTools:{}},$a={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function ix(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 ox extends Qn.BaseModelProvider{transport;agent;promptManager;llmConfig={...po,...$a};isGenuiEnabled;debugStream=!1;emit;constructor(r,o,c,u){super(r);let f;c&&"llm"in c?f={...po,...c}:f={...po,...$a,...c||{}},this.llmConfig=f;const g={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new $n.AgentModelProvider(g),this.promptManager=new rx,this.promptManager.setStatic(o),this.emit=u}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:m,llm:g,providerOptions:v,headers:x}){if(g)this.agent.llm=g,this.llmConfig.model=r,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;else if(f&&o&&u){const E=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=Ic;else if(f==="openai")A=Au;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:u,baseURL:E,...x?{headers:x}:{}})}this.llmConfig.providerOptions=v,this.llmConfig.headers=x}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 g=f[m];g.role===c&&this.isSnapshotContent(g.content)&&this.replaceSnapshotWithPlaceholder(g)}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:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:ix(this.llmConfig.providerOptions,ex),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),B=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ne=>{B.push(...Object.keys(ne||{}))});const D=Array.from(new Set(B)).filter(ne=>!this.agent.ignoreToolnames.includes(ne));return{system:this.promptManager.getSystemPrompt(),messages:S,activeTools:D}},onStepFinish:T=>{if(T.finishReason==="tool-calls"&&T.content.length>0){const S=T.content[T.content.length-1];if(S.toolName==="get_skill_content"&&S.type==="tool-result"){const B=S.output.content;this.promptManager.appendTemp(B)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},g=[...(T=>T.map(S=>({role:S.role,content:S.content})))(this.agent.responseMessages),f];u.messages=g;const v=await this.agent.chatStream(u),x=new Zp,A=await new tx({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{x.resolve(),o.onDone()})}}).traverse(v),M={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)o.onData(M);else{const B=T.steps.map(D=>D.contents).flat().map(D=>{if(D.type==="text")return nx(D.text);if(D.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:D.text,thinkId:D.id};if(D.type==="tool")return{type:"tool",id:D.id,name:D.toolName,content:JSON.stringify({input:D.inputStr,output:D.output}),status:D.error?"failed":D.running?"running":"success"}});if(T?.error){const D={type:"markdown",content:`**错误**:${T.error.responseBody||T.error.message||"未知错误"}`};B.push(D)}(T.steps.length>=1||T?.error)&&o.onData({...M,uiContent:B.flat(),usage:T.totalUsage||null})}},{deep:!0}),x.promise}chat(r){throw new Error("Method not implemented.")}}const sx=({systemPrompt:t,llmConfig:r,emit:o})=>{const c=new ox({provider:"custom"},t,r,o),u=new Qn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:g,switchConversation:v,deleteConversation:x,updateTitle:E,state:A}=Qn.useConversation({client:u,autoSave:!0,events:{onLoaded(){},onReceiveData($,P,L){L(),P.value[P.value.length-1].role==="assistant"&&P.value.pop(),o("before-ai-render",$),P.value.push($)}}}),{messageState:M,inputMessage:T,sendMessage:S,abortRequest:B,messages:D,addMessage:ne,send:z}=f,Z=_.ref(),re=async($,P,L)=>{if(L){const{shouldBlock:U}=await L($);if(U)return!1}T.value=$;const G=g();if(G&&G.title==="新会话"&&E(G.id,T.value.slice(0,15)),P&&P.length>0){const U=[{type:"text",text:T.value},...P],ee=[];T.value&&ee.push({type:"text",content:T.value});for(const ue of P)ue.type==="image"&&ue.image&&ee.push({type:"image",content:ue.image});const Y={role:"user",content:U,uiContent:ee};D.value.push(Y),T.value="",z()}else{const U={role:"user",content:T.value,uiContent:[{type:"text",content:T.value}]};D.value.push(U),T.value="",z()}return!0};return _.onMounted(()=>{Z.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:u,messageManager:f,addMessage:ne,send:z,conversationState:A,messages:D,messageState:M,inputMessage:T,sendMessage:S,abortRequest:B,senderRef:Z,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:x,getCurrentConversation:g}};function ax(){}const Fn=Object.assign,Jo=typeof window<"u",Fi=t=>t!==null&&typeof t=="object",nr=t=>t!=null,Ro=t=>typeof t=="function",lx=t=>Fi(t)&&Ro(t.then)&&Ro(t.catch),Eu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),cx=()=>Jo?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function ja(t,r){const o=r.split(".");let c=t;return o.forEach(u=>{var f;c=Fi(c)&&(f=c[u])!=null?f:""}),c}function ux(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const ki=null,fn=[Number,String],pr={type:Boolean,default:!0},dx=t=>({type:Number,default:t}),hn=t=>({type:String,default:t});var Qo=typeof window<"u";function Iu(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function Su(t,r,o={}){if(!Qo)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let m=!1,g;const v=A=>{if(m)return;const M=_.unref(A);M&&!g&&(M.addEventListener(t,r,{capture:f,passive:u}),g=!0)},x=A=>{if(m)return;const M=_.unref(A);M&&g&&(M.removeEventListener(t,r,f),g=!1)};_.onUnmounted(()=>x(c)),_.onDeactivated(()=>x(c)),Iu(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,M)=>{x(M),v(A)})),()=>{E?.(),x(c),m=!0}}var vi,mo;function fx(){if(!vi&&(vi=_.ref(0),mo=_.ref(0),Qo)){const t=()=>{vi.value=window.innerWidth,mo.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:vi,height:mo}}var hx=/scroll|auto|overlay/i,px=Qo?window:void 0;function mx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ha(t,r=px){let o=t;for(;o&&o!==r&&mx(o);){const{overflowY:c}=window.getComputedStyle(o);if(hx.test(c))return o;o=o.parentNode}return r}cx();const gx=t=>t.stopPropagation();function Tu(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),gx(t)}fx();function bn(t){if(nr(t))return Eu(t)?`${t}px`:String(t)}function xx(t){if(nr(t)){if(Array.isArray(t))return{width:bn(t[0]),height:bn(t[1])};const r=bn(t);return{width:r,height:r}}}function yx(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const wx=/-(\w)/g,Nu=t=>t.replace(wx,(r,o)=>o.toUpperCase()),_x=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:vx}=Object.prototype;function Cx(t,r,o){const c=r[o];nr(c)&&(!vx.call(t,o)||!Fi(c)?t[o]=c:t[o]=Ou(Object(t[o]),c))}function Ou(t,r){return Object.keys(r).forEach(o=>{Cx(t,r,o)}),t}var bx={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",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 Wa=_.ref("zh-CN"),Ga=_.reactive({"zh-CN":bx}),Ax={messages(){return Ga[Wa.value]},use(t,r){Wa.value=t,this.add({[t]:r})},add(t={}){Ou(Ga,t)}};var Ex=Ax;function Ix(t){const r=Nu(t)+".";return(o,...c)=>{const u=Ex.messages(),f=ja(u,r+o)||ja(u,o);return Ro(f)?f(...c):f}}function Mo(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((o,c)=>o+Mo(t,c),""):Object.keys(r).reduce((o,c)=>o+(r[c]?Mo(t,c):""),""):""}function Sx(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Mo(r,o)}`)}function yr(t){const r=`van-${t}`;return[r,Sx(r),Ix(r)]}const Tx="van-haptics-feedback",Xa=5;function Nx(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);lx(f)?f.then(m=>{m?o():c&&c()}).catch(u||ax):f?o():c&&c()}else o()}function oi(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(Nu(`-${o}`),t))},t}const Ox=Symbol();function ku(t){const r=_.getCurrentInstance();r&&Fn(r.proxy,t)}const[kx,qa]=yr("badge"),Rx={dot:Boolean,max:fn,tag:hn("div"),color:String,offset:Array,content:fn,showZero:pr,position:hn("top-right")};var Mx=_.defineComponent({name:kx,props:Rx,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:g,showZero:v}=t;return nr(g)&&g!==""&&(v||g!==0&&g!=="0")},c=()=>{const{dot:g,max:v,content:x}=t;if(!g&&o())return r.content?r.content():nr(v)&&Eu(x)&&+x>+v?`${v}+`:x},u=g=>g.startsWith("-")?g.replace("-",""):`-${g}`,f=_.computed(()=>{const g={background:t.color};if(t.offset){const[v,x]=t.offset,{position:E}=t,[A,M]=E.split("-");r.default?(typeof x=="number"?g[A]=bn(A==="top"?x:-x):g[A]=A==="top"?bn(x):u(x),typeof v=="number"?g[M]=bn(M==="left"?v:-v):g[M]=M==="left"?bn(v):u(v)):(g.marginTop=bn(x),g.marginLeft=bn(v))}return g}),m=()=>{if(o()||t.dot)return _.createVNode("div",{class:qa([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:g}=t;return _.createVNode(g,{class:qa("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const Dx=oi(Mx);let Ru=2e3;const Px=()=>++Ru,Bx=t=>{Ru=t},[Mu,Lx]=yr("config-provider"),Du=Symbol(Mu),Fx={tag:hn("div"),theme:hn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:hn("local"),iconPrefix:String};function Ux(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function zx(t){const r={};return Object.keys(t).forEach(o=>{const c=Ux(_x(o));r[`--van-${c}`]=t[o]}),r}function Ci(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)})}_.defineComponent({name:Mu,props:Fx,setup(t,{slots:r}){const o=_.computed(()=>zx(Fn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(Jo){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},u=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&u(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(u),_.onBeforeUnmount(u),_.watch(o,(f,m)=>{t.themeVarsScope==="global"&&Ci(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Ci({},o.value),f==="global"&&Ci(o.value,{})}),t.themeVarsScope==="global"&&Ci(o.value,{})}return _.provide(Du,t),_.watchEffect(()=>{t.zIndex!==void 0&&Bx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Lx(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[Vx,Ya]=yr("icon"),Zx=t=>t?.includes("/"),$x={dot:Boolean,tag:hn("i"),name:String,size:fn,badge:fn,color:String,badgeProps:Object,classPrefix:String};var jx=_.defineComponent({name:Vx,props:$x,setup(t,{slots:r}){const o=_.inject(Du,null),c=_.computed(()=>t.classPrefix||o?.iconPrefix||Ya());return()=>{const{tag:u,dot:f,name:m,size:g,badge:v,color:x}=t,E=Zx(m);return _.createVNode(Dx,_.mergeProps({dot:f,tag:u,class:[c.value,E?"":`${c.value}-${m}`],style:{color:x,fontSize:bn(g)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&_.createVNode("img",{class:Ya("image"),src:m},null)]}})}}});const es=oi(jx),[Hx,Xr]=yr("loading"),Wx=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Xr("line",String(r+1))},null)),Gx=_.createVNode("svg",{class:Xr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),Xx={size:fn,type:hn("circular"),color:String,vertical:Boolean,textSize:fn,textColor:String};var qx=_.defineComponent({name:Hx,props:Xx,setup(t,{slots:r}){const o=_.computed(()=>Fn({color:t.color},xx(t.size))),c=()=>{const f=t.type==="spinner"?Wx:Gx;return _.createVNode("span",{class:Xr("spinner",t.type),style:o.value},[r.icon?r.icon():f])},u=()=>{var f;if(r.default)return _.createVNode("span",{class:Xr("text"),style:{fontSize:bn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Xr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),u()])}}});const Yx=oi(qx),Kx={show:Boolean,zIndex:fn,overlay:pr,duration:fn,teleport:[String,Object],lockScroll:pr,lazyRender:pr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:ki,transitionAppear:Boolean,closeOnClickOverlay:pr};function Jx(t,r){return t>r?"horizontal":r>t?"vertical":""}function Qx(){const t=_.ref(0),r=_.ref(0),o=_.ref(0),c=_.ref(0),u=_.ref(0),f=_.ref(0),m=_.ref(""),g=_.ref(!0),v=()=>m.value==="vertical",x=()=>m.value==="horizontal",E=()=>{o.value=0,c.value=0,u.value=0,f.value=0,m.value="",g.value=!0};return{move:(T=>{const S=T.touches[0];o.value=(S.clientX<0?0:S.clientX)-t.value,c.value=S.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=Jx(u.value,f.value)),g.value&&(u.value>Xa||f.value>Xa)&&(g.value=!1)}),start:(T=>{E(),t.value=T.touches[0].clientX,r.value=T.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:m,isVertical:v,isHorizontal:x,isTap:g}}let Zr=0;const Ka="van-overflow-hidden";function ey(t,r){const o=Qx(),c="01",u="10",f=E=>{o.move(E);const A=o.deltaY.value>0?u:c;let M=Ha(E.target,t.value);for(;M.scrollHeight<=M.offsetHeight&&M!==t.value&&M.parentElement;)M=Ha(M.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:B}=M;let D="11";B===0?D=S>=T?"00":"01":B+S>=T&&(D="10"),D!=="11"&&o.isVertical()&&!(parseInt(D,2)&parseInt(A,2))&&Tu(E)},m=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),Zr||document.body.classList.add(Ka),Zr++},g=()=>{Zr&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),Zr--,Zr||document.body.classList.remove(Ka))},v=()=>r()&&m(),x=()=>r()&&g();Iu(v),_.onDeactivated(x),_.onBeforeUnmount(x),_.watch(r,E=>{E?m():g()})}function Pu(t){const r=_.ref(!1);return _.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const Ja=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[ty,ny]=yr("overlay"),ry={show:Boolean,zIndex:fn,duration:fn,className:ki,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var iy=_.defineComponent({name:ty,inheritAttrs:!1,props:ry,setup(t,{attrs:r,slots:o}){const c=_.ref(),u=Pu(()=>t.show||!t.lazyRender),f=g=>{t.lockScroll&&Tu(g)},m=u(()=>{var g;const v=Fn(yx(t.zIndex),t.customStyle);return nr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[ny(),t.className]},r),[(g=o.default)==null?void 0:g.call(o)]),[[_.vShow,t.show]])});return Su("touchmove",f,{target:c}),()=>{const g=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[g]}):g}}});const oy=oi(iy),sy=Fn({},Kx,{round:Boolean,position:hn("center"),closeIcon:hn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:hn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[ay,Qa]=yr("popup");var ly=_.defineComponent({name:ay,inheritAttrs:!1,props:sy,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:o,slots:c}){let u,f;const m=_.ref(),g=_.ref(),v=Pu(()=>t.show||!t.lazyRender),x=_.computed(()=>{const P={zIndex:m.value};if(nr(t.duration)){const L=t.position==="center"?"animationDuration":"transitionDuration";P[L]=`${t.duration}s`}return P}),E=()=>{u||(u=!0,m.value=t.zIndex!==void 0?+t.zIndex:Px(),r("open"))},A=()=>{u&&Nx(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},M=P=>{r("clickOverlay",P),t.closeOnClickOverlay&&A()},T=()=>{if(t.overlay){const P=Fn({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 _.createVNode(oy,_.mergeProps(P,Ja(),{onClick:M}),{default:c["overlay-content"]})}},S=P=>{r("clickCloseIcon",P),A()},B=()=>{if(t.closeable)return _.createVNode(es,{role:"button",tabindex:0,name:t.closeIcon,class:[Qa("close-icon",t.closeIconPosition),Tx],classPrefix:t.iconPrefix,onClick:S},null)};let D;const ne=()=>{D&&clearTimeout(D),D=setTimeout(()=>{r("opened")})},z=()=>r("closed"),Z=P=>r("keydown",P),re=v(()=>{var P;const{destroyOnClose:L,round:G,position:U,safeAreaInsetTop:ee,safeAreaInsetBottom:Y,show:ue}=t;if(!(!ue&&L))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:g,style:x.value,role:"dialog",tabindex:0,class:[Qa({round:G,[U]:U}),{"van-safe-area-top":ee,"van-safe-area-bottom":Y}],onKeydown:Z},o,Ja()),[(P=c.default)==null?void 0:P.call(c),B()]),[[_.vShow,ue]])}),$=()=>{const{position:P,transition:L,transitionAppear:G}=t,U=P==="center"?"van-fade":`van-popup-slide-${P}`;return _.createVNode(_.Transition,{name:L||U,appear:G,onAfterEnter:ne,onAfterLeave:z},{default:re})};return _.watch(()=>t.show,P=>{P&&!u&&(E(),o.tabindex===0&&_.nextTick(()=>{var L;(L=g.value)==null||L.focus()})),!P&&u&&(u=!1,r("close"))}),ku({popupRef:g}),ey(g,()=>t.show&&t.lockScroll),Su("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),_.onMounted(()=>{t.show&&E()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),_.provide(Ox,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),$()]}):_.createVNode(_.Fragment,null,[T(),$()])}});const cy=oi(ly);let $r=0;function uy(t){t?($r||document.body.classList.add("van-toast--unclickable"),$r++):$r&&($r--,$r||document.body.classList.remove("van-toast--unclickable"))}const[dy,Tr]=yr("toast"),fy=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],hy={icon:String,show:Boolean,type:hn("text"),overlay:Boolean,message:fn,iconSize:fn,duration:dx(2e3),position:hn("middle"),teleport:[String,Object],wordBreak:String,className:ki,iconPrefix:String,transition:hn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:ki,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:fn};var py=_.defineComponent({name:dy,props:hy,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,uy(u))},m=A=>r("update:show",A),g=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),x=()=>{const{icon:A,type:M,iconSize:T,iconPrefix:S,loadingType:B}=t;if(A||M==="success"||M==="fail")return _.createVNode(es,{name:A||M,size:T,class:Tr("icon"),classPrefix:S},null);if(M==="loading")return _.createVNode(Yx,{class:Tr("loading"),size:T,type:B},null)},E=()=>{const{type:A,message:M}=t;if(o.message)return _.createVNode("div",{class:Tr("text")},[o.message()]);if(nr(M)&&M!=="")return A==="html"?_.createVNode("div",{key:0,class:Tr("text"),innerHTML:String(M)},null):_.createVNode("div",{class:Tr("text")},[M])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(cy,_.mergeProps({class:[Tr([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:g,onClosed:v,"onUpdate:show":m},ux(t,fy)),{default:()=>[x(),E()]})}});function my(){const t=_.reactive({show:!1}),r=u=>{t.show=u},o=u=>{Fn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return ku({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function gy(t){const r=_.createApp(t),o=document.createElement("div");return document.body.appendChild(o),{instance:r.mount(o),unmount(){r.unmount(),document.body.removeChild(o)}}}const xy={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 bi=[],yy=!1,el=Fn({},xy);const wy=new Map;function Bu(t){return Fi(t)?t:{message:t}}function _y(){const{instance:t}=gy({setup(){const r=_.ref(""),{open:o,state:c,close:u,toggle:f}=my(),m=()=>{},g=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(py,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=g,{open:o,close:u,message:r}}});return t}function vy(){if(!bi.length||yy){const t=_y();bi.push(t)}return bi[bi.length-1]}function rt(t={}){if(!Jo)return{};const r=vy(),o=Bu(t);return r.open(Fn({},el,wy.get(o.type||el.type),o)),r}const Cy=t=>r=>rt(Fn({type:t},Bu(r))),Lu=Cy("loading"),by=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=Ay(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},Ay=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:o,sessionId:c,headers:u}=t;return r==="extension"?c?{type:"extension",url:o,sessionId:c,headers:u,useAISdkClient:!0}:null:r==="streamableHttp"||r==="sse"?{type:r,url:o,headers:u,useAISdkClient:!0}:{type:"streamableHttp",url:o,headers:u,useAISdkClient:!0}},Ey=(t,r,o)=>{const c=async(f,m,g,v,x)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const T={id:`plugin-${f.replace("mcp-server-","")}`,name:g,icon:x||o,description:v||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(S=>({id:S,name:S,description:A[S].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(T),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{Lu("添加工具中...");try{if(f==="code"){if(typeof m!="string"){rt("添加工具失败:code 类型需要 JSON 字符串格式");return}const z=by(m);if(z.length===0){rt("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let Z=0,re=0;for(const{name:$,config:P}of z){const L=`mcp-server-${$}`;await c(L,P,$)?Z++:re++}await t.closeAll(),re===0?rt(`成功添加 ${Z} 个工具`):Z>0?rt(`成功添加 ${Z} 个工具,${re} 个失败`):rt("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){rt("添加工具失败:数据格式不正确");return}const{description:g,headers:v,name:x,thumbnail:E,type:A,url:M}=m;if(!x||!M||!A){rt("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${x}-${Date.now()}`}`;let B;if(typeof v=="string"&&v.trim())try{B=JSON.parse(v)}catch(z){console.warn("Failed to parse headers JSON:",z)}else typeof v=="object"&&(B=v);await c(S,{type:A,url:M,headers:B,useAISdkClient:!0},x,g,E)?(await t.closeAll(),rt("添加工具完成")):rt("重复添加工具或无法获取工具列表")}catch(g){console.error("handleCustomAdd error:",g),rt(`添加工具失败:${g instanceof Error?g.message:"未知错误"}`)}}}};function Iy(t,r,o){const c=_.ref([]),u=_.ref([]),f=_.ref(!1),m=$=>t.mcpServers[$]?.type==="local",g=($,P)=>{P?t.ignoreToolnames=t.ignoreToolnames.filter(L=>L!==$):t.ignoreToolnames.includes($)||t.ignoreToolnames.push($)},v=($,P)=>{r.value||(r.value={});const L={...r.value};$===null?Object.keys(L).forEach(G=>{L[G]=P}):L[$]=P,r.value=L},x=$=>{const P=u.value.find(L=>L.id===$);P&&(P.addState="idle")},E=$=>{const P=t.mcpTools[$];if(!P)return[];const L=m($),G=r.value||{};return Object.keys(P).map(U=>{const ee=Object.prototype.hasOwnProperty.call(G,U),Y=L&&ee?G[U]:!0;return g(U,Y),{id:U,name:U,description:P[U].description,enabled:Y}})},A=()=>{c.value.forEach(P=>{const L=new Map(P.tools.map(U=>[U.id,U.enabled])),G=E(P.id).map(U=>{const ee=L.has(U.id)?!!L.get(U.id):U.enabled;return g(U.id,ee),{...U,enabled:ee}});P.tools=G});const $=new Set(c.value.flatMap(P=>P.tools.map(L=>L.id)));t.ignoreToolnames=t.ignoreToolnames.filter(P=>$.has(P))},M=async $=>{const P=$.pluginId;if(!await t.insertMcpServer(P,$.mcpServer))return!1;if(!t.mcpTools[P])return await t.removeMcpServer(P),!1;const U=E(P);if(U.length===0&&$.mcpServer?.type!=="builtin")return await t.removeMcpServer(P),!1;const ee=c.value.find(ue=>ue.id===$.pluginId);if(ee)return ee.tools=U,ee.originMcpConfig=_.markRaw($.mcpServer),!0;const Y={id:$.pluginId,name:$.name,icon:$.icon||o,description:$.description,enabled:!0,expanded:!1,tools:U,originMcpConfig:_.markRaw($.mcpServer)};return c.value.push(Y),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async($,P)=>{let L=P.name,G=P.description;if(!L||!G){if("type"in P&&P.type==="local")L=L||"本地工具",G=G||"本地工具列表";else if("type"in P&&P.type==="builtin")L=L||"浏览器内置工具",G=G||"通过 navigator.modelContextTesting 暴露的浏览器原生 MCP 工具";else if("url"in P)try{const U=new URL(P.url);L=L||U.origin,G=G||U.searchParams.get("sessionId")||("sessionId"in P?P.sessionId:"")||""}catch(U){console.error("[usePlugin] Failed to parse MCP server URL:",P.url,U),L=L||"未知插件",G=G||""}}await M({pluginId:$,name:L||"",description:G||"",mcpServer:P})},togglePlugin:($,P)=>{const L=m($.id);$.tools.forEach(G=>{G.enabled=P,g(G.id,P),L&&v(G.id,P)})},toggleTool:($,P,L)=>{const G=m($.id);$.tools.forEach(U=>{U.id===P&&(U.enabled=L)}),g(P,L),G&&v(P,L)},deletePlugin:async $=>{const P=c.value.find(G=>G.id===$.id);if(!P)return;c.value=c.value.filter(G=>G.id!==P.id),x(P.id);const L=$.id;await t.removeMcpServer(L)},addPluginCore:M,addPluginFromMarket:async $=>{$.addState="loading";const P={type:$.type,url:$.url,headers:$.headers,useAISdkClient:!0},L=await M({pluginId:$.id,name:$.name,description:$.description||"",icon:$.icon,mcpServer:P});$.addState=L?"added":"idle"},addPluginFromScan:async($,P)=>{const L={type:"streamableHttp",url:`${P}mcp?sessionId=${$}`};let G="未知插件";try{G=new URL(`${P}mcp?sessionId=${$}`).origin}catch(U){console.error("[usePlugin] Failed to parse scan URL:",U)}return await M({pluginId:`plugin-${$}`,name:G,description:$,mcpServer:L})},handleClientDisconnected:async $=>{const P=$,L=c.value.find(G=>G.id===P);return await t.removeMcpServer($),L?(c.value=c.value.filter(G=>G.id!==P),x(P),L):null},searchPlugin:($,P)=>$.trim()===""||P.name.toLowerCase().includes($.toLowerCase()),syncInstalledPluginTools:A}}function Sy(t){const{onToolCatalogChanged:r}=t,o=typeof window<"u"&&window!==window.top,c=M=>M===window||o&&M===window.parent;let u=!1,f=!1,m=!1;const g=async()=>{if(!(!r||u)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(M){console.warn("[useRouteBasedTools] refresh tool catalog failed:",M)}}while(m&&!u)}finally{f=!1}}},v=M=>{!c(M.source)||M.data?.type!==$n.MSG_TOOL_REGISTERED&&M.data?.type!==$n.MSG_TOOL_UNREGISTERED||g()};let x=!1;const E=()=>{x||(u=!1,x=!0,window.addEventListener("message",v),o&&window.parent&&window.parent.postMessage({type:$n.MSG_REMOTER_READY},"*"))},A=()=>{x&&(u=!0,m=!1,x=!1,window.removeEventListener("message",v))};_.onMounted(()=>{E()}),_.onUnmounted(()=>{A()})}function Ty(t){const{skillsRef:r,customAgentProvider:o}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const g=r?.value;c.value=g?await $n.getSkillOverviews(g):[]});const u=_.computed(()=>{const g=c.value;return g.length>0?$n.formatSkillsForSystemPrompt(g):""}),f=_.computed(()=>{const g=r?.value;return g?$n.createSkillTools(g):{}});return _.watchEffect(()=>{if(o.promptManager.setSkillMeta(u.value),o.llmConfig){const g=o.llmConfig.extraTools??{};o.llmConfig.extraTools={...g,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:u,skillTools:f,skillOverviews:c}}const Ny=["title"],Oy=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,o=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:g=0,inputTokenDetails:v,outputTokenDetails:x}=r.usage,E=v?.cacheReadTokens||0,A=x?.reasoningTokens||0;return{cachedInputTokens:[E/g*100+"%",E],inputTokens:[(f-E)/g*100+"%",f],reasoningTokens:[A/g*100+"%",A],outputTokens:[(m-A)/g*100+"%",m]}}),u=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:g=0,inputTokenDetails:v,outputTokenDetails:x}=r.usage,E=v?.cacheReadTokens||0,A=x?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${g}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
61
- `)});return(f,m)=>o.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:u.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(g,v)=>(_.openBlock(),_.createElementBlock("div",{key:v,class:_.normalizeClass(v),style:_.normalizeStyle({width:g[0]})},null,6))),128))],8,Ny))}}),rr=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},ky=rr(Oy,[["__scopeId","data-v-000098b4"]]),Ry={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 My(t,r){return _.openBlock(),_.createElementBlock("svg",Ry,[...r[0]||(r[0]=[_.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),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.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),_.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 Fu={render:My};function Dy(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=_.h(Fu,{style:{width:"48px",height:"48px"}}),m=_.ref({}),g=_.computed(()=>Qn.GeneratingStatus.includes(o.status)),v=_.computed(()=>r.value.findLastIndex(T=>T.role==="assistant")),x=T=>T===void 0?"复制":m.value[T]?"复制成功":"复制",E=async T=>{const B=r.value[T].uiContent.map(D=>D.content).join(`
62
- `);try{await navigator.clipboard.writeText(B),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(D){console.error("复制失败:",D),rt("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((D,ne)=>D.role==="user"&&ne<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),rt("无法重新生成消息");return}const B=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(B.content)){const ne=B.content.find(Z=>Z.type==="text")?.text||"",z=B.content.filter(Z=>Z.type!=="text");c.value=ne,await u(ne,z.length>0?z:void 0)}else c.value=B.content,await u(B.content)},M={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:T})=>{const S=v.value===T;return g.value&&S?"":_.h("div",{class:["assistant-actions",{"latest-assistant":S,"historical-assistant":!S}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h($t.IconButton,{icon:kr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(_d,{effect:"light",content:x(T),placement:"right",visibleArrow:!1},()=>_.h($t.IconButton,{icon:kr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h(ky,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:M,copyingStates:m,isProcessing:g,latestAssistantMessageIndex:v,copyTooltipContent:x,copyMessageToClipboard:E,regenerateMessage:A}}function Py(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:m,customAgentProvider:g}=t,v=_.ref(!1),x=()=>{_.nextTick(()=>{const S=document.querySelector("div.tr-bubble-list");S&&S.scrollTo({top:S.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const S=[];g.agent.responseMessages=S,r();const B=u();B.aiSdkMessages=S},handleHistorySelect:S=>{f(),o(S.id);const B=u();g.agent.responseMessages=B.aiSdkMessages,v.value=!1,x()},handleHistoryUpdateTitle:(S,B)=>{B.title=S},handleHistoryDelete:(S,B)=>{if(S.id==="delete"){if(m.currentId===B.id){rt("不允许删除当前会话");return}c(B.id)}},scrollToBottom:x}}function By(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:m,AILogoUrl:g,show:v,addPluginFromScan:x,inputMessage:E}=t;let A=null,M=!1;const T=async z=>{if(Lu("添加工具中..."),z){const Z=await x(z,o.value);rt(Z?"添加工具完成":"重复添加工具或添加失败")}else rt("添加工具失败")},S=async z=>{if(/^\/[A-Za-z0-9-]{6,}$/.test(z)){try{const Z=await fetch(`${o.value}client?sessionId=${z.slice(1)}`);if(!Z.ok)throw new Error(`HTTP ${Z.status}`);const $=(await Z.json())?.data?.sessionId;$?await T($):rt("添加工具失败,请检查识别码是否正确"),E.value=""}catch(Z){console.error("识别码处理失败:",Z),rt("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},B=()=>{const z=Z=>{A&&(A.destroy(),A=null),A=$n.createRemoter({sessionId:Z||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:m?.value,logoUrl:g,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};_.watch(r,Z=>{if(c!=="remoter")return;const re=!!Z;A?!M&&re&&(z(Z),M=!0):(z(Z),M=re)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&A&&z(r.value)},{deep:!0}),_.watch(v,Z=>{A&&(Z?A.hide():A.show())},{immediate:!0})},D=()=>{_.watch(r,z=>{z&&T(z)})};return{handleScanSuccess:T,handleSessionIdInput:S,initialize:()=>{r.value&&T(r.value),c==="remoter"&&B(),D()},initializeRemoter:B,watchSessionIdChanges:D}}function Ly(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function Fy(t){return t.type.startsWith("image/")}function Uy(t,r){const o=r*1024*1024;return t.size<=o}async function zy(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await Ly(o.rawFile);Fy(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),rt({type:"fail",message:"文件处理失败"})}return r}function Vy(t={}){const r=_.ref([]),o=async u=>{if(!u||u.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const g of u){if(!m.some(x=>g.type.startsWith(x))){rt({type:"fail",message:`不支持的文件类型: ${g.type}`});continue}if(!Uy(g,f)){rt({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:g,url:URL.createObjectURL(g)})}},c=()=>{r.value.forEach(u=>{u.url&&URL.revokeObjectURL(u.url)}),r.value=[]};return{attachments:r,handleFilesSelected:o,clearAttachments:c}}function Zy(t){const{selectedModel:r,selectedModelId:o}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),u=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:g,clearAttachments:v}=Vy({maxFileSize:u,supportedTypes:f});return _.watch(o,()=>{if(m.value.length>0&&r.value){const T=r.value.multimodal?.maxFileSize||10,S=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(D=>{if(!D.rawFile||!S.some(Z=>D.rawFile.type.startsWith(Z)))return!0;const z=T*1024*1024;return D.rawFile.size>z}).length>0&&(v(),rt("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{g(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(rt("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await zy(m.value),cleanupAttachments:()=>{m.value.length>0&&v()},clearAttachments:v}}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 tl=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"]]),nl;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(nl||(nl={}));function $y(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 jy=(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})(),Uu=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!tl.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,tl.get(r))},t})(),rl=(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})(),Do;(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"})(Do||(Do={}));var Hy=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Do.UNKWOWN_ERROR}},t})(),Wy=(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 Vn(t){return typeof t>"u"||t===null}var Or=(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})(),zu=(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),g=0,v=m;g<v.length;g++){var x=v[g];if(f.has(x))return o.logError("".concat(x," is not supported videoConstaints."),!0),!1}return!0},t})(),Ai=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gy(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Hr={exports:{}},Xy=Hr.exports,il;function qy(){return il||(il=1,(function(t,r){(function(o,c){c(r)})(Xy,(function(o){function c(C){return C==null}var u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,e){C.__proto__=e}||function(C,e){for(var n in e)e.hasOwnProperty(n)&&(C[n]=e[n])};function f(C,e){u(C,e);function n(){this.constructor=C}C.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function g(C,e){e===void 0&&(e=C.constructor);var n=Error.captureStackTrace;n&&n(C,e)}var v=(function(C){f(e,C);function e(n){var i=this.constructor,s=C.call(this,n)||this;return Object.defineProperty(s,"name",{value:i.name,enumerable:!1}),m(s,i.prototype),g(s),s}return e})(Error);class x extends v{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}x.kind="Exception";class E extends x{}E.kind="ArgumentException";class A extends x{}A.kind="IllegalArgumentException";class M{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 M(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new M(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new M(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class T extends x{static getChecksumInstance(){return new T}}T.kind="ChecksumException";class S{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 D extends x{}D.kind="IndexOutOfBoundsException";class ne extends D{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}ne.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 ne(n);if(i>e)throw new ne(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 Z{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)}}Z.MIN_VALUE_32_BITS=-2147483648,Z.MAX_VALUE=Number.MAX_SAFE_INTEGER;class re{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=re.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=re.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+Z.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+Z.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 re))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 re(this.size,this.bits.slice())}}var $;(function(C){C[C.OTHER=0]="OTHER",C[C.PURE_BARCODE=1]="PURE_BARCODE",C[C.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",C[C.TRY_HARDER=3]="TRY_HARDER",C[C.CHARACTER_SET=4]="CHARACTER_SET",C[C.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",C[C.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",C[C.ASSUME_GS1=7]="ASSUME_GS1",C[C.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",C[C.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",C[C.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})($||($={}));var P=$;class L extends x{static getFormatInstance(){return new L}}L.kind="FormatException";var G;(function(C){C[C.Cp437=0]="Cp437",C[C.ISO8859_1=1]="ISO8859_1",C[C.ISO8859_2=2]="ISO8859_2",C[C.ISO8859_3=3]="ISO8859_3",C[C.ISO8859_4=4]="ISO8859_4",C[C.ISO8859_5=5]="ISO8859_5",C[C.ISO8859_6=6]="ISO8859_6",C[C.ISO8859_7=7]="ISO8859_7",C[C.ISO8859_8=8]="ISO8859_8",C[C.ISO8859_9=9]="ISO8859_9",C[C.ISO8859_10=10]="ISO8859_10",C[C.ISO8859_11=11]="ISO8859_11",C[C.ISO8859_13=12]="ISO8859_13",C[C.ISO8859_14=13]="ISO8859_14",C[C.ISO8859_15=14]="ISO8859_15",C[C.ISO8859_16=15]="ISO8859_16",C[C.SJIS=16]="SJIS",C[C.Cp1250=17]="Cp1250",C[C.Cp1251=18]="Cp1251",C[C.Cp1252=19]="Cp1252",C[C.Cp1256=20]="Cp1256",C[C.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",C[C.UTF8=22]="UTF8",C[C.ASCII=23]="ASCII",C[C.Big5=24]="Big5",C[C.GB18030=25]="GB18030",C[C.EUC_KR=26]="EUC_KR"})(G||(G={}));class U{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,U.VALUE_IDENTIFIER_TO_ECI.set(e,this),U.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];U.VALUES_TO_ECI.set(h,this)}for(const l of s)U.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 L("incorect value");const n=U.VALUES_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}static getCharacterSetECIByName(e){const n=U.NAME_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}equals(e){if(!(e instanceof U))return!1;const n=e;return this.getName()===n.getName()}}U.VALUE_IDENTIFIER_TO_ECI=new Map,U.VALUES_TO_ECI=new Map,U.NAME_TO_ECI=new Map,U.Cp437=new U(G.Cp437,Int32Array.from([0,2]),"Cp437"),U.ISO8859_1=new U(G.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),U.ISO8859_2=new U(G.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),U.ISO8859_3=new U(G.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),U.ISO8859_4=new U(G.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),U.ISO8859_5=new U(G.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),U.ISO8859_6=new U(G.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),U.ISO8859_7=new U(G.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),U.ISO8859_8=new U(G.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),U.ISO8859_9=new U(G.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),U.ISO8859_10=new U(G.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),U.ISO8859_11=new U(G.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),U.ISO8859_13=new U(G.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),U.ISO8859_14=new U(G.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),U.ISO8859_15=new U(G.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),U.ISO8859_16=new U(G.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),U.SJIS=new U(G.SJIS,20,"SJIS","Shift_JIS"),U.Cp1250=new U(G.Cp1250,21,"Cp1250","windows-1250"),U.Cp1251=new U(G.Cp1251,22,"Cp1251","windows-1251"),U.Cp1252=new U(G.Cp1252,23,"Cp1252","windows-1252"),U.Cp1256=new U(G.Cp1256,24,"Cp1256","windows-1256"),U.UnicodeBigUnmarked=new U(G.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),U.UTF8=new U(G.UTF8,26,"UTF8","UTF-8"),U.ASCII=new U(G.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),U.Big5=new U(G.Big5,28,"Big5"),U.GB18030=new U(G.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),U.EUC_KR=new U(G.EUC_KR,30,"EUC_KR","EUC-KR");class ee extends x{}ee.kind="UnsupportedOperationException";class Y{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!Y.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 U?e:U.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(Y.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(U.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new ee(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(U.UTF8)||e.equals(U.ISO8859_1)||e.equals(U.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 ue{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return Y.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(P.CHARACTER_SET)!==void 0)return n.get(P.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,p=0,y=0,b=0,I=0,R=0,F=0,V=0,W=0,Q=0;const ce=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let de=0;de<i&&(s||a||l);de++){const ae=e[de]&255;l&&(d>0?(ae&128)===0?l=!1:d--:(ae&128)!==0&&((ae&64)===0?l=!1:(d++,(ae&32)===0?h++:(d++,(ae&16)===0?p++:(d++,(ae&8)===0?y++:l=!1))))),s&&(ae>127&&ae<160?s=!1:ae>159&&(ae<192||ae===215||ae===247)&&Q++),a&&(b>0?ae<64||ae===127||ae>252?a=!1:b--:ae===128||ae===160||ae>239?a=!1:ae>160&&ae<224?(I++,F=0,R++,R>V&&(V=R)):ae>127?(b++,R=0,F++,F>W&&(W=F)):(R=0,F=0))}return l&&d>0&&(l=!1),a&&b>0&&(a=!1),l&&(ce||h+p+y>0)?ue.UTF8:a&&(ue.ASSUME_SHIFT_JIS||V>=3||W>=3)?ue.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=i?ue.SHIFT_JIS:ue.ISO88591:s?ue.ISO88591:a?ue.SHIFT_JIS:l?ue.UTF8:ue.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,p,y,b){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(b){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),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return Y.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}ue.SHIFT_JIS=U.SJIS.getName(),ue.GB2312="GB2312",ue.ISO88591=U.ISO8859_1.getName(),ue.EUC_JP="EUC_JP",ue.UTF8=U.UTF8.getName(),ue.PLATFORM_DEFAULT_ENCODING=ue.UTF8,ue.ASSUME_SHIFT_JIS=!1;class ge{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+=ue.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 Te{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 Te(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)===`
63
- `||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 Te(d,h);for(let b=0;b<a;b++)s[b]&&y.set(Math.floor(b%d),Math.floor(b/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 re(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 b=e;b<a;b++)h[y+Math.floor(b/32)]|=1<<(b&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new re(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 re(e),s=new re(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 b=s[p*i+y];if(b!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(b<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>d){let I=31;for(;!(b>>>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 Te))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=`
64
- `){return this.buildToString(e,n,i)}buildToString(e,n,i){let s=new ge;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 Te(this.width,this.height,this.rowSize,this.bits.slice())}}class H extends x{static getNotFoundInstance(){return new H}}H.kind="NotFoundException";class ye extends S{constructor(e){super(e),this.luminances=ye.EMPTY,this.buckets=new Int32Array(ye.LUMINANCE_BUCKETS)}getBlackRow(e,n){const i=this.getLuminanceSource(),s=i.getWidth();n==null||n.getSize()<s?n=new re(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)>>ye.LUMINANCE_SHIFT]++;const d=ye.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 b=a[y+1]&255;(p*4-h-b)/2<d&&n.set(y),h=p,p=b}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight(),s=new Te(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),b=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<b;I++){const R=y[I]&255;a[R>>ye.LUMINANCE_SHIFT]++}}const l=ye.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 ye(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let i=0;i<ye.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 b=y-s,I=e[y]*b*b;I>d&&(l=y,d=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new H;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const b=y-s,I=b*b*(l-y)*(i-e[y]);I>p&&(h=y,p=I)}return h<<ye.LUMINANCE_SHIFT}}ye.LUMINANCE_BITS=5,ye.LUMINANCE_SHIFT=8-ye.LUMINANCE_BITS,ye.LUMINANCE_BUCKETS=1<<ye.LUMINANCE_BITS,ye.EMPTY=Uint8ClampedArray.from([0]);class he extends ye{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>=he.MINIMUM_DIMENSION&&i>=he.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>he.BLOCK_SIZE_POWER;(n&he.BLOCK_SIZE_MASK)!==0&&a++;let l=i>>he.BLOCK_SIZE_POWER;(i&he.BLOCK_SIZE_MASK)!==0&&l++;const d=he.calculateBlackPoints(s,a,l,n,i),h=new Te(n,i);he.calculateThresholdForBlock(s,a,l,n,i,d,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new he(e)}static calculateThresholdForBlock(e,n,i,s,a,l,d){const h=a-he.BLOCK_SIZE,p=s-he.BLOCK_SIZE;for(let y=0;y<i;y++){let b=y<<he.BLOCK_SIZE_POWER;b>h&&(b=h);const I=he.cap(y,2,i-3);for(let R=0;R<n;R++){let F=R<<he.BLOCK_SIZE_POWER;F>p&&(F=p);const V=he.cap(R,2,n-3);let W=0;for(let ce=-2;ce<=2;ce++){const de=l[I+ce];W+=de[V-2]+de[V-1]+de[V]+de[V+1]+de[V+2]}const Q=W/25;he.thresholdBlock(e,F,b,Q,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<he.BLOCK_SIZE;d++,h+=a)for(let p=0;p<he.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,i+d)}static calculateBlackPoints(e,n,i,s,a){const l=a-he.BLOCK_SIZE,d=s-he.BLOCK_SIZE,h=new Array(i);for(let p=0;p<i;p++){h[p]=new Int32Array(n);let y=p<<he.BLOCK_SIZE_POWER;y>l&&(y=l);for(let b=0;b<n;b++){let I=b<<he.BLOCK_SIZE_POWER;I>d&&(I=d);let R=0,F=255,V=0;for(let Q=0,ce=y*s+I;Q<he.BLOCK_SIZE;Q++,ce+=s){for(let de=0;de<he.BLOCK_SIZE;de++){const ae=e[ce+de]&255;R+=ae,ae<F&&(F=ae),ae>V&&(V=ae)}if(V-F>he.MIN_DYNAMIC_RANGE)for(Q++,ce+=s;Q<he.BLOCK_SIZE;Q++,ce+=s)for(let de=0;de<he.BLOCK_SIZE;de++)R+=e[ce+de]&255}let W=R>>he.BLOCK_SIZE_POWER*2;if(V-F<=he.MIN_DYNAMIC_RANGE&&(W=F/2,p>0&&b>0)){const Q=(h[p-1][b]+2*h[p][b-1]+h[p-1][b-1])/4;F<Q&&(W=Q)}h[p][b]=W}}return h}}he.BLOCK_SIZE_POWER=3,he.BLOCK_SIZE=1<<he.BLOCK_SIZE_POWER,he.BLOCK_SIZE_MASK=he.BLOCK_SIZE-1,he.MINIMUM_DIMENSION=he.BLOCK_SIZE*5,he.MIN_DYNAMIC_RANGE=24;class Se{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 ee("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new ee("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new ee("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new ge;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(`
65
- `)}return n.toString()}}class We extends Se{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 We(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new We(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new We(this.delegate.rotateCounterClockwise45())}}class me extends Se{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=me.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return me.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],b=e[a+1],I=e[a+2];h=306*y+601*b+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*me.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=me.makeBufferFromCanvasImageData(n),this}invert(){return new We(this)}}me.DEGREE_TO_RADIANS=Math.PI/180;class Oe{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 Me=(globalThis||Ai||self||window||void 0)&&(globalThis||Ai||self||window||void 0).__awaiter||function(C,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(b){l(b)}}function h(y){try{p(i.throw(y))}catch(b){l(b)}}function p(y){y.done?a(y.value):s(y.value).then(d,h)}p((i=i.apply(C,e||[])).next())})};class Je{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 Me(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 Me(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new Oe(n.deviceId,n.label))})}findDeviceById(e){return Me(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Me(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Me(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 Me(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return Me(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 Me(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return Me(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 Me(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 Me(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 Me(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 Me(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 E(`element with id '${e}' not found`);if(i.nodeName.toLowerCase()!==n.toLowerCase())throw new E(`element with id '${e}' must be an ${n} element`);return i}decodeFromImage(e,n){if(!e&&!n)throw new E("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 E("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 E("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 E("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 E("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new E("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 E("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 E("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 Me(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Me(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 H("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 H,y=(d instanceof T||d instanceof L)&&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 T||s instanceof L,l=s instanceof H;(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 me(n),s=new he(i);return new M(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 be{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 ke;(function(C){C[C.AZTEC=0]="AZTEC",C[C.CODABAR=1]="CODABAR",C[C.CODE_39=2]="CODE_39",C[C.CODE_93=3]="CODE_93",C[C.CODE_128=4]="CODE_128",C[C.DATA_MATRIX=5]="DATA_MATRIX",C[C.EAN_8=6]="EAN_8",C[C.EAN_13=7]="EAN_13",C[C.ITF=8]="ITF",C[C.MAXICODE=9]="MAXICODE",C[C.PDF_417=10]="PDF_417",C[C.QR_CODE=11]="QR_CODE",C[C.RSS_14=12]="RSS_14",C[C.RSS_EXPANDED=13]="RSS_EXPANDED",C[C.UPC_A=14]="UPC_A",C[C.UPC_E=15]="UPC_E",C[C.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ke||(ke={}));var te=ke,Ie;(function(C){C[C.OTHER=0]="OTHER",C[C.ORIENTATION=1]="ORIENTATION",C[C.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",C[C.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",C[C.ISSUE_NUMBER=4]="ISSUE_NUMBER",C[C.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",C[C.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",C[C.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",C[C.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",C[C.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",C[C.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(Ie||(Ie={}));var Ae=Ie;class fe{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 K{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=K.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=K.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]=K.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]=K.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 et extends x{}et.kind="ArithmeticException";class we extends K{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 et;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"+Z.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}we.AZTEC_DATA_12=new we(4201,4096,1),we.AZTEC_DATA_10=new we(1033,1024,1),we.AZTEC_DATA_6=new we(67,64,1),we.AZTEC_PARAM=new we(19,16,1),we.QR_CODE_FIELD_256=new we(285,256,0),we.DATA_MATRIX_FIELD_256=new we(301,256,1),we.AZTEC_DATA_8=we.DATA_MATRIX_FIELD_256,we.MAXICODE_FIELD_64=we.AZTEC_DATA_6;class kt extends x{}kt.kind="ReedSolomonException";class Bt extends x{}Bt.kind="IllegalStateException";class Tn{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],b=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,b);for(let R=0;R<b.length;R++){const F=e.length-1-i.log(b[R]);if(F<0)throw new kt("Bad error location");e[F]=we.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 kt("r_{i-1} was zero");l=R;let V=s.getZero();const W=a.getCoefficient(a.getDegree()),Q=s.inverse(W);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const ce=l.getDegree()-a.getDegree(),de=s.multiply(l.getCoefficient(l.getDegree()),Q);V=V.addOrSubtract(s.buildMonomial(ce,de)),l=l.addOrSubtract(a.multiplyByMonomial(ce,de))}if(h=V.multiply(d).addOrSubtract(F),l.getDegree()>=a.getDegree())throw new Bt("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new kt("sigmaTilde(0) was zero");const y=s.inverse(p),b=h.multiplyScalar(y),I=l.multiplyScalar(y);return[b,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 kt("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),b=(y&1)===0?y|1:y&-2;h=a.multiply(h,b)}s[l]=a.multiply(e.evaluateAt(d),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],d))}return s}}var It;(function(C){C[C.UPPER=0]="UPPER",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.DIGIT=3]="DIGIT",C[C.PUNCT=4]="PUNCT",C[C.BINARY=5]="BINARY"})(It||(It={}));class Qe{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=Qe.convertBoolArrayToByteArray(s),l=Qe.getEncodedData(s),d=new fe(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=It.UPPER,s=It.UPPER,a="",l=0;for(;l<n;)if(s===It.BINARY){if(n-l<5)break;let d=Qe.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=Qe.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const p=Qe.readCode(e,l,8);a+=ue.castAsNonUtf8Char(p),l+=8}s=i}else{let d=s===It.DIGIT?4:5;if(n-l<d)break;let h=Qe.readCode(e,l,d);l+=d;let p=Qe.getCharacter(s,h);p.startsWith("CTRL_")?(i=s,s=Qe.getTable(p.charAt(5)),p.charAt(6)==="L"&&(i=s)):(a+=p,s=i)}return a}static getTable(e){switch(e){case"L":return It.LOWER;case"P":return It.PUNCT;case"M":return It.MIXED;case"D":return It.DIGIT;case"B":return It.BINARY;case"U":default:return It.UPPER}}static getCharacter(e,n){switch(e){case It.UPPER:return Qe.UPPER_TABLE[n];case It.LOWER:return Qe.LOWER_TABLE[n];case It.MIXED:return Qe.MIXED_TABLE[n];case It.PUNCT:return Qe.PUNCT_TABLE[n];case It.DIGIT:return Qe.DIGIT_TABLE[n];default:throw new Bt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=we.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=we.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=we.AZTEC_DATA_10):(i=12,n=we.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new L;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=Qe.readCode(e,l,i);try{new Tn(n).decode(d,a-s)}catch(I){throw new L(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 L;(R===1||R===h-1)&&p++}let y=new Array(s*i-p),b=0;for(let I=0;I<s;I++){let R=d[I];if(R===1||R===h-1)y.fill(R>1,b,b+i-1),b+=i-1;else for(let F=i-1;F>=0;--F)y[b++]=(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*Z.truncDivision(Z.truncDivision(s,2)-1,15),h=s/2,p=Z.truncDivision(d,2);for(let y=0;y<h;y++){let b=y+Z.truncDivision(y,15);a[h-y-1]=p-b-1,a[h+y]=p+b+1}}for(let d=0,h=0;d<i;d++){let p=(i-d)*4+(n?9:12),y=d*2,b=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[b-F]),l[h+4*p+R+F]=e.get(a[b-F],a[b-I]),l[h+6*p+R+F]=e.get(a[b-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?Qe.readCode(e,n,8):Qe.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]=Qe.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Qe.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"],Qe.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"],Qe.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
66
- `,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],Qe.PUNCT_TABLE=["","\r",`\r
67
- `,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],Qe.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 Nn{static floatToIntBits(e){return e}}Nn.MAX_VALUE=Number.MAX_SAFE_INTEGER;class Ce{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof Ce){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*Nn.floatToIntBits(this.x)+Nn.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 Un{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class Hn extends Un{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 Yt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=Yt.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 H}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,b=!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 V=!0;for(;(V||!p)&&s<R;)V=this.containsBlackPoint(e,n,s,!0),V?(s++,l=!0,p=!0):p||s++;if(s>=R){a=!0;break}let W=!0;for(;(W||!y)&&e>=0;)W=this.containsBlackPoint(i,s,e,!1),W?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let Q=!0;for(;(Q||!b)&&i>=0;)Q=this.containsBlackPoint(e,n,i,!0),Q?(i--,l=!0,b=!0):b||i--;if(i<0){a=!0;break}l&&(d=!0)}if(!a&&d){const F=n-e;let V=null;for(let de=1;V===null&&de<F;de++)V=this.getBlackPointOnSegment(e,s-de,e+de,s);if(V==null)throw new H;let W=null;for(let de=1;W===null&&de<F;de++)W=this.getBlackPointOnSegment(e,i+de,e+de,i);if(W==null)throw new H;let Q=null;for(let de=1;Q===null&&de<F;de++)Q=this.getBlackPointOnSegment(n,i+de,n-de,i);if(Q==null)throw new H;let ce=null;for(let de=1;ce===null&&de<F;de++)ce=this.getBlackPointOnSegment(n,s-de,n-de,s);if(ce==null)throw new H;return this.centerEdges(ce,V,Q,W)}else throw new H}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),b=je.round(n+p*d);if(h.get(y,b))return new Ce(y,b)}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(),b=s.getX(),I=s.getY(),R=Yt.CORR;return a<this.width/2?[new Ce(b-R,I+R),new Ce(d+R,h+R),new Ce(p-R,y-R),new Ce(a+R,l-R)]:[new Ce(b+R,I+R),new Ce(d+R,h-R),new Ce(p-R,y+R),new Ce(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}}Yt.INIT_SIZE=10,Yt.CORR=1;class Wn{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 H;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 H;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 zt{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,b,I,R,F,V,W){const Q=zt.quadrilateralToSquare(e,n,i,s,a,l,d,h);return zt.squareToQuadrilateral(p,y,b,I,R,F,V,W).times(Q)}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,b=this.a33;for(let I=0;I<n;I+=2){const R=e[I],F=e[I+1],V=a*R+h*F+b;e[I]=(i*R+l*F+p)/V,e[I+1]=(s*R+d*F+y)/V}}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,b=this.a33,I=e.length;for(let R=0;R<I;R++){const F=e[R],V=n[R],W=a*F+h*V+b;e[R]=(i*F+l*V+p)/W,n[R]=(s*F+d*V+y)/W}}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 zt(i-e,a-i,e,s-n,l-s,n,0,0,1);{const b=i-a,I=d-a,R=s-l,F=h-l,V=b*F-I*R,W=(p*F-I*y)/V,Q=(b*y-p*R)/V;return new zt(i-e+W*i,d-e+Q*d,e,s-n+W*s,h-n+Q*h,n,W,Q,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return zt.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new zt(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 zt(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 ir extends Wn{sampleGrid(e,n,i,s,a,l,d,h,p,y,b,I,R,F,V,W,Q,ce,de){const ae=zt.quadrilateralToQuadrilateral(s,a,l,d,h,p,y,b,I,R,F,V,W,Q,ce,de);return this.sampleGridWithTransform(e,n,i,ae)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new H;const a=new Te(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),Wn.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 H}}return a}}class ln{static setGridSampler(e){ln.gridSampler=e}static getInstance(){return ln.gridSampler}}ln.gridSampler=new ir;class k{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new Ce(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class se{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 Hn(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 H;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(Z.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new H}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 Tn(we.AZTEC_PARAM).decode(l,a)}catch{throw new H}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 b=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 V=this.distancePoint(F,b)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(V<.75||V>1.25||!this.isWhiteOrBlackRectangle(b,I,R,F))break}n=b,i=I,s=R,a=F,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new H;this.compact=this.nbCenterLayers===5;let d=new Ce(n.getX()+.5,n.getY()-.5),h=new Ce(i.getX()+.5,i.getY()+.5),p=new Ce(s.getX()-.5,s.getY()+.5),y=new Ce(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 Yt(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 k(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new k(h+7,p+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new k(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new k(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 Yt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new k(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new k(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new k(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new k(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 k(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=ln.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 b=0;b<i;b++)this.image.get(je.round(d+b*p),je.round(h+b*y))&&(s|=1<<i-b-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new k(e.getX()-a,e.getY()+a),n=new k(n.getX()-a,n.getY()-a),i=new k(i.getX()+a,i.getY()-a),s=new k(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 b=l/i;return b>.1&&b<.9?0:b<=.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 k(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 Ce(d+s*a,h+s*l),y=new Ce(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 b=new Ce(d+s*a,h+s*l),I=new Ce(d-s*a,h-s*l);return[p,b,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*(Z.truncDivision(this.nbLayers-4,8)+1)+15}}class Ye{decode(e,n=null){let i=null,s=new se(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Qe().decode(y)}catch(y){i=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Qe().decode(y)}catch(y){throw i??y}let d=new be(l.getText(),l.getRawBytes(),l.getNumBits(),a,te.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(P.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class bt extends Je{constructor(e=500){super(new Ye,e)}}class mt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(P.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 b=0;b<p.length;b++)p[b]=new Ce(y-p[b].getY()-1,p[b].getX())}return l}else throw new H}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new re(i);const l=n&&n.get(P.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 b=Math.trunc((y+1)/2),I=(y&1)===0,R=p+d*(I?b:-b);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(P.NEED_RESULT_POINT_CALLBACK)===!0)){const V=new Map;n.forEach((W,Q)=>V.set(Q,W)),V.delete(P.NEED_RESULT_POINT_CALLBACK),n=V}try{const V=this.decodeRow(R,a,n);if(F===1){V.putMetadata(Ae.ORIENTATION,180);const W=V.getResultPoints();W!==null&&(W[0]=new Ce(i-W[0].getX()-1,W[0].getY()),W[1]=new Ce(i-W[1].getX()-1,W[1].getY()))}return V}catch{}}}throw new H}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 H;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 H}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 H;mt.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],b=n[p]*d,I=y>b?y-b:b-y;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class pe extends mt{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=pe.MAX_AVG_VARIANCE,b=-1;for(let I=pe.CODE_START_A;I<=pe.CODE_START_C;I++){const R=mt.patternMatchVariance(a,pe.CODE_PATTERNS[I],pe.MAX_INDIVIDUAL_VARIANCE);R<y&&(y=R,b=I)}if(b>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,b]);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 H}static decodeCode(e,n,i){mt.recordPattern(e,i,n);let s=pe.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<pe.CODE_PATTERNS.length;l++){const d=pe.CODE_PATTERNS[l],h=this.patternMatchVariance(n,d,pe.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new H}decodeRow(e,n,i){const s=i&&i.get(P.ASSUME_GS1)===!0,a=pe.findStartPattern(n),l=a[2];let d=0;const h=new Uint8Array(20);h[d++]=l;let p;switch(l){case pe.CODE_START_A:p=pe.CODE_CODE_A;break;case pe.CODE_START_B:p=pe.CODE_CODE_B;break;case pe.CODE_START_C:p=pe.CODE_CODE_C;break;default:throw new L}let y=!1,b=!1,I="",R=a[0],F=a[1];const V=Int32Array.from([0,0,0,0,0,0]);let W=0,Q=0,ce=l,de=0,ae=!0,Xe=!1,Ve=!1;for(;!y;){const Sr=b;switch(b=!1,W=Q,Q=pe.decodeCode(n,V,F),h[d++]=Q,Q!==pe.CODE_STOP&&(ae=!0),Q!==pe.CODE_STOP&&(de++,ce+=de*Q),R=F,F+=V.reduce((xd,yd)=>xd+yd,0),Q){case pe.CODE_START_A:case pe.CODE_START_B:case pe.CODE_START_C:throw new L}switch(p){case pe.CODE_CODE_A:if(Q<64)Ve===Xe?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),Ve=!1;else if(Q<96)Ve===Xe?I+=String.fromCharCode(Q-64):I+=String.fromCharCode(Q+64),Ve=!1;else switch(Q!==pe.CODE_STOP&&(ae=!1),Q){case pe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case pe.CODE_FNC_2:case pe.CODE_FNC_3:break;case pe.CODE_FNC_4_A:!Xe&&Ve?(Xe=!0,Ve=!1):Xe&&Ve?(Xe=!1,Ve=!1):Ve=!0;break;case pe.CODE_SHIFT:b=!0,p=pe.CODE_CODE_B;break;case pe.CODE_CODE_B:p=pe.CODE_CODE_B;break;case pe.CODE_CODE_C:p=pe.CODE_CODE_C;break;case pe.CODE_STOP:y=!0;break}break;case pe.CODE_CODE_B:if(Q<96)Ve===Xe?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),Ve=!1;else switch(Q!==pe.CODE_STOP&&(ae=!1),Q){case pe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case pe.CODE_FNC_2:case pe.CODE_FNC_3:break;case pe.CODE_FNC_4_B:!Xe&&Ve?(Xe=!0,Ve=!1):Xe&&Ve?(Xe=!1,Ve=!1):Ve=!0;break;case pe.CODE_SHIFT:b=!0,p=pe.CODE_CODE_A;break;case pe.CODE_CODE_A:p=pe.CODE_CODE_A;break;case pe.CODE_CODE_C:p=pe.CODE_CODE_C;break;case pe.CODE_STOP:y=!0;break}break;case pe.CODE_CODE_C:if(Q<100)Q<10&&(I+="0"),I+=Q;else switch(Q!==pe.CODE_STOP&&(ae=!1),Q){case pe.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case pe.CODE_CODE_A:p=pe.CODE_CODE_A;break;case pe.CODE_CODE_B:p=pe.CODE_CODE_B;break;case pe.CODE_STOP:y=!0;break}break}Sr&&(p=p===pe.CODE_CODE_A?pe.CODE_CODE_B:pe.CODE_CODE_A)}const rn=F-R;if(F=n.getNextUnset(F),!n.isRange(F,Math.min(n.getSize(),F+(F-R)/2),!1))throw new H;if(ce-=de*W,ce%103!==W)throw new T;const _n=I.length;if(_n===0)throw new H;_n>0&&ae&&(p===pe.CODE_CODE_C?I=I.substring(0,_n-2):I=I.substring(0,_n-1));const on=(a[1]+a[0])/2,dt=R+rn/2,Gt=h.length,cn=new Uint8Array(Gt);for(let Sr=0;Sr<Gt;Sr++)cn[Sr]=h[Sr];const Ir=[new Ce(on,e),new Ce(dt,e)];return new be(I,cn,0,Ir,te.CODE_128,new Date().getTime())}}pe.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])],pe.MAX_AVG_VARIANCE=.25,pe.MAX_INDIVIDUAL_VARIANCE=.7,pe.CODE_SHIFT=98,pe.CODE_CODE_C=99,pe.CODE_CODE_B=100,pe.CODE_CODE_A=101,pe.CODE_FNC_1=102,pe.CODE_FNC_2=97,pe.CODE_FNC_3=96,pe.CODE_FNC_4_A=101,pe.CODE_FNC_4_B=100,pe.CODE_START_A=103,pe.CODE_START_B=104,pe.CODE_START_C=105,pe.CODE_STOP=106;class Rt extends mt{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=Rt.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,p;do{Rt.recordPattern(n,l,s);let V=Rt.toNarrowWidePattern(s);if(V<0)throw new H;h=Rt.patternToChar(V),this.decodeRowResult+=h,p=l;for(let W of s)l+=W;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let V of s)y+=V;let b=l-p-y;if(l!==d&&b*2<y)throw new H;if(this.usingCheckDigit){let V=this.decodeRowResult.length-1,W=0;for(let Q=0;Q<V;Q++)W+=Rt.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Q));if(this.decodeRowResult.charAt(V)!==Rt.ALPHABET_STRING.charAt(W%43))throw new T;this.decodeRowResult=this.decodeRowResult.substring(0,V)}if(this.decodeRowResult.length===0)throw new H;let I;this.extendedMode?I=Rt.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let R=(a[1]+a[0])/2,F=p+y/2;return new be(I,null,0,[new Ce(R,e),new Ce(F,e)],te.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)===Rt.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 H}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<Rt.CHARACTER_ENCODINGS.length;n++)if(Rt.CHARACTER_ENCODINGS[n]===e)return Rt.ALPHABET_STRING.charAt(n);if(e===Rt.ASTERISK_ENCODING)return"*";throw new H}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 L;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new L;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 L;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new L;break}i+=d,s++}else i+=a}return i}}Rt.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",Rt.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],Rt.ASTERISK_ENCODING=148;class at extends mt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new ge;at.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(P.ALLOWED_LENGTHS)),h==null&&(h=at.DEFAULT_ALLOWED_LENGTHS);let p=d.length,y=!1,b=0;for(let F of h){if(p===F){y=!0;break}F>b&&(b=F)}if(!y&&p>b&&(y=!0),!y)throw new L;const I=[new Ce(s[1],e),new Ce(a[0],e)];return new be(d,null,0,I,te.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;){mt.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=at.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=at.skipWhiteSpace(e),i=at.findGuardPattern(e,n,at.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 H}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new H;return i}decodeEnd(e){e.reverse();try{let n=at.skipWhiteSpace(e),i;try{i=at.findGuardPattern(e,n,at.END_PATTERN_REVERSED[0])}catch(a){a instanceof H&&(i=at.findGuardPattern(e,n,at.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(mt.patternMatchVariance(a,i,at.MAX_INDIVIDUAL_VARIANCE)<at.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 H}static decodeDigit(e){let n=at.MAX_AVG_VARIANCE,i=-1,s=at.PATTERNS.length;for(let a=0;a<s;a++){let l=at.PATTERNS[a],d=mt.patternMatchVariance(e,l,at.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new H}}at.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])],at.MAX_AVG_VARIANCE=.38,at.MAX_INDIVIDUAL_VARIANCE=.5,at.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],at.START_PATTERN=Int32Array.from([1,1,1,1]),at.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class _t extends mt{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=_t.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 _t.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return _t.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 L;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 L;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return _t.findGuardPattern(e,n,!1,_t.START_END_PATTERN,new Int32Array(_t.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 b=n;b<l;b++)if(e.get(b)!==y)a[d]++;else{if(d===p-1){if(mt.patternMatchVariance(a,s,_t.MAX_INDIVIDUAL_VARIANCE)<_t.MAX_AVG_VARIANCE)return Int32Array.from([h,b]);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 H}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=mt.patternMatchVariance(n,p,_t.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new H}}_t.MAX_AVG_VARIANCE=.48,_t.MAX_INDIVIDUAL_VARIANCE=.7,_t.START_END_PATTERN=Int32Array.from([1,1,1]),_t.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),_t.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),_t.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 He{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=He.parseExtensionString(l),h=[new Ce((i[0]+i[1])/2,e),new Ce(a,e)],p=new be(l,null,0,h,te.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=_t.decodeDigit(e,s,l,_t.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(d|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new H;let h=this.determineCheckDigit(d);if(He.extensionChecksum(i.toString())!==h)throw new H;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 H}static parseExtensionString(e){if(e.length!==5)return null;let n=He.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 Pe{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=Pe.parseExtensionString(l),h=[new Ce((i[0]+i[1])/2,e),new Ce(a,e)],p=new be(l,null,0,h,te.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=_t.decodeDigit(e,s,l,_t.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 H;if(parseInt(i.toString())%4!==d)throw new H;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ae.ISSUE_NUMBER,parseInt(e)]])}}class tt{static decodeRow(e,n,i){let s=_t.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new He().decodeRow(e,n,s)}catch{return new Pe().decodeRow(e,n,s)}}}tt.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ge extends _t{constructor(){super(),this.decodeRowStringBuffer="",Ge.L_AND_G_PATTERNS=Ge.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=Ge.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];Ge.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=Ge.findStartGuardPattern(n),a=i==null?null:i.get(P.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ae=new Ce((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ae)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),d=l.rowOffset,h=l.resultString;if(a!=null){const ae=new Ce(d,e);a.foundPossibleResultPoint(ae)}let p=this.decodeEnd(n,d);if(a!=null){const ae=new Ce((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ae)}let y=p[1],b=y+(y-p[0]);if(b>=n.getSize()||!n.isRange(y,b,!1))throw new H;let I=h.toString();if(I.length<8)throw new L;if(!Ge.checkChecksum(I))throw new T;let R=(s[1]+s[0])/2,F=(p[1]+p[0])/2,V=this.getBarcodeFormat(),W=[new Ce(R,e),new Ce(F,e)],Q=new be(I,null,0,W,V,new Date().getTime()),ce=0;try{let ae=tt.decodeRow(e,n,p[1]);Q.putMetadata(Ae.UPC_EAN_EXTENSION,ae.getText()),Q.putAllMetadata(ae.getResultMetadata()),Q.addResultPoints(ae.getResultPoints()),ce=ae.getText().length}catch{}let de=i==null?null:i.get(P.ALLOWED_EAN_EXTENSIONS);if(de!=null){let ae=!1;for(let Xe in de)if(ce.toString()===Xe){ae=!0;break}if(!ae)throw new H}return Q}decodeEnd(e,n){return Ge.findGuardPattern(e,n,!1,Ge.START_END_PATTERN,new Int32Array(Ge.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return Ge.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return Ge.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 L;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 L;i+=a}return(1e3-i)%10}}class zn extends Ge{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=Ge.decodeDigit(e,s,l,Ge.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(d|=1<<5-p)}i=zn.determineFirstDigit(i,d),l=Ge.findGuardPattern(e,l,!0,Ge.MIDDLE_PATTERN,new Int32Array(Ge.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=Ge.decodeDigit(e,s,l,Ge.L_PATTERNS);i+=String.fromCharCode(48+y);for(let b of s)l+=b}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return te.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 H}}zn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class is extends Ge{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=Ge.decodeDigit(e,s,l,Ge.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}l=Ge.findGuardPattern(e,l,!0,Ge.MIDDLE_PATTERN,new Int32Array(Ge.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=Ge.decodeDigit(e,s,l,Ge.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return te.EAN_8}}class os extends Ge{constructor(){super(...arguments),this.ean13Reader=new zn}getBarcodeFormat(){return te.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 be(n.substring(1),null,null,e.getResultPoints(),te.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new H}reset(){this.ean13Reader.reset()}}class wn extends Ge{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=wn.decodeDigit(e,s,l,wn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(d|=1<<5-p)}let h=wn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return wn.findGuardPatternWithoutCounters(e,n,!0,wn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ge.checkChecksum(wn.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 H.getNotFoundInstance()}getBarcodeFormat(){return te.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new ge;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()}}wn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),wn.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 Ui extends mt{constructor(e){super();let n=e==null?null:e.get(P.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new zn),i.push(new os),i.push(new is),i.push(new wn)):(n.indexOf(te.EAN_13)>-1&&i.push(new zn),n.indexOf(te.UPC_A)>-1&&i.push(new os),n.indexOf(te.EAN_8)>-1&&i.push(new is),n.indexOf(te.UPC_E)>-1&&i.push(new wn)),this.readers=i}decodeRow(e,n,i){for(let s of this.readers)try{const a=s.decodeRow(e,n,i),l=a.getBarcodeFormat()===te.EAN_13&&a.getText().charAt(0)==="0",d=i==null?null:i.get(P.POSSIBLE_FORMATS),h=d==null||d.includes(te.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new be(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),te.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new H}reset(){for(let e of this.readers)e.reset()}}class Xt extends mt{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(mt.patternMatchVariance(e,n[i],Xt.MAX_INDIVIDUAL_VARIANCE)<Xt.MAX_AVG_VARIANCE)return i;throw new H}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>=Xt.MIN_FINDER_PATTERN_RATIO&&s<=Xt.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}}Xt.MAX_AVG_VARIANCE=.2,Xt.MAX_INDIVIDUAL_VARIANCE=.45,Xt.MIN_FINDER_PATTERN_RATIO=9.5/12,Xt.MAX_FINDER_PATTERN_RATIO=12.5/14;class wr{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 wr))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class si{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 Ce(i,a)),this.resultPoints.push(new Ce(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof si))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class On{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=On.combins(s-p-1,d-h-2);if(i&&l===0&&s-p-(d-h-1)>=d-h-1&&(y-=On.combins(s-p-(d-h),d-h-2)),d-h-1>1){let b=0;for(let I=s-p-(d-h-2);I>n;I--)b+=On.combins(s-p-I-1,d-h-3);y-=b*(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 $u{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new re(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 b=11;b>=0;--b)(y&1<<b)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let b=p.getRightChar().getValue();for(let I=11;I>=0;--I)(b&1<<I)!=0&&s.set(a),a++}}return s}}class or{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class zi{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class en extends zi{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===en.FNC1}}en.FNC1="$";class sr extends zi{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 mn extends zi{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new L;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===mn.FNC1}isSecondDigitFNC1(){return this.secondDigit===mn.FNC1}isAnyFNC1(){return this.firstDigit===mn.FNC1||this.secondDigit===mn.FNC1}}mn.FNC1=10;class _e{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new H;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 H;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 H;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 H}static processFixedAI(e,n,i){if(i.length<e)throw new H;let s=i.substring(0,e);if(i.length<e+n)throw new H;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 _r{constructor(e){this.buffer=new ge,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 mn(this.information.getSize(),mn.FNC1,mn.FNC1):new mn(this.information.getSize(),a-1,mn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new mn(e+7,i,s)}extractNumericValueFromBitArray(e,n){return _r.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 sr(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new sr(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 sr(this.current.getPosition(),this.buffer.toString()):n=new sr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new or(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new sr(this.current.getPosition(),this.buffer.toString());return new or(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new or(!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 sr(this.current.getPosition(),this.buffer.toString());return new or(!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 or(!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 sr(this.current.getPosition(),this.buffer.toString());return new or(!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 or(!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 en(e+5,en.FNC1);if(n>=5&&n<15)return new en(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new en(e+7,""+(i+1));if(i>=90&&i<116)return new en(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 L}return new en(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 en(e+5,en.FNC1);if(n>=5&&n<15)return new en(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new en(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 Bt("Decoding invalid alphanumeric value: "+i)}return new en(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 Vi{constructor(e){this.information=e,this.generalDecoder=new _r(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class tn extends Vi{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)}tn.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)}}tn.GTIN_SIZE=40;class vr extends tn{constructor(e){super(e)}parseInformation(){let e=new ge;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(vr.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,vr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,vr.HEADER_SIZE+44)}}vr.HEADER_SIZE=4;class ai extends Vi{constructor(e){super(e)}parseInformation(){let e=new ge;return this.getGeneralDecoder().decodeAllCodes(e,ai.HEADER_SIZE)}}ai.HEADER_SIZE=5;class li extends tn{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 kn extends li{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=kn.HEADER_SIZE+li.GTIN_SIZE+kn.WEIGHT_SIZE)throw new H;let e=new ge;return this.encodeCompressedGtin(e,kn.HEADER_SIZE),this.encodeCompressedWeight(e,kn.HEADER_SIZE+li.GTIN_SIZE,kn.WEIGHT_SIZE),e.toString()}}kn.HEADER_SIZE=5,kn.WEIGHT_SIZE=15;class ju extends kn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Hu extends kn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class Rn extends tn{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Rn.HEADER_SIZE+tn.GTIN_SIZE)throw new H;let e=new ge;this.encodeCompressedGtin(e,Rn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Rn.HEADER_SIZE+tn.GTIN_SIZE,Rn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(Rn.HEADER_SIZE+tn.GTIN_SIZE+Rn.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}Rn.HEADER_SIZE=8,Rn.LAST_DIGIT_SIZE=2;class Kt extends tn{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Kt.HEADER_SIZE+tn.GTIN_SIZE)throw new H;let e=new ge;this.encodeCompressedGtin(e,Kt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Kt.HEADER_SIZE+tn.GTIN_SIZE,Kt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(Kt.HEADER_SIZE+tn.GTIN_SIZE+Kt.LAST_DIGIT_SIZE,Kt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Kt.HEADER_SIZE+tn.GTIN_SIZE+Kt.LAST_DIGIT_SIZE+Kt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Kt.HEADER_SIZE=8,Kt.LAST_DIGIT_SIZE=2,Kt.FIRST_THREE_DIGITS_SIZE=10;class vt extends li{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=vt.HEADER_SIZE+vt.GTIN_SIZE+vt.WEIGHT_SIZE+vt.DATE_SIZE)throw new H;let e=new ge;return this.encodeCompressedGtin(e,vt.HEADER_SIZE),this.encodeCompressedWeight(e,vt.HEADER_SIZE+vt.GTIN_SIZE,vt.WEIGHT_SIZE),this.encodeCompressedDate(e,vt.HEADER_SIZE+vt.GTIN_SIZE+vt.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,vt.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}}vt.HEADER_SIZE=8,vt.WEIGHT_SIZE=20,vt.DATE_SIZE=16;function ss(C){try{if(C.get(1))return new vr(C);if(!C.get(2))return new ai(C);switch(_r.extractNumericValueFromBitArray(C,1,4)){case 4:return new ju(C);case 5:return new Hu(C)}switch(_r.extractNumericValueFromBitArray(C,1,5)){case 12:return new Rn(C);case 13:return new Kt(C)}switch(_r.extractNumericValueFromBitArray(C,1,7)){case 56:return new vt(C,"310","11");case 57:return new vt(C,"320","11");case 58:return new vt(C,"310","13");case 59:return new vt(C,"320","13");case 60:return new vt(C,"310","15");case 61:return new vt(C,"320","15");case 62:return new vt(C,"310","17");case 63:return new vt(C,"320","17")}}catch(e){throw console.log(e),new Bt("unknown decoder: "+C)}}class Gn{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 Gn?Gn.equalsOrNull(e.leftchar,n.leftchar)&&Gn.equalsOrNull(e.rightchar,n.rightchar)&&Gn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:Gn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Zi{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 Zi?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 oe extends Xt{constructor(e){super(...arguments),this.pairs=new Array(oe.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 oe.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,oe.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 H){if(!this.pairs.length)throw new H;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 H}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()),!oe.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 H}static isValidSequence(e){for(let n of oe.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||oe.isPartialRow(this.pairs,this.rows)||(this.rows.push(i,new Zi(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(Gn.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=$u.buildBitArray(e),s=ss(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 be(s,null,null,d,te.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=oe.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 H;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new Gn(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 b=l;b<a;b++)if(e.get(b)!=h)s[p]++;else{if(p==3){if(d&&oe.reverseCounters(s),oe.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=b;return}d&&oe.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 H}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,oe.FINDER_PATTERNS)}catch{return null}return new si(h,[a,l],a,l,n)}decodeDataCharacter(e,n,i,s){let a=this.getDataCharacterCounters();for(let dt=0;dt<a.length;dt++)a[dt]=0;if(s)oe.recordPatternInReverse(e,n.getStartEnd()[0],a);else{oe.recordPattern(e,n.getStartEnd()[1],a);for(let dt=0,Gt=a.length-1;dt<Gt;dt++,Gt--){let cn=a[dt];a[dt]=a[Gt],a[Gt]=cn}}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 H;let p=this.getOddCounts(),y=this.getEvenCounts(),b=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let dt=0;dt<a.length;dt++){let Gt=1*a[dt]/d,cn=Gt+.5;if(cn<1){if(Gt<.3)throw new H;cn=1}else if(cn>8){if(Gt>8.7)throw new H;cn=8}let Ir=dt/2;(dt&1)==0?(p[Ir]=cn,b[Ir]=Gt-cn):(y[Ir]=cn,I[Ir]=Gt-cn)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(i?0:2)+(s?0:1)-1,F=0,V=0;for(let dt=p.length-1;dt>=0;dt--){if(oe.isNotA1left(n,i,s)){let Gt=oe.WEIGHTS[R][2*dt];V+=p[dt]*Gt}F+=p[dt]}let W=0;for(let dt=y.length-1;dt>=0;dt--)if(oe.isNotA1left(n,i,s)){let Gt=oe.WEIGHTS[R][2*dt+1];W+=y[dt]*Gt}let Q=V+W;if((F&1)!=0||F>13||F<4)throw new H;let ce=(13-F)/2,de=oe.SYMBOL_WIDEST[ce],ae=9-de,Xe=On.getRSSvalue(p,de,!0),Ve=On.getRSSvalue(y,ae,!1),rn=oe.EVEN_TOTAL_SUBSET[ce],_n=oe.GSUM[ce],on=Xe*rn+Ve+_n;return new wr(on,Q)}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 H;a=!0}else{if(!y)throw new H;d=!0}else if(h==-1)if(p){if(y)throw new H;s=!0}else{if(!y)throw new H;l=!0}else if(h==0){if(p){if(!y)throw new H;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(y)throw new H}else throw new H;if(s){if(a)throw new H;oe.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&oe.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new H;oe.increment(this.getEvenCounts(),this.getOddRoundingErrors())}d&&oe.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}oe.SYMBOL_WIDEST=[7,5,4,3,1],oe.EVEN_TOTAL_SUBSET=[4,20,52,104,204],oe.GSUM=[0,348,1388,2948,3988],oe.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])],oe.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]],oe.FINDER_PAT_A=0,oe.FINDER_PAT_B=1,oe.FINDER_PAT_C=2,oe.FINDER_PAT_D=3,oe.FINDER_PAT_E=4,oe.FINDER_PAT_F=5,oe.FINDER_PATTERN_SEQUENCES=[[oe.FINDER_PAT_A,oe.FINDER_PAT_A],[oe.FINDER_PAT_A,oe.FINDER_PAT_B,oe.FINDER_PAT_B],[oe.FINDER_PAT_A,oe.FINDER_PAT_C,oe.FINDER_PAT_B,oe.FINDER_PAT_D],[oe.FINDER_PAT_A,oe.FINDER_PAT_E,oe.FINDER_PAT_B,oe.FINDER_PAT_D,oe.FINDER_PAT_C],[oe.FINDER_PAT_A,oe.FINDER_PAT_E,oe.FINDER_PAT_B,oe.FINDER_PAT_D,oe.FINDER_PAT_D,oe.FINDER_PAT_F],[oe.FINDER_PAT_A,oe.FINDER_PAT_E,oe.FINDER_PAT_B,oe.FINDER_PAT_D,oe.FINDER_PAT_E,oe.FINDER_PAT_F,oe.FINDER_PAT_F],[oe.FINDER_PAT_A,oe.FINDER_PAT_A,oe.FINDER_PAT_B,oe.FINDER_PAT_B,oe.FINDER_PAT_C,oe.FINDER_PAT_C,oe.FINDER_PAT_D,oe.FINDER_PAT_D],[oe.FINDER_PAT_A,oe.FINDER_PAT_A,oe.FINDER_PAT_B,oe.FINDER_PAT_B,oe.FINDER_PAT_C,oe.FINDER_PAT_C,oe.FINDER_PAT_D,oe.FINDER_PAT_E,oe.FINDER_PAT_E],[oe.FINDER_PAT_A,oe.FINDER_PAT_A,oe.FINDER_PAT_B,oe.FINDER_PAT_B,oe.FINDER_PAT_C,oe.FINDER_PAT_C,oe.FINDER_PAT_D,oe.FINDER_PAT_E,oe.FINDER_PAT_F,oe.FINDER_PAT_F],[oe.FINDER_PAT_A,oe.FINDER_PAT_A,oe.FINDER_PAT_B,oe.FINDER_PAT_B,oe.FINDER_PAT_C,oe.FINDER_PAT_D,oe.FINDER_PAT_D,oe.FINDER_PAT_E,oe.FINDER_PAT_E,oe.FINDER_PAT_F,oe.FINDER_PAT_F]],oe.MAX_PAIRS=11;class Wu extends wr{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 St extends Xt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);St.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);St.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&&St.checkChecksum(l,d))return St.constructResult(l,d)}throw new H}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 ge;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 be(a.toString(),null,0,[d[0],d[1],h[0],h[1]],te.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(P.NEED_RESULT_POINT_CALLBACK);if(d!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),d.foundPossibleResultPoint(new Ce(y,i))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Wu(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let W=0;W<s.length;W++)s[W]=0;if(i)mt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{mt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let W=0,Q=s.length-1;W<Q;W++,Q--){let ce=s[W];s[W]=s[Q],s[Q]=ce}}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 W=0;W<s.length;W++){let Q=s[W]/l,ce=Math.floor(Q+.5);ce<1?ce=1:ce>8&&(ce=8);let de=Math.floor(W/2);(W&1)===0?(d[de]=ce,p[de]=Q-ce):(h[de]=ce,y[de]=Q-ce)}this.adjustOddEvenCounts(i,a);let b=0,I=0;for(let W=d.length-1;W>=0;W--)I*=9,I+=d[W],b+=d[W];let R=0,F=0;for(let W=h.length-1;W>=0;W--)R*=9,R+=h[W],F+=h[W];let V=I+3*R;if(i){if((b&1)!==0||b>12||b<4)throw new H;let W=(12-b)/2,Q=St.OUTSIDE_ODD_WIDEST[W],ce=9-Q,de=On.getRSSvalue(d,Q,!1),ae=On.getRSSvalue(h,ce,!0),Xe=St.OUTSIDE_EVEN_TOTAL_SUBSET[W],Ve=St.OUTSIDE_GSUM[W];return new wr(de*Xe+ae+Ve,V)}else{if((F&1)!==0||F>10||F<4)throw new H;let W=(10-F)/2,Q=St.INSIDE_ODD_WIDEST[W],ce=9-Q,de=On.getRSSvalue(d,Q,!0),ae=On.getRSSvalue(h,ce,!1),Xe=St.INSIDE_ODD_TOTAL_SUBSET[W],Ve=St.INSIDE_GSUM[W];return new wr(ae*Xe+de+Ve,V)}}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(Xt.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 H}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,St.FINDER_PATTERNS);let b=l,I=s[1];return i&&(b=e.getSize()-1-b,I=e.getSize()-1-I),new si(y,[l,s[1]],b,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),b=(s&1)===1;if(p===1)if(y){if(b)throw new H;l=!0}else{if(!b)throw new H;h=!0}else if(p===-1)if(y){if(b)throw new H;a=!0}else{if(!b)throw new H;d=!0}else if(p===0){if(y){if(!b)throw new H;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(b)throw new H}else throw new H;if(a){if(l)throw new H;Xt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Xt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new H;Xt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Xt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}St.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],St.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],St.OUTSIDE_GSUM=[0,161,961,2015,2715],St.INSIDE_GSUM=[0,336,1036,1516],St.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],St.INSIDE_ODD_WIDEST=[2,4,6,8],St.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 Cr extends mt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(P.POSSIBLE_FORMATS):null,s=e&&e.get(P.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(te.EAN_13)||i.includes(te.UPC_A)||i.includes(te.EAN_8)||i.includes(te.UPC_E))&&this.readers.push(new Ui(e)),i.includes(te.CODE_39)&&this.readers.push(new Rt(s)),i.includes(te.CODE_128)&&this.readers.push(new pe),i.includes(te.ITF)&&this.readers.push(new at),i.includes(te.RSS_14)&&this.readers.push(new St),i.includes(te.RSS_EXPANDED)&&this.readers.push(new oe(this.verbose))):(this.readers.push(new Ui(e)),this.readers.push(new Rt),this.readers.push(new Ui(e)),this.readers.push(new pe),this.readers.push(new at),this.readers.push(new St),this.readers.push(new oe(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 H}reset(){this.readers.forEach(e=>e.reset())}}class Gu extends Je{constructor(e=500,n){super(new Cr(n),e,n)}}class ot{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class nt{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class qe{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 L;for(let i of qe.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new L}toString(){return""+this.versionNumber}static buildVersions(){return[new qe(1,10,10,8,8,new ot(5,new nt(1,3))),new qe(2,12,12,10,10,new ot(7,new nt(1,5))),new qe(3,14,14,12,12,new ot(10,new nt(1,8))),new qe(4,16,16,14,14,new ot(12,new nt(1,12))),new qe(5,18,18,16,16,new ot(14,new nt(1,18))),new qe(6,20,20,18,18,new ot(18,new nt(1,22))),new qe(7,22,22,20,20,new ot(20,new nt(1,30))),new qe(8,24,24,22,22,new ot(24,new nt(1,36))),new qe(9,26,26,24,24,new ot(28,new nt(1,44))),new qe(10,32,32,14,14,new ot(36,new nt(1,62))),new qe(11,36,36,16,16,new ot(42,new nt(1,86))),new qe(12,40,40,18,18,new ot(48,new nt(1,114))),new qe(13,44,44,20,20,new ot(56,new nt(1,144))),new qe(14,48,48,22,22,new ot(68,new nt(1,174))),new qe(15,52,52,24,24,new ot(42,new nt(2,102))),new qe(16,64,64,14,14,new ot(56,new nt(2,140))),new qe(17,72,72,16,16,new ot(36,new nt(4,92))),new qe(18,80,80,18,18,new ot(48,new nt(4,114))),new qe(19,88,88,20,20,new ot(56,new nt(4,144))),new qe(20,96,96,22,22,new ot(68,new nt(4,174))),new qe(21,104,104,24,24,new ot(56,new nt(6,136))),new qe(22,120,120,18,18,new ot(68,new nt(6,175))),new qe(23,132,132,20,20,new ot(62,new nt(8,163))),new qe(24,144,144,22,22,new ot(62,new nt(8,156),new nt(2,155))),new qe(25,8,18,6,16,new ot(7,new nt(1,5))),new qe(26,8,32,6,14,new ot(11,new nt(1,10))),new qe(27,12,26,10,24,new ot(14,new nt(1,16))),new qe(28,12,36,10,16,new ot(18,new nt(1,22))),new qe(29,16,36,14,16,new ot(24,new nt(1,32))),new qe(30,16,48,14,22,new ot(28,new nt(1,49)))]}}qe.VERSIONS=qe.buildVersions();class $i{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new L;this.version=$i.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new Te(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return qe.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 L;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 Te(p,h);for(let b=0;b<l;++b){const I=b*s;for(let R=0;R<d;++R){const F=R*a;for(let V=0;V<s;++V){const W=b*(s+2)+1+V,Q=I+V;for(let ce=0;ce<a;++ce){const de=R*(a+2)+1+ce;if(e.get(de,W)){const ae=F+ce;y.set(ae,Q)}}}}}return y}}class ji{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 V of a)s+=V.getCount();const l=new Array(s);let d=0;for(let V of a)for(let W=0;W<V.getCount();W++){const Q=V.getDataCodewords(),ce=i.getECCodewords()+Q;l[d++]=new ji(Q,new Uint8Array(ce))}const p=l[0].codewords.length-i.getECCodewords(),y=p-1;let b=0;for(let V=0;V<y;V++)for(let W=0;W<d;W++)l[W].codewords[V]=e[b++];const I=n.getVersionNumber()===24,R=I?8:d;for(let V=0;V<R;V++)l[V].codewords[p-1]=e[b++];const F=l[0].codewords.length;for(let V=p;V<F;V++)for(let W=0;W<d;W++){const Q=I?(W+8)%d:W,ce=I&&Q>7?V-1:V;l[Q].codewords[ce]=e[b++]}if(b!==e.length)throw new A;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Hi{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 Lt;(function(C){C[C.PAD_ENCODE=0]="PAD_ENCODE",C[C.ASCII_ENCODE=1]="ASCII_ENCODE",C[C.C40_ENCODE=2]="C40_ENCODE",C[C.TEXT_ENCODE=3]="TEXT_ENCODE",C[C.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",C[C.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",C[C.BASE256_ENCODE=6]="BASE256_ENCODE"})(Lt||(Lt={}));class Xn{static decode(e){const n=new Hi(e),i=new ge,s=new ge,a=new Array;let l=Lt.ASCII_ENCODE;do if(l===Lt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Lt.C40_ENCODE:this.decodeC40Segment(n,i);break;case Lt.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Lt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Lt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Lt.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new L}l=Lt.ASCII_ENCODE}while(l!==Lt.PAD_ENCODE&&n.available()>0);return s.length()>0&&i.append(s.toString()),new fe(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 L;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Lt.ASCII_ENCODE;if(a===129)return Lt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Lt.C40_ENCODE;case 231:return Lt.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 Lt.ANSIX12_ENCODE;case 239:return Lt.TEXT_ENCODE;case 240:return Lt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new L;break}}while(e.available()>0);return Lt.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 L;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 L}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 L}}}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 L;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 L}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 L;break;default:throw new L}}}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 L;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 L;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new L;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(Y.decode(d,ue.ISO88591))}catch(h){throw new Bt("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}}Xn.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"],Xn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],Xn.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"],Xn.TEXT_SHIFT2_SET_CHARS=Xn.C40_SHIFT2_SET_CHARS,Xn.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 Xu{constructor(){this.rsDecoder=new Tn(we.DATA_MATRIX_FIELD_256)}decode(e){const n=new $i(e),i=n.getVersion(),s=n.readCodewords(),a=ji.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],b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)d[R*h+p]=b[R]}return Xn.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=i[s]}}class Mt{constructor(e){this.image=e,this.rectangleDetector=new Yt(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 H;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=Mt.sampleGrid(this.image,i,s,a,l,d,h);return new Un(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 Ce(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 Ce(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,b=[a,n,i,s];return y>d&&(y=d,b[0]=n,b[1]=i,b[2]=s,b[3]=a),y>h&&(y=h,b[0]=i,b[1]=s,b[2]=a,b[3]=n),y>p&&(b[0]=s,b[1]=a,b[2]=n,b[3]=i),b}detectSolid2(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=Mt.shiftPoint(i,s,(l+1)*4),h=Mt.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=Mt.shiftPoint(n,i,(d+1)*4),p=Mt.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(p,a);let y=new Ce(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),b=new Ce(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(y))return this.isValid(b)?b:null;if(!this.isValid(b))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),R=this.transitionsBetween(h,b)+this.transitionsBetween(p,b);return I>R?y:b}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=Mt.shiftPoint(n,i,d*4),p=Mt.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,b=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Mt.moveAway(n,y,b),i=Mt.moveAway(i,y,b),s=Mt.moveAway(s,y,b),a=Mt.moveAway(a,y,b);let I,R;return h=Mt.shiftPoint(n,i,d*4),h=Mt.shiftPoint(h,a,l*4),I=Mt.shiftPoint(i,n,d*4),I=Mt.shiftPoint(I,s,l*4),p=Mt.shiftPoint(s,a,d*4),p=Mt.shiftPoint(p,i,l*4),R=Mt.shiftPoint(a,s,d*4),R=Mt.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 ln.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 V=i;i=s,s=V,V=a,a=l,l=V}let h=Math.abs(a-i),p=Math.abs(l-s),y=-h/2,b=s<l?1:-1,I=i<a?1:-1,R=0,F=this.image.get(d?s:i,d?i:s);for(let V=i,W=s;V!==a;V+=I){let Q=this.image.get(d?W:V,d?V:W);if(Q!==F&&(R++,F=Q),y+=p,y>0){if(W===l)break;W+=b,y-=h}}return R}}class qn{constructor(){this.decoder=new Xu}decode(e,n=null){let i,s;if(n!=null&&n.has(P.PURE_BARCODE)){const p=qn.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(p),s=qn.NO_POINTS}else{const p=new Mt(e.getBlackMatrix()).detect();i=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=i.getRawBytes(),l=new be(i.getText(),a,8*a.length,s,te.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 H;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 H;const b=s/2;a+=b,d+=b;const I=new Te(p,y);for(let R=0;R<y;R++){const F=a+R*s;for(let V=0;V<p;V++)e.get(d+V*s,F)&&I.set(V,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 H;const l=s-e[0];if(l===0)throw new H;return l}}qn.NO_POINTS=[];class qu extends Je{constructor(e=500){super(new qn,e)}}var br;(function(C){C[C.L=0]="L",C[C.M=1]="M",C[C.Q=2]="Q",C[C.H=3]="H"})(br||(br={}));class ht{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,ht.FOR_BITS.set(i,this),ht.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return ht.L;case"M":return ht.M;case"Q":return ht.Q;case"H":return ht.H;default:throw new E(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof ht))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=ht.FOR_BITS.size)throw new A;return ht.FOR_BITS.get(e)}}ht.FOR_BITS=new Map,ht.FOR_VALUE=new Map,ht.L=new ht(br.L,"L",1),ht.M=new ht(br.M,"M",0),ht.Q=new ht(br.Q,"Q",3),ht.H=new ht(br.H,"H",2);class qt{constructor(e){this.errorCorrectionLevel=ht.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return Z.bitCount(e^n)}static decodeFormatInformation(e,n){const i=qt.doDecodeFormatInformation(e,n);return i!==null?i:qt.doDecodeFormatInformation(e^qt.FORMAT_INFO_MASK_QR,n^qt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=Number.MAX_SAFE_INTEGER,s=0;for(const a of qt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new qt(a[1]);let d=qt.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=qt.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=3?new qt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof qt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}qt.FORMAT_INFO_MASK_QR=21522,qt.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 X{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 O{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Re{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 L;try{return this.getVersionForNumber((e-17)/4)}catch{throw new L}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return Re.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<Re.VERSION_DECODE_INFO.length;s++){const a=Re.VERSION_DECODE_INFO[s];if(a===e)return Re.getVersionForNumber(s+7);const l=qt.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?Re.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new Te(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}}Re.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]),Re.VERSIONS=[new Re(1,new Int32Array(0),new X(7,new O(1,19)),new X(10,new O(1,16)),new X(13,new O(1,13)),new X(17,new O(1,9))),new Re(2,Int32Array.from([6,18]),new X(10,new O(1,34)),new X(16,new O(1,28)),new X(22,new O(1,22)),new X(28,new O(1,16))),new Re(3,Int32Array.from([6,22]),new X(15,new O(1,55)),new X(26,new O(1,44)),new X(18,new O(2,17)),new X(22,new O(2,13))),new Re(4,Int32Array.from([6,26]),new X(20,new O(1,80)),new X(18,new O(2,32)),new X(26,new O(2,24)),new X(16,new O(4,9))),new Re(5,Int32Array.from([6,30]),new X(26,new O(1,108)),new X(24,new O(2,43)),new X(18,new O(2,15),new O(2,16)),new X(22,new O(2,11),new O(2,12))),new Re(6,Int32Array.from([6,34]),new X(18,new O(2,68)),new X(16,new O(4,27)),new X(24,new O(4,19)),new X(28,new O(4,15))),new Re(7,Int32Array.from([6,22,38]),new X(20,new O(2,78)),new X(18,new O(4,31)),new X(18,new O(2,14),new O(4,15)),new X(26,new O(4,13),new O(1,14))),new Re(8,Int32Array.from([6,24,42]),new X(24,new O(2,97)),new X(22,new O(2,38),new O(2,39)),new X(22,new O(4,18),new O(2,19)),new X(26,new O(4,14),new O(2,15))),new Re(9,Int32Array.from([6,26,46]),new X(30,new O(2,116)),new X(22,new O(3,36),new O(2,37)),new X(20,new O(4,16),new O(4,17)),new X(24,new O(4,12),new O(4,13))),new Re(10,Int32Array.from([6,28,50]),new X(18,new O(2,68),new O(2,69)),new X(26,new O(4,43),new O(1,44)),new X(24,new O(6,19),new O(2,20)),new X(28,new O(6,15),new O(2,16))),new Re(11,Int32Array.from([6,30,54]),new X(20,new O(4,81)),new X(30,new O(1,50),new O(4,51)),new X(28,new O(4,22),new O(4,23)),new X(24,new O(3,12),new O(8,13))),new Re(12,Int32Array.from([6,32,58]),new X(24,new O(2,92),new O(2,93)),new X(22,new O(6,36),new O(2,37)),new X(26,new O(4,20),new O(6,21)),new X(28,new O(7,14),new O(4,15))),new Re(13,Int32Array.from([6,34,62]),new X(26,new O(4,107)),new X(22,new O(8,37),new O(1,38)),new X(24,new O(8,20),new O(4,21)),new X(22,new O(12,11),new O(4,12))),new Re(14,Int32Array.from([6,26,46,66]),new X(30,new O(3,115),new O(1,116)),new X(24,new O(4,40),new O(5,41)),new X(20,new O(11,16),new O(5,17)),new X(24,new O(11,12),new O(5,13))),new Re(15,Int32Array.from([6,26,48,70]),new X(22,new O(5,87),new O(1,88)),new X(24,new O(5,41),new O(5,42)),new X(30,new O(5,24),new O(7,25)),new X(24,new O(11,12),new O(7,13))),new Re(16,Int32Array.from([6,26,50,74]),new X(24,new O(5,98),new O(1,99)),new X(28,new O(7,45),new O(3,46)),new X(24,new O(15,19),new O(2,20)),new X(30,new O(3,15),new O(13,16))),new Re(17,Int32Array.from([6,30,54,78]),new X(28,new O(1,107),new O(5,108)),new X(28,new O(10,46),new O(1,47)),new X(28,new O(1,22),new O(15,23)),new X(28,new O(2,14),new O(17,15))),new Re(18,Int32Array.from([6,30,56,82]),new X(30,new O(5,120),new O(1,121)),new X(26,new O(9,43),new O(4,44)),new X(28,new O(17,22),new O(1,23)),new X(28,new O(2,14),new O(19,15))),new Re(19,Int32Array.from([6,30,58,86]),new X(28,new O(3,113),new O(4,114)),new X(26,new O(3,44),new O(11,45)),new X(26,new O(17,21),new O(4,22)),new X(26,new O(9,13),new O(16,14))),new Re(20,Int32Array.from([6,34,62,90]),new X(28,new O(3,107),new O(5,108)),new X(26,new O(3,41),new O(13,42)),new X(30,new O(15,24),new O(5,25)),new X(28,new O(15,15),new O(10,16))),new Re(21,Int32Array.from([6,28,50,72,94]),new X(28,new O(4,116),new O(4,117)),new X(26,new O(17,42)),new X(28,new O(17,22),new O(6,23)),new X(30,new O(19,16),new O(6,17))),new Re(22,Int32Array.from([6,26,50,74,98]),new X(28,new O(2,111),new O(7,112)),new X(28,new O(17,46)),new X(30,new O(7,24),new O(16,25)),new X(24,new O(34,13))),new Re(23,Int32Array.from([6,30,54,78,102]),new X(30,new O(4,121),new O(5,122)),new X(28,new O(4,47),new O(14,48)),new X(30,new O(11,24),new O(14,25)),new X(30,new O(16,15),new O(14,16))),new Re(24,Int32Array.from([6,28,54,80,106]),new X(30,new O(6,117),new O(4,118)),new X(28,new O(6,45),new O(14,46)),new X(30,new O(11,24),new O(16,25)),new X(30,new O(30,16),new O(2,17))),new Re(25,Int32Array.from([6,32,58,84,110]),new X(26,new O(8,106),new O(4,107)),new X(28,new O(8,47),new O(13,48)),new X(30,new O(7,24),new O(22,25)),new X(30,new O(22,15),new O(13,16))),new Re(26,Int32Array.from([6,30,58,86,114]),new X(28,new O(10,114),new O(2,115)),new X(28,new O(19,46),new O(4,47)),new X(28,new O(28,22),new O(6,23)),new X(30,new O(33,16),new O(4,17))),new Re(27,Int32Array.from([6,34,62,90,118]),new X(30,new O(8,122),new O(4,123)),new X(28,new O(22,45),new O(3,46)),new X(30,new O(8,23),new O(26,24)),new X(30,new O(12,15),new O(28,16))),new Re(28,Int32Array.from([6,26,50,74,98,122]),new X(30,new O(3,117),new O(10,118)),new X(28,new O(3,45),new O(23,46)),new X(30,new O(4,24),new O(31,25)),new X(30,new O(11,15),new O(31,16))),new Re(29,Int32Array.from([6,30,54,78,102,126]),new X(30,new O(7,116),new O(7,117)),new X(28,new O(21,45),new O(7,46)),new X(30,new O(1,23),new O(37,24)),new X(30,new O(19,15),new O(26,16))),new Re(30,Int32Array.from([6,26,52,78,104,130]),new X(30,new O(5,115),new O(10,116)),new X(28,new O(19,47),new O(10,48)),new X(30,new O(15,24),new O(25,25)),new X(30,new O(23,15),new O(25,16))),new Re(31,Int32Array.from([6,30,56,82,108,134]),new X(30,new O(13,115),new O(3,116)),new X(28,new O(2,46),new O(29,47)),new X(30,new O(42,24),new O(1,25)),new X(30,new O(23,15),new O(28,16))),new Re(32,Int32Array.from([6,34,60,86,112,138]),new X(30,new O(17,115)),new X(28,new O(10,46),new O(23,47)),new X(30,new O(10,24),new O(35,25)),new X(30,new O(19,15),new O(35,16))),new Re(33,Int32Array.from([6,30,58,86,114,142]),new X(30,new O(17,115),new O(1,116)),new X(28,new O(14,46),new O(21,47)),new X(30,new O(29,24),new O(19,25)),new X(30,new O(11,15),new O(46,16))),new Re(34,Int32Array.from([6,34,62,90,118,146]),new X(30,new O(13,115),new O(6,116)),new X(28,new O(14,46),new O(23,47)),new X(30,new O(44,24),new O(7,25)),new X(30,new O(59,16),new O(1,17))),new Re(35,Int32Array.from([6,30,54,78,102,126,150]),new X(30,new O(12,121),new O(7,122)),new X(28,new O(12,47),new O(26,48)),new X(30,new O(39,24),new O(14,25)),new X(30,new O(22,15),new O(41,16))),new Re(36,Int32Array.from([6,24,50,76,102,128,154]),new X(30,new O(6,121),new O(14,122)),new X(28,new O(6,47),new O(34,48)),new X(30,new O(46,24),new O(10,25)),new X(30,new O(2,15),new O(64,16))),new Re(37,Int32Array.from([6,28,54,80,106,132,158]),new X(30,new O(17,122),new O(4,123)),new X(28,new O(29,46),new O(14,47)),new X(30,new O(49,24),new O(10,25)),new X(30,new O(24,15),new O(46,16))),new Re(38,Int32Array.from([6,32,58,84,110,136,162]),new X(30,new O(4,122),new O(18,123)),new X(28,new O(13,46),new O(32,47)),new X(30,new O(48,24),new O(14,25)),new X(30,new O(42,15),new O(32,16))),new Re(39,Int32Array.from([6,26,54,82,110,138,166]),new X(30,new O(20,117),new O(4,118)),new X(28,new O(40,47),new O(7,48)),new X(30,new O(43,24),new O(22,25)),new X(30,new O(10,15),new O(67,16))),new Re(40,Int32Array.from([6,30,58,86,114,142,170]),new X(30,new O(19,118),new O(6,119)),new X(28,new O(18,47),new O(31,48)),new X(30,new O(34,24),new O(34,25)),new X(30,new O(20,15),new O(61,16)))];var Vt;(function(C){C[C.DATA_MASK_000=0]="DATA_MASK_000",C[C.DATA_MASK_001=1]="DATA_MASK_001",C[C.DATA_MASK_010=2]="DATA_MASK_010",C[C.DATA_MASK_011=3]="DATA_MASK_011",C[C.DATA_MASK_100=4]="DATA_MASK_100",C[C.DATA_MASK_101=5]="DATA_MASK_101",C[C.DATA_MASK_110=6]="DATA_MASK_110",C[C.DATA_MASK_111=7]="DATA_MASK_111"})(Vt||(Vt={}));class gn{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)}}gn.values=new Map([[Vt.DATA_MASK_000,new gn(Vt.DATA_MASK_000,(C,e)=>(C+e&1)===0)],[Vt.DATA_MASK_001,new gn(Vt.DATA_MASK_001,(C,e)=>(C&1)===0)],[Vt.DATA_MASK_010,new gn(Vt.DATA_MASK_010,(C,e)=>e%3===0)],[Vt.DATA_MASK_011,new gn(Vt.DATA_MASK_011,(C,e)=>(C+e)%3===0)],[Vt.DATA_MASK_100,new gn(Vt.DATA_MASK_100,(C,e)=>(Math.floor(C/2)+Math.floor(e/3)&1)===0)],[Vt.DATA_MASK_101,new gn(Vt.DATA_MASK_101,(C,e)=>C*e%6===0)],[Vt.DATA_MASK_110,new gn(Vt.DATA_MASK_110,(C,e)=>C*e%6<3)],[Vt.DATA_MASK_111,new gn(Vt.DATA_MASK_111,(C,e)=>(C+e+C*e%3&1)===0)]]);class Yu{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new L;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=qt.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new L}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 Re.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=Re.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=Re.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new L}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=gn.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 b=s-1;b>0;b-=2){b===6&&b--;for(let I=0;I<s;I++){const R=l?s-1-I:I;for(let F=0;F<2;F++)a.get(b-F,R)||(y++,p<<=1,this.bitMatrix.get(b-F,R)&&(p|=1),y===8&&(d[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new L;return d}remask(){if(this.parsedFormatInfo===null)return;const e=gn.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 Wi{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 V=0;V<F.getCount();V++){const W=F.getDataCodewords(),Q=s.getECCodewordsPerBlock()+W;d[h++]=new Wi(W,new Uint8Array(Q))}const p=d[0].codewords.length;let y=d.length-1;for(;y>=0&&d[y].codewords.length!==p;)y--;y++;const b=p-s.getECCodewordsPerBlock();let I=0;for(let F=0;F<b;F++)for(let V=0;V<h;V++)d[V].codewords[F]=e[I++];for(let F=y;F<h;F++)d[F].codewords[b]=e[I++];const R=d[0].codewords.length;for(let F=b;F<R;F++)for(let V=0;V<h;V++){const W=V<y?F:F+1;d[V].codewords[W]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var xn;(function(C){C[C.TERMINATOR=0]="TERMINATOR",C[C.NUMERIC=1]="NUMERIC",C[C.ALPHANUMERIC=2]="ALPHANUMERIC",C[C.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",C[C.BYTE=4]="BYTE",C[C.ECI=5]="ECI",C[C.KANJI=6]="KANJI",C[C.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",C[C.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",C[C.HANZI=9]="HANZI"})(xn||(xn={}));class De{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,De.FOR_BITS.set(s,this),De.FOR_VALUE.set(e,this)}static forBits(e){const n=De.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 De))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}De.FOR_BITS=new Map,De.FOR_VALUE=new Map,De.TERMINATOR=new De(xn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),De.NUMERIC=new De(xn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),De.ALPHANUMERIC=new De(xn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),De.STRUCTURED_APPEND=new De(xn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),De.BYTE=new De(xn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),De.ECI=new De(xn.ECI,"ECI",Int32Array.from([0,0,0]),7),De.KANJI=new De(xn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),De.FNC1_FIRST_POSITION=new De(xn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),De.FNC1_SECOND_POSITION=new De(xn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),De.HANZI=new De(xn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class At{static decode(e,n,i,s){const a=new Hi(e);let l=new ge;const d=new Array;let h=-1,p=-1;try{let y=null,b=!1,I;do{if(a.available()<4)I=De.TERMINATOR;else{const R=a.readBits(4);I=De.forBits(R)}switch(I){case De.TERMINATOR:break;case De.FNC1_FIRST_POSITION:case De.FNC1_SECOND_POSITION:b=!0;break;case De.STRUCTURED_APPEND:if(a.available()<16)throw new L;h=a.readBits(8),p=a.readBits(8);break;case De.ECI:const R=At.parseECIValue(a);if(y=U.getCharacterSetECIByValue(R),y===null)throw new L;break;case De.HANZI:const F=a.readBits(4),V=a.readBits(I.getCharacterCountBits(n));F===At.GB2312_SUBSET&&At.decodeHanziSegment(a,l,V);break;default:const W=a.readBits(I.getCharacterCountBits(n));switch(I){case De.NUMERIC:At.decodeNumericSegment(a,l,W);break;case De.ALPHANUMERIC:At.decodeAlphanumericSegment(a,l,W,b);break;case De.BYTE:At.decodeByteSegment(a,l,W,y,d,s);break;case De.KANJI:At.decodeKanjiSegment(a,l,W);break;default:throw new L}break}}while(I!==De.TERMINATOR)}catch{throw new L}return new fe(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 L;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(Y.decode(s,ue.GB2312))}catch(l){throw new L(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new L;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(Y.decode(s,ue.SHIFT_JIS))}catch(l){throw new L(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new L;const d=new Uint8Array(i);for(let p=0;p<i;p++)d[p]=e.readBits(8);let h;s===null?h=ue.guessEncoding(d,l):h=s.getName();try{n.append(Y.decode(d,h))}catch(p){throw new L(p)}a.push(d)}static toAlphaNumericChar(e){if(e>=At.ALPHANUMERIC_CHARS.length)throw new L;return At.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new L;const l=e.readBits(11);n.append(At.toAlphaNumericChar(Math.floor(l/45))),n.append(At.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new L;n.append(At.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 L;const s=e.readBits(10);if(s>=1e3)throw new L;n.append(At.toAlphaNumericChar(Math.floor(s/100))),n.append(At.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(At.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new L;const s=e.readBits(7);if(s>=100)throw new L;n.append(At.toAlphaNumericChar(Math.floor(s/10))),n.append(At.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new L;const s=e.readBits(4);if(s>=10)throw new L;n.append(At.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 L}}At.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",At.GB2312_SUBSET=1;class as{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 Ku{constructor(){this.rsDecoder=new Tn(we.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(Te.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new Yu(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 as(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=Wi.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 b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)h[p++]=b[R]}return At.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=i[s]}}class Gi extends Ce{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 Gi(s,a,l)}}class ci{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 b=0;for(;y<s;){if(d.get(y,p))if(b===1)l[1]++;else if(b===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,b=1}else l[++b]++;else b===1&&b++,l[b]++;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 H}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)?ci.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i){const s=e[0]+e[1]+e[2],a=ci.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 Gi(a,l,d);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class Xi extends Ce{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 Xi(a,l,d,s)}}class Ju{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 Zt{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(P.TRY_HARDER)!==void 0,i=e!=null&&e.get(P.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Zt.MAX_MODULES));(d<Zt.MIN_SKIP||n)&&(d=Zt.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let b=d-1;b<a&&!h;b+=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,b))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(Zt.foundPatternCross(p)){if(this.handlePossibleCenter(p,b,R,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const V=this.findRowSkip();V>p[2]&&(b+=V-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]++;Zt.foundPatternCross(p)&&this.handlePossibleCenter(p,b,l,i)===!0&&(d=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return Ce.orderBestPatterns(y),new Ju(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&&Zt.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:Zt.foundPatternCross(d)?Zt.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:Zt.foundPatternCross(d)?Zt.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Zt.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 b=0,I=y.length;b<I;b++){const R=y[b];if(R.aboutEquals(h,d,l)){y[b]=R.combineEstimate(d,l,h),p=!0;break}}if(!p){const b=new Xi(l,d,h);y.push(b),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(b)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const i of this.possibleCenters)if(i.getCount()>=Zt.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()>=Zt.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 H;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),b=Math.abs(h.getEstimatedModuleSize()-i);return y<b?-1:y>b?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]]}}Zt.CENTER_QUORUM=2,Zt.MIN_SKIP=3,Zt.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(P.NEED_RESULT_POINT_CALLBACK);const i=new Zt(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 H("No pattern found in proccess finder.");const l=Rr.computeDimension(n,i,s,a),d=Re.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(),V=1-3/h,W=Math.floor(n.getX()+V*(R-n.getX())),Q=Math.floor(n.getY()+V*(F-n.getY()));for(let ce=4;ce<=16;ce<<=1)try{p=this.findAlignmentInRegion(a,W,Q,ce);break}catch(de){if(!(de instanceof H))throw de}}const y=Rr.createTransform(n,i,s,p,l),b=Rr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,i]:I=[s,n,i,p],new Un(b,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),zt.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 ln.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=je.round(Ce.distance(e,n)/s),l=je.round(Ce.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 H("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 b=0;const I=i+p;for(let R=e,F=n;R!==I;R+=p){const V=a?F:R,W=a?R:F;if(b===1===this.image.get(V,W)){if(b===2)return je.distance(R,F,e,n);b++}if(h+=d,h>0){if(F===s)break;F+=y,h-=l}}return b===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 H("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 H("Alignment bottom exceeds estimated module size.");return new ci(this.image,l,h,d-l,p-h,e,this.resultPointCallback).find()}}class Yn{constructor(){this.decoder=new Ku}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(P.PURE_BARCODE)!==void 0){const h=Yn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=Yn.NO_POINTS}else{const h=new Rr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof as&&i.getOther().applyMirroredCorrection(s);const a=new be(i.getText(),i.getRawBytes(),void 0,s,te.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 H;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 H;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new H;const p=Math.round((h-d+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new H;if(y!==p)throw new H;const b=Math.floor(s/2);a+=b,d+=b;const I=d+Math.floor((p-1)*s)-h;if(I>0){if(I>b)throw new H;d-=I}const R=a+Math.floor((y-1)*s)-l;if(R>0){if(R>b)throw new H;a-=R}const F=new Te(p,y);for(let V=0;V<y;V++){const W=a+Math.floor(V*s);for(let Q=0;Q<p;Q++)e.get(d+Math.floor(Q*s),W)&&F.set(Q,V)}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 H;return(a-e[0])/7}}Yn.NO_POINTS=new Array;class Le{PDF417Common(){}static getBitCountSum(e){return je.sum(e)}static toIntArray(e){if(e==null||!e.length)return Le.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(Le.SYMBOL_TABLE,e&262143);return n<0?-1:(Le.CODEWORD_TABLE[n]-1)%Le.NUMBER_OF_CODEWORDS}}Le.NUMBER_OF_CODEWORDS=929,Le.MAX_CODEWORDS_IN_BARCODE=Le.NUMBER_OF_CODEWORDS-1,Le.MIN_ROWS_IN_BARCODE=3,Le.MAX_ROWS_IN_BARCODE=90,Le.MODULES_IN_CODEWORD=17,Le.MODULES_IN_STOP_PATTERN=18,Le.BARS_IN_MODULE=8,Le.EMPTY_INT_ARRAY=new Int32Array([]),Le.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]),Le.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 Qu{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class Ze{static detectMultiple(e,n,i){let s=e.getBlackMatrix(),a=Ze.detect(i,s);return a.length||(s=s.clone(),s.rotate180(),a=Ze.detect(i,s)),new Qu(s,a)}static detect(e,n){const i=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const d=Ze.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+=Ze.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 Ze.copyToResult(l,Ze.findRowsWithPattern(e,s,a,n,i,Ze.START_PATTERN),Ze.INDEXES_START_PATTERN),l[4]!=null&&(i=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),Ze.copyToResult(l,Ze.findRowsWithPattern(e,s,a,n,i,Ze.STOP_PATTERN),Ze.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+=Ze.ROW_STEP){let b=Ze.findGuardPattern(e,a,s,i,!1,l,p);if(b!=null){for(;s>0;){const I=Ze.findGuardPattern(e,a,--s,i,!1,l,p);if(I!=null)b=I;else{s++;break}}d[0]=new Ce(b[0],s),d[1]=new Ce(b[1],s),h=!0;break}}let y=s+1;if(h){let b=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;y<n;y++){const R=Ze.findGuardPattern(e,I[0],y,i,!1,l,p);if(R!=null&&Math.abs(I[0]-R[0])<Ze.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<Ze.MAX_PATTERN_DRIFT)I=R,b=0;else{if(b>Ze.SKIPPED_ROW_COUNT_MAX)break;b++}}y-=b+1,d[2]=new Ce(I[0],y),d[3]=new Ce(I[1],y)}return y-s<Ze.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++<Ze.MAX_PIXEL_DRIFT;)h--;let y=h,b=0,I=l.length;for(let R=a;y<s;y++)if(e.get(y,i)!==R)d[b]++;else{if(b===I-1){if(Ze.patternMatchVariance(d,l,Ze.MAX_INDIVIDUAL_VARIANCE)<Ze.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=d[0]+d[1],B.arraycopy(d,2,d,0,b-1),d[b-1]=0,d[b]=0,b--}else b++;d[b]=1,R=!R}return b===I-1&&Ze.patternMatchVariance(d,l,Ze.MAX_INDIVIDUAL_VARIANCE)<Ze.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],b=n[p]*d,I=y>b?y-b:b-y;if(I>i)return 1/0;h+=I}return h/a}}Ze.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),Ze.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),Ze.MAX_AVG_VARIANCE=.42,Ze.MAX_INDIVIDUAL_VARIANCE=.8,Ze.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),Ze.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),Ze.MAX_PIXEL_DRIFT=3,Ze.MAX_PATTERN_DRIFT=5,Ze.SKIPPED_ROW_COUNT_MAX=25,Ze.ROW_STEP=5,Ze.BARCODE_MIN_HEIGHT=10;class Ht{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 Ht(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 Ht?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 Ht(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 Ht(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 Ht(this.field,n)}multiplyScalar(e){if(e===0)return new Ht(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 Ht(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new Ht(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 Ht(this.field,s)}toString(){let e=new ge;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 ed{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 et;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 qi extends ed{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 Ht(this,new Int32Array([0])),this.one=new Ht(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 Ht(this,i)}}qi.PDF417_GF=new qi(Le.NUMBER_OF_CODEWORDS,3);class ls{constructor(){this.field=qi.PDF417_GF}decode(e,n,i){let s=new Ht(this.field,e),a=new Int32Array(n),l=!1;for(let F=n;F>0;F--){let V=s.evaluateAt(this.field.exp(F));a[n-F]=V,V!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const F of i){let V=this.field.exp(e.length-1-F),W=new Ht(this.field,new Int32Array([this.field.subtract(0,V),1]));d=d.multiply(W)}let h=new Ht(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],b=p[1],I=this.findErrorLocations(y),R=this.findErrorMagnitudes(b,y,I);for(let F=0;F<I.length;F++){let V=e.length-1-this.field.log(I[F]);if(V<0)throw T.getChecksumInstance();e[V]=this.field.subtract(e[V],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 T.getChecksumInstance();a=I;let F=this.field.getZero(),V=s.getCoefficient(s.getDegree()),W=this.field.inverse(V);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Q=a.getDegree()-s.getDegree(),ce=this.field.multiply(a.getCoefficient(a.getDegree()),W);F=F.add(this.field.buildMonomial(Q,ce)),a=a.subtract(s.multiplyByMonomial(Q,ce))}d=F.multiply(l).subtract(R).negative()}let h=d.getCoefficient(0);if(h===0)throw T.getChecksumInstance();let p=this.field.inverse(h),y=d.multiply(p),b=a.multiply(p);return[y,b]}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 T.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 Ht(this.field,a),d=i.length,h=new Int32Array(d);for(let p=0;p<d;p++){let y=this.field.inverse(i[p]),b=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(b,I)}return h}}class ar{constructor(e,n,i,s,a){e instanceof ar?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 H;l?(n=new Ce(0,s.getY()),i=new Ce(0,a.getY())):d&&(s=new Ce(e.getWidth()-1,n.getY()),a=new Ce(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 ar(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 Ce(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 Ce(h.getX(),p);i?a=y:d=y}return new ar(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 td{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 Mr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,p,y,b){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(b){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),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<F;)R=d!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Mr.form(e,n)}toString(){return this.buffer}}class Dr{constructor(e){this.boundingBox=new ar(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<Dr.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 Mr;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()}}Dr.MAX_NEARBY_DISTANCE=5;class Pr{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 Le.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class cs extends Dr{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 b=l;b<d;b++){if(n[b]==null)continue;let I=n[b],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>b)n[b]=null;else{let F;p>2?F=(p-2)*R:F=R;let V=F>=b;for(let W=1;W<=F&&!V;W++)V=n[b-W]!=null;V?n[b]=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 b=y.getRowNumber()-h;b===0||(b===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?d[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Pr,i=new Pr,s=new Pr,a=new Pr;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]<Le.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>Le.MAX_ROWS_IN_BARCODE)return null;let l=new td(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+`
68
- `+super.toString()}}class Br{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=Le.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=Br.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=Br.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(Br.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 Mr;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 Lr{constructor(e,n,i,s){this.rowNumber=Lr.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!==Lr.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}}Lr.BARCODE_ROW_UNKNOWN=-1;class nn{static initialize(){for(let e=0;e<Le.SYMBOL_TABLE.length;e++){let n=Le.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<Le.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,nn.RATIOS_TABLE[e]||(nn.RATIOS_TABLE[e]=new Array(Le.BARS_IN_MODULE)),nn.RATIOS_TABLE[e][Le.BARS_IN_MODULE-s-1]=Math.fround(a/Le.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=nn.getDecodedCodewordValue(nn.sampleBitCounts(e));return n!==-1?n:nn.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=je.sum(e),i=new Int32Array(Le.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Le.MODULES_IN_CODEWORD;l++){let d=n/(2*Le.MODULES_IN_CODEWORD)+l*n/Le.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=nn.getBitValue(e);return Le.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(Le.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=Nn.MAX_VALUE,a=-1;this.bSymbolTableReady||nn.initialize();for(let l=0;l<nn.RATIOS_TABLE.length;l++){let d=0,h=nn.RATIOS_TABLE[l];for(let p=0;p<Le.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=Le.SYMBOL_TABLE[l])}return a}}nn.bSymbolTableReady=!1,nn.RATIOS_TABLE=new Array(Le.SYMBOL_TABLE.length).map(C=>new Array(Le.BARS_IN_MODULE));class us{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 ds{static parseLong(e,n=void 0){return parseInt(e,n)}}class fs extends x{}fs.kind="NullPointerException";class nd{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new fs;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new D;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class rd extends x{}class id extends nd{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 rd;i=Z.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 D;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 ct;(function(C){C[C.ALPHA=0]="ALPHA",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.PUNCT=3]="PUNCT",C[C.ALPHA_SHIFT=4]="ALPHA_SHIFT",C[C.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(ct||(ct={}));function hs(){if(typeof window<"u")return window.BigInt||null;if(typeof Ai<"u")return Ai.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let ui;function Kn(C){if(typeof ui>"u"&&(ui=hs()),ui===null)throw new Error("BigInt is not supported!");return ui(C)}function od(){let C=[];C[0]=Kn(1);let e=Kn(900);C[1]=e;for(let n=2;n<16;n++)C[n]=C[n-1]*e;return C}class J{static decode(e,n){let i=new ge(""),s=U.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new us;for(;a<e[0];){switch(l){case J.TEXT_COMPACTION_MODE_LATCH:a=J.textCompaction(e,a,i);break;case J.BYTE_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH_6:a=J.byteCompaction(l,e,s,a,i);break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:i.append(e[a++]);break;case J.NUMERIC_COMPACTION_MODE_LATCH:a=J.numericCompaction(e,a,i);break;case J.ECI_CHARSET:U.getCharacterSetECIByValue(e[a++]);break;case J.ECI_GENERAL_PURPOSE:a+=2;break;case J.ECI_USER_DEFINED:a++;break;case J.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=J.decodeMacroBlock(e,a,d);break;case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case J.MACRO_PDF417_TERMINATOR:throw new L;default:a--,a=J.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw L.getFormatInstance()}if(i.length()===0)throw L.getFormatInstance();let h=new fe(null,i.toString(),null,n);return h.setOther(d),h}static decodeMacroBlock(e,n,i){if(n+J.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw L.getFormatInstance();let s=new Int32Array(J.NUMBER_OF_SEQUENCE_CODEWORDS);for(let d=0;d<J.NUMBER_OF_SEQUENCE_CODEWORDS;d++,n++)s[d]=e[n];i.setSegmentIndex(Z.parseInt(J.decodeBase900toBase10(s,J.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new ge;n=J.textCompaction(e,n,a),i.setFileId(a.toString());let l=-1;for(e[n]===J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case J.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let d=new ge;n=J.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new ge;n=J.textCompaction(e,n+1,h),i.setSender(h.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new ge;n=J.textCompaction(e,n+1,p),i.setAddressee(p.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new ge;n=J.numericCompaction(e,n+1,y),i.setSegmentCount(Z.parseInt(y.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let b=new ge;n=J.numericCompaction(e,n+1,b),i.setTimestamp(ds.parseLong(b.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new ge;n=J.numericCompaction(e,n+1,I),i.setChecksum(Z.parseInt(I.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let R=new ge;n=J.numericCompaction(e,n+1,R),i.setFileSize(ds.parseLong(R.toString()));break;default:throw L.getFormatInstance()}break;case J.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw L.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<J.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case J.TEXT_COMPACTION_MODE_LATCH:s[l++]=J.TEXT_COMPACTION_MODE_LATCH;break;case J.BYTE_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH_6:case J.NUMERIC_COMPACTION_MODE_LATCH:case J.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case J.MACRO_PDF417_TERMINATOR:n--,d=!0;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return J.decodeTextCompaction(s,a,l,i),n}static decodeTextCompaction(e,n,i,s){let a=ct.ALPHA,l=ct.ALPHA,d=0;for(;d<i;){let h=e[d],p="";switch(a){case ct.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case J.LL:a=ct.LOWER;break;case J.ML:a=ct.MIXED;break;case J.PS:l=a,a=ct.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break;case ct.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case J.AS:l=a,a=ct.ALPHA_SHIFT;break;case J.ML:a=ct.MIXED;break;case J.PS:l=a,a=ct.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break;case ct.MIXED:if(h<J.PL)p=J.MIXED_CHARS[h];else switch(h){case J.PL:a=ct.PUNCT;break;case 26:p=" ";break;case J.LL:a=ct.LOWER;break;case J.AL:a=ct.ALPHA;break;case J.PS:l=a,a=ct.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break;case ct.PUNCT:if(h<J.PAL)p=J.PUNCT_CHARS[h];else switch(h){case J.PAL:a=ct.ALPHA;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break;case ct.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break;case ct.PUNCT_SHIFT:if(a=l,h<J.PAL)p=J.PUNCT_CHARS[h];else switch(h){case J.PAL:a=ct.ALPHA;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=ct.ALPHA;break}break}p!==""&&s.append(p),d++}}static byteCompaction(e,n,i,s,a){let l=new id,d=0,h=0,p=!1;switch(e){case J.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),b=n[s++];for(;s<n[0]&&!p;)switch(y[d++]=b,h=900*h+b,b=n[s++],b){case J.TEXT_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH:case J.NUMERIC_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH_6:case J.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case J.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(d%5===0&&d>0){for(let I=0;I<6;++I)l.write(Number(Kn(h)>>Kn(8*(5-I))));h=0,d=0}break}s===n[0]&&b<J.TEXT_COMPACTION_MODE_LATCH&&(y[d++]=b);for(let I=0;I<d;I++)l.write(y[I]);break;case J.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<J.TEXT_COMPACTION_MODE_LATCH)d++,h=900*h+I;else switch(I){case J.TEXT_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH:case J.NUMERIC_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH_6:case J.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case J.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(d%5===0&&d>0){for(let R=0;R<6;++R)l.write(Number(Kn(h)>>Kn(8*(5-R))));h=0,d=0}}break}return a.append(Y.decode(l.toByteArray(),i)),s}static numericCompaction(e,n,i){let s=0,a=!1,l=new Int32Array(J.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let d=e[n++];if(n===e[0]&&(a=!0),d<J.TEXT_COMPACTION_MODE_LATCH)l[s]=d,s++;else switch(d){case J.TEXT_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH:case J.BYTE_COMPACTION_MODE_LATCH_6:case J.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case J.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%J.MAX_NUMERIC_CODEWORDS===0||d===J.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(i.append(J.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let i=Kn(0);for(let a=0;a<n;a++)i+=J.EXP900[n-a-1]*Kn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new L;return s.substring(1)}}J.TEXT_COMPACTION_MODE_LATCH=900,J.BYTE_COMPACTION_MODE_LATCH=901,J.NUMERIC_COMPACTION_MODE_LATCH=902,J.BYTE_COMPACTION_MODE_LATCH_6=924,J.ECI_USER_DEFINED=925,J.ECI_GENERAL_PURPOSE=926,J.ECI_CHARSET=927,J.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,J.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,J.MACRO_PDF417_TERMINATOR=922,J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,J.MAX_NUMERIC_CODEWORDS=15,J.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,J.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,J.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,J.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,J.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,J.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,J.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,J.PL=25,J.LL=27,J.AS=27,J.ML=28,J.AL=28,J.PS=29,J.PAL=29,J.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
69
- -.$/"|*()?{}'`,J.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",J.EXP900=hs()?od():[],J.NUMBER_OF_SEQUENCE_CODEWORDS=2;class $e{constructor(){}static decode(e,n,i,s,a,l,d){let h=new ar(e,n,i,s,a),p=null,y=null,b;for(let F=!0;;F=!1){if(n!=null&&(p=$e.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(y=$e.getRowIndicatorColumn(e,h,s,!1,l,d)),b=$e.merge(p,y),b==null)throw H.getNotFoundInstance();let V=b.getBoundingBox();if(F&&V!=null&&(V.getMinY()<h.getMinY()||V.getMaxY()>h.getMaxY()))h=V;else break}b.setBoundingBox(h);let I=b.getBarcodeColumnCount()+1;b.setDetectionResultColumn(0,p),b.setDetectionResultColumn(I,y);let R=p!=null;for(let F=1;F<=I;F++){let V=R?F:I-F;if(b.getDetectionResultColumn(V)!==void 0)continue;let W;V===0||V===I?W=new cs(h,V===0):W=new Dr(h),b.setDetectionResultColumn(V,W);let Q=-1,ce=Q;for(let de=h.getMinY();de<=h.getMaxY();de++){if(Q=$e.getStartColumn(b,V,de,R),Q<0||Q>h.getMaxX()){if(ce===-1)continue;Q=ce}let ae=$e.detectCodeword(e,h.getMinX(),h.getMaxX(),R,Q,de,l,d);ae!=null&&(W.setCodeword(de,ae),ce=Q,l=Math.min(l,ae.getWidth()),d=Math.max(d,ae.getWidth()))}}return $e.createDecoderResult(b)}static merge(e,n){if(e==null&&n==null)return null;let i=$e.getBarcodeMetadata(e,n);if(i==null)return null;let s=ar.merge($e.adjustBoundingBox(e),$e.adjustBoundingBox(n));return new Br(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=$e.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 cs(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(i.getX()));for(let b=Math.trunc(Math.trunc(i.getY()));b<=n.getMaxY()&&b>=n.getMinY();b+=p){let I=$e.detectCodeword(e,0,e.getWidth(),s,y,b,a,l);I!=null&&(d.setCodeword(b,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()-$e.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Le.MAX_CODEWORDS_IN_BARCODE)throw H.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=$e.createBarcodeMatrix(e);$e.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(),b=h*e.getBarcodeColumnCount()+p;y.length===0?i.push(b):y.length===1?s[b]=y[0]:(l.push(b),a.push(y))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return $e.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Le.toIntArray(i),Le.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 $e.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof T))throw h}if(l.length===0)throw T.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 T.getChecksumInstance()}throw T.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 Pr;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($e.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($e.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;$e.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=$e.adjustCodewordStartColumn(e,n,i,s,a,l);let p=$e.getModuleBitCount(e,n,i,s,a,l);if(p==null)return null;let y,b=je.sum(p);if(s)y=a+b;else{for(let F=0;F<p.length/2;F++){let V=p[F];p[F]=p[p.length-1-F],p[p.length-1-F]=V}y=a,a=y-b}if(!$e.checkCodewordSkew(b,d,h))return null;let I=nn.getDecodedValue(p),R=Le.getCodeword(I);return R===-1?null:new Lr(a,y,$e.getCodewordBucketNumber(I),R)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),p=0,y=s?1:-1,b=s;for(;(s?d<i:d>=n)&&p<h.length;)e.get(d,l)===b?(h[p]++,d+=y):(p++,b=!b);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)>$e.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-$e.CODEWORD_SKEW_SIZE<=e&&e<=i+$e.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw L.getFormatInstance();let s=1<<n+1,a=$e.correctErrors(e,i,s);$e.verifyCodewordCount(e,s);let l=J.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(i.length),l}static correctErrors(e,n,i){if(n!=null&&n.length>i/2+$e.MAX_ERRORS||i<0||i>$e.MAX_EC_CODEWORDS)throw T.getChecksumInstance();return $e.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw L.getFormatInstance();let i=e[0];if(i>e.length)throw L.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw L.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 $e.getCodewordBucketNumber($e.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Mr;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()}}$e.CODEWORD_SKEW_SIZE=2,$e.MAX_ERRORS=3,$e.MAX_EC_CODEWORDS=512,$e.errorCorrection=new ls;class Wt{decode(e,n=null){let i=Wt.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw H.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Wt.decode(e,n,!0)}catch(i){throw i instanceof L||i instanceof T?H.getNotFoundInstance():i}}static decode(e,n,i){const s=new Array,a=Ze.detectMultiple(e,n,i);for(const l of a.getPoints()){const d=$e.decode(a.getBits(),l[4],l[5],l[6],l[7],Wt.getMinCodewordWidth(l),Wt.getMaxCodewordWidth(l)),h=new be(d.getText(),d.getRawBytes(),void 0,l,te.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?Z.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Wt.getMaxWidth(e[0],e[4]),Wt.getMaxWidth(e[6],e[2])*Le.MODULES_IN_CODEWORD/Le.MODULES_IN_STOP_PATTERN),Math.max(Wt.getMaxWidth(e[1],e[5]),Wt.getMaxWidth(e[7],e[3])*Le.MODULES_IN_CODEWORD/Le.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Wt.getMinWidth(e[0],e[4]),Wt.getMinWidth(e[6],e[2])*Le.MODULES_IN_CODEWORD/Le.MODULES_IN_STOP_PATTERN),Math.min(Wt.getMinWidth(e[1],e[5]),Wt.getMinWidth(e[7],e[3])*Le.MODULES_IN_CODEWORD/Le.MODULES_IN_STOP_PATTERN)))}reset(){}}class di extends x{}di.kind="ReaderException";class ps{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(P.TRY_HARDER)===!0,i=c(e)?null:e.get(P.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===te.UPC_A||l===te.UPC_E||l===te.EAN_13||l===te.EAN_8||l===te.CODABAR||l===te.CODE_39||l===te.CODE_93||l===te.CODE_128||l===te.ITF||l===te.RSS_14||l===te.RSS_EXPANDED);a&&!n&&s.push(new Cr(e,this.verbose)),i.includes(te.QR_CODE)&&s.push(new Yn),i.includes(te.DATA_MATRIX)&&s.push(new qn),i.includes(te.AZTEC)&&s.push(new Ye),i.includes(te.PDF_417)&&s.push(new Wt),a&&n&&s.push(new Cr(e,this.verbose))}s.length===0&&(n||s.push(new Cr(e,this.verbose)),s.push(new Yn),s.push(new qn),s.push(new Ye),s.push(new Wt),n&&s.push(new Cr(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 di("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 di)continue}throw new H("No MultiFormat Readers were able to detect the code.")}}class sd extends Je{constructor(e=null,n=500){const i=new ps;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class ad extends Je{constructor(e=500){super(new Wt,e)}}class ld extends Je{constructor(e=500){super(new Yn,e)}}var Yi;(function(C){C[C.ERROR_CORRECTION=0]="ERROR_CORRECTION",C[C.CHARACTER_SET=1]="CHARACTER_SET",C[C.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",C[C.MIN_SIZE=3]="MIN_SIZE",C[C.MAX_SIZE=4]="MAX_SIZE",C[C.MARGIN=5]="MARGIN",C[C.PDF417_COMPACT=6]="PDF417_COMPACT",C[C.PDF417_COMPACTION=7]="PDF417_COMPACTION",C[C.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",C[C.AZTEC_LAYERS=9]="AZTEC_LAYERS",C[C.QR_VERSION=10]="QR_VERSION"})(Yi||(Yi={}));var Ft=Yi;class Ki{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 Tt{constructor(){}static applyMaskPenaltyRule1(e){return Tt.applyMaskPenaltyRule1Internal(e,!0)+Tt.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 Tt.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&&(Tt.isWhiteHorizontal(h,d-4,d)||Tt.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&&(Tt.isWhiteVertical(i,d,l-4,l)||Tt.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*Tt.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)*Tt.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 b=n?l[d][y]:l[y][d];b===p?h++:(h>=5&&(i+=Tt.N1+(h-5)),h=1,p=b)}h>=5&&(i+=Tt.N1+(h-5))}return i}}Tt.N1=3,Tt.N2=3,Tt.N3=40,Tt.N4=10;class fi{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 fi))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 ge;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(`
70
- `)}return e.toString()}}class lr{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 ge;return e.append(`<<
60
+ `}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const xi={model:"deepseek-ai/DeepSeek-V3",maxSteps:30,extraTools:{}},Xa={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function gx(t,r){if(!r&&!t)return;if(!t)return r;if(!r)return t;const i={...r};for(const[c,d]of Object.entries(t))d&&typeof d=="object"&&!Array.isArray(d)?i[c]={...i[c]||{},...d}:i[c]=d;return i}class xx extends Kn.BaseModelProvider{transport;agent;promptManager;llmConfig={...xi,...Xa};isGenuiEnabled;debugStream=!1;emit;constructor(r,i,c,d){super(r);let f;c&&"llm"in c?f={...xi,...c}:f={...xi,...Xa,...c||{}},this.llmConfig=f;const x={llmConfig:f.llm?{llm:f.llm}:{...f}};this.agent=new Jn.AgentModelProvider(x),this.promptManager=new mx,this.promptManager.setStatic(i),this.emit=d}updateLLMConfig({model:r,baseURL:i,genuiUrl:c,apiKey:d,providerType:f,useReActMode:m,llm:x,providerOptions:v,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&&i&&d){const E=this.isGenuiEnabled?.value&&c||i;this.llmConfig.model=r,this.llmConfig.apiKey=d,this.llmConfig.baseURL=i,this.llmConfig.providerType=f,this.llmConfig.useReActMode=m||!1,this.agent.useReActMode=m||!1;let A;if(f==="deepseek")A=kc;else if(f==="openai")A=Ou;else if(typeof f=="function")A=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=A({apiKey:d,baseURL:E,...g?{headers:g}:{}})}this.llmConfig.providerOptions=v,this.llmConfig.headers=g}cleanGetSkillContentToolResult(r){const i=r[r.length-1];if(i.role==="tool"&&i.content.length>0){const c=i.content[i.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",d=r[r.length-1];if(!d||d.role!==c||!this.isSnapshotContent(d.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 i=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of i){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 d=["已成功获取页面无障碍树快照","takeSnapshot","snapshotId_counter"];for(const f of d)if(r.startsWith(f))return"📸 历史快照已清理";return r}replaceSnapshotWithPlaceholder(r){if(Array.isArray(r.content)){const i=r.content[0];if(i?.output?.value?.content){const c=i.output.value.content;Array.isArray(c)&&(i.output.value.content=c.map(d=>d.type==="image"||d.type==="image_url"?null:d.type==="text"&&d.text&&this.isSnapshotContent(d.text)?{type:"text",text:this.removeSnapshotData(d.text)}:d).filter(d=>d!==null)),i.output.value.screenshot&&delete i.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 i=["无障碍树快照","takeSnapshot","snapshotId_counter","UID 格式","快照 ID","操作后的页面快照","已成功获取页面无障碍树快照","快照内容:"];if(typeof r=="string")return i.some(c=>r.includes(c));if(Array.isArray(r))for(const c of r){const d=c?.output?.value?.content?.[0]?.text;if(d&&i.some(f=>d.includes(f))||c.type==="text"&&c.text&&i.some(f=>c.text.includes(f))||c.type==="image"||c.type==="image_url")return!0}return!1}async chatStream(r,i){let c=r.messages[r.messages.length-1];if(!c)return;const d={model:this.llmConfig.model,system:this.promptManager.getSystemPrompt(),abortSignal:r.options?.signal,toolChoice:"auto",tools:this.llmConfig.extraTools||{},maxSteps:this.llmConfig.maxSteps,providerOptions:gx(this.llmConfig.providerOptions,fx),prepareStep:({messages:T})=>{this.cleanGetSkillContentToolResult(T);const S=this.cleanupOldSnapshotsInMessages(T),P=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(ee=>{P.push(...Object.keys(ee||{}))});const M=Array.from(new Set(P)).filter(ee=>!this.agent.ignoreToolnames.includes(ee));return{system:this.promptManager.getSystemPrompt(),messages:S,activeTools:M}},onStepFinish:T=>{if(T.finishReason==="tool-calls"&&T.content.length>0){const S=T.content[T.content.length-1];if(S.toolName==="get_skill_content"&&S.type==="tool-result"){const P=S.output.content;this.promptManager.appendTemp(P)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp(""),this.emit?.("chat-stream-finish")}},f={role:"user",content:c.content},x=[...(T=>T.map(S=>({role:S.role,content:S.content})))(this.agent.responseMessages),f];d.messages=x;const v=await this.agent.chatStream(d),g=new qp,A=await new hx({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{g.resolve(),i.onDone()})}}).traverse(v),D={role:"assistant",content:"",uiContent:[]};return _.watch(A,T=>{if(!T)i.onData(D);else{const P=T.steps.map(M=>M.contents).flat().map(M=>{if(M.type==="text")return px(M.text);if(M.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:M.text,thinkId:M.id};if(M.type==="tool")return{type:"tool",id:M.id,name:M.toolName,content:JSON.stringify({input:M.inputStr,output:M.output}),status:M.error?"failed":M.running?"running":"success"}});if(T?.error){const M={type:"markdown",content:`**错误**:${T.error.responseBody||T.error.message||"未知错误"}`};P.push(M)}(T.steps.length>=1||T?.error)&&i.onData({...D,uiContent:P.flat(),usage:T.totalUsage||null})}},{deep:!0}),g.promise}chat(r){throw new Error("Method not implemented.")}}const yx=({systemPrompt:t,llmConfig:r,emit:i})=>{const c=new xx({provider:"custom"},t,r,i),d=new Kn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:x,switchConversation:v,deleteConversation:g,updateTitle:E,state:A}=Kn.useConversation({client:d,autoSave:!0,events:{onLoaded(){},onReceiveData(Z,B,L){L(),B.value[B.value.length-1].role==="assistant"&&B.value.pop(),i("before-ai-render",Z),B.value.push(Z)}}}),{messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,messages:M,addMessage:ee,send:$}=f,F=_.ref(),re=async(Z,B,L)=>{if(L){const{shouldBlock:z}=await L(Z);if(z)return!1}T.value=Z;const W=x();if(W&&W.title==="新会话"&&E(W.id,T.value.slice(0,15)),B&&B.length>0){const z=[{type:"text",text:T.value},...B],we=[];T.value&&we.push({type:"text",content:T.value});for(const me of B)me.type==="image"&&me.image&&we.push({type:"image",content:me.image});const G={role:"user",content:z,uiContent:we};M.value.push(G),T.value="",$()}else{const z={role:"user",content:T.value,uiContent:[{type:"text",content:T.value}]};M.value.push(z),T.value="",$()}return!0};return _.onMounted(()=>{F.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:d,messageManager:f,addMessage:ee,send:$,conversationState:A,messages:M,messageState:D,inputMessage:T,sendMessage:S,abortRequest:P,senderRef:F,handleSendMessage:re,createConversation:m,switchConversation:v,deleteConversation:g,getCurrentConversation:x}};function wx(){}const Pn=Object.assign,ts=typeof window<"u",Zo=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Pi=t=>typeof t=="function",_x=t=>Zo(t)&&Pi(t.then)&&Pi(t.catch),ku=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),vx=()=>ts?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Ya(t,r){const i=r.split(".");let c=t;return i.forEach(d=>{var f;c=Zo(c)&&(f=c[d])!=null?f:""}),c}function Cx(t,r,i){return r.reduce((c,d)=>(c[d]=t[d],c),{})}const Po=null,un=[Number,String],pr={type:Boolean,default:!0},bx=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var ns=typeof window<"u";function Ru(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function Mu(t,r,i={}){if(!ns)return;const{target:c=window,passive:d=!1,capture:f=!1}=i;let m=!1,x;const v=A=>{if(m)return;const D=_.unref(A);D&&!x&&(D.addEventListener(t,r,{capture:f,passive:d}),x=!0)},g=A=>{if(m)return;const D=_.unref(A);D&&x&&(D.removeEventListener(t,r,f),x=!1)};_.onUnmounted(()=>g(c)),_.onDeactivated(()=>g(c)),Ru(()=>v(c));let E;return _.isRef(c)&&(E=_.watch(c,(A,D)=>{g(D),v(A)})),()=>{E?.(),g(c),m=!0}}var Eo,yi;function Ax(){if(!Eo&&(Eo=_.ref(0),yi=_.ref(0),ns)){const t=()=>{Eo.value=window.innerWidth,yi.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:Eo,height:yi}}var Ex=/scroll|auto|overlay/i,Ix=ns?window:void 0;function Sx(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Ka(t,r=Ix){let i=t;for(;i&&i!==r&&Sx(i);){const{overflowY:c}=window.getComputedStyle(i);if(Ex.test(c))return i;i=i.parentNode}return r}vx();const Tx=t=>t.stopPropagation();function Du(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),Tx(t)}Ax();function vn(t){if(tr(t))return ku(t)?`${t}px`:String(t)}function Nx(t){if(tr(t)){if(Array.isArray(t))return{width:vn(t[0]),height:vn(t[1])};const r=vn(t);return{width:r,height:r}}}function Ox(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const kx=/-(\w)/g,Pu=t=>t.replace(kx,(r,i)=>i.toUpperCase()),Rx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:Mx}=Object.prototype;function Dx(t,r,i){const c=r[i];tr(c)&&(!Mx.call(t,i)||!Zo(c)?t[i]=c:t[i]=Bu(Object(t[i]),c))}function Bu(t,r){return Object.keys(r).forEach(i=>{Dx(t,r,i)}),t}var Px={name:"姓名",tel:"电话",save:"保存",clear:"清空",undo:"撤销",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=_.ref("zh-CN"),Qa=_.reactive({"zh-CN":Px}),Bx={messages(){return Qa[Ja.value]},use(t,r){Ja.value=t,this.add({[t]:r})},add(t={}){Bu(Qa,t)}};var Lx=Bx;function Fx(t){const r=Pu(t)+".";return(i,...c)=>{const d=Lx.messages(),f=Ya(d,r+i)||Ya(d,i);return Pi(f)?f(...c):f}}function Bi(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((i,c)=>i+Bi(t,c),""):Object.keys(r).reduce((i,c)=>i+(r[c]?Bi(t,c):""),""):""}function Ux(t){return(r,i)=>(r&&typeof r!="string"&&(i=r,r=""),r=r?`${t}__${r}`:t,`${r}${Bi(r,i)}`)}function yr(t){const r=`van-${t}`;return[r,Ux(r),Fx(r)]}const zx="van-haptics-feedback",el=5;function Vx(t,{args:r=[],done:i,canceled:c,error:d}){if(t){const f=t.apply(null,r);_x(f)?f.then(m=>{m?i():c&&c()}).catch(d||wx):f?i():c&&c()}else i()}function lo(t){return t.install=r=>{const{name:i}=t;i&&(r.component(i,t),r.component(Pu(`-${i}`),t))},t}const Zx=Symbol();function Lu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[$x,tl]=yr("badge"),jx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:pr,position:dn("top-right")};var Hx=_.defineComponent({name:$x,props:jx,setup(t,{slots:r}){const i=()=>{if(r.content)return!0;const{content:x,showZero:v}=t;return tr(x)&&x!==""&&(v||x!==0&&x!=="0")},c=()=>{const{dot:x,max:v,content:g}=t;if(!x&&i())return r.content?r.content():tr(v)&&ku(g)&&+g>+v?`${v}+`:g},d=x=>x.startsWith("-")?x.replace("-",""):`-${x}`,f=_.computed(()=>{const x={background:t.color};if(t.offset){const[v,g]=t.offset,{position:E}=t,[A,D]=E.split("-");r.default?(typeof g=="number"?x[A]=vn(A==="top"?g:-g):x[A]=A==="top"?vn(g):d(g),typeof v=="number"?x[D]=vn(D==="left"?v:-v):x[D]=D==="left"?vn(v):d(v)):(x.marginTop=vn(g),x.marginLeft=vn(v))}return x}),m=()=>{if(i()||t.dot)return _.createVNode("div",{class:tl([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:x}=t;return _.createVNode(x,{class:tl("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const Wx=lo(Hx);let Fu=2e3;const Gx=()=>++Fu,qx=t=>{Fu=t},[Uu,Xx]=yr("config-provider"),zu=Symbol(Uu),Yx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function Kx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function Jx(t){const r={};return Object.keys(t).forEach(i=>{const c=Kx(Rx(i));r[`--van-${c}`]=t[i]}),r}function Io(t={},r={}){Object.keys(t).forEach(i=>{t[i]!==r[i]&&document.documentElement.style.setProperty(i,t[i])}),Object.keys(r).forEach(i=>{t[i]||document.documentElement.style.removeProperty(i)})}_.defineComponent({name:Uu,props:Yx,setup(t,{slots:r}){const i=_.computed(()=>Jx(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(ts){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},d=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};_.watch(()=>t.theme,(f,m)=>{m&&d(m),c()},{immediate:!0}),_.onActivated(c),_.onDeactivated(d),_.onBeforeUnmount(d),_.watch(i,(f,m)=>{t.themeVarsScope==="global"&&Io(f,m)}),_.watch(()=>t.themeVarsScope,(f,m)=>{m==="global"&&Io({},i.value),f==="global"&&Io(i.value,{})}),t.themeVarsScope==="global"&&Io(i.value,{})}return _.provide(zu,t),_.watchEffect(()=>{t.zIndex!==void 0&&qx(t.zIndex)}),()=>_.createVNode(t.tag,{class:Xx(),style:t.themeVarsScope==="local"?i.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[Qx,nl]=yr("icon"),ey=t=>t?.includes("/"),ty={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var ny=_.defineComponent({name:Qx,props:ty,setup(t,{slots:r}){const i=_.inject(zu,null),c=_.computed(()=>t.classPrefix||i?.iconPrefix||nl());return()=>{const{tag:d,dot:f,name:m,size:x,badge:v,color:g}=t,E=ey(m);return _.createVNode(Wx,_.mergeProps({dot:f,tag:d,class:[c.value,E?"":`${c.value}-${m}`],style:{color:g,fontSize:vn(x)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&_.createVNode("img",{class:nl("image"),src:m},null)]}})}}});const rs=lo(ny),[ry,Kr]=yr("loading"),oy=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Kr("line",String(r+1))},null)),iy=_.createVNode("svg",{class:Kr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),sy={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var ay=_.defineComponent({name:ry,props:sy,setup(t,{slots:r}){const i=_.computed(()=>Pn({color:t.color},Nx(t.size))),c=()=>{const f=t.type==="spinner"?oy:iy;return _.createVNode("span",{class:Kr("spinner",t.type),style:i.value},[r.icon?r.icon():f])},d=()=>{var f;if(r.default)return _.createVNode("span",{class:Kr("text"),style:{fontSize:vn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:m}=t;return _.createVNode("div",{class:Kr([f,{vertical:m}]),"aria-live":"polite","aria-busy":!0},[c(),d()])}}});const ly=lo(ay),cy={show:Boolean,zIndex:un,overlay:pr,duration:un,teleport:[String,Object],lockScroll:pr,lazyRender:pr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Po,transitionAppear:Boolean,closeOnClickOverlay:pr};function uy(t,r){return t>r?"horizontal":r>t?"vertical":""}function dy(){const t=_.ref(0),r=_.ref(0),i=_.ref(0),c=_.ref(0),d=_.ref(0),f=_.ref(0),m=_.ref(""),x=_.ref(!0),v=()=>m.value==="vertical",g=()=>m.value==="horizontal",E=()=>{i.value=0,c.value=0,d.value=0,f.value=0,m.value="",x.value=!0};return{move:(T=>{const S=T.touches[0];i.value=(S.clientX<0?0:S.clientX)-t.value,c.value=S.clientY-r.value,d.value=Math.abs(i.value),f.value=Math.abs(c.value);const P=10;(!m.value||d.value<P&&f.value<P)&&(m.value=uy(d.value,f.value)),x.value&&(d.value>el||f.value>el)&&(x.value=!1)}),start:(T=>{E(),t.value=T.touches[0].clientX,r.value=T.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:i,deltaY:c,offsetX:d,offsetY:f,direction:m,isVertical:v,isHorizontal:g,isTap:x}}let Hr=0;const rl="van-overflow-hidden";function fy(t,r){const i=dy(),c="01",d="10",f=E=>{i.move(E);const A=i.deltaY.value>0?d:c;let D=Ka(E.target,t.value);for(;D.scrollHeight<=D.offsetHeight&&D!==t.value&&D.parentElement;)D=Ka(D.parentElement,t.value);const{scrollHeight:T,offsetHeight:S,scrollTop:P}=D;let M="11";P===0?M=S>=T?"00":"01":P+S>=T&&(M="10"),M!=="11"&&i.isVertical()&&!(parseInt(M,2)&parseInt(A,2))&&Du(E)},m=()=>{document.addEventListener("touchstart",i.start),document.addEventListener("touchmove",f,{passive:!1}),Hr||document.body.classList.add(rl),Hr++},x=()=>{Hr&&(document.removeEventListener("touchstart",i.start),document.removeEventListener("touchmove",f),Hr--,Hr||document.body.classList.remove(rl))},v=()=>r()&&m(),g=()=>r()&&x();Ru(v),_.onDeactivated(g),_.onBeforeUnmount(g),_.watch(r,E=>{E?m():x()})}function Vu(t){const r=_.ref(!1);return _.watch(t,i=>{i&&(r.value=i)},{immediate:!0}),i=>()=>r.value?i():null}const ol=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[hy,py]=yr("overlay"),my={show:Boolean,zIndex:un,duration:un,className:Po,lockScroll:pr,lazyRender:pr,customStyle:Object,teleport:[String,Object]};var gy=_.defineComponent({name:hy,inheritAttrs:!1,props:my,setup(t,{attrs:r,slots:i}){const c=_.ref(),d=Vu(()=>t.show||!t.lazyRender),f=x=>{t.lockScroll&&Du(x)},m=d(()=>{var x;const v=Pn(Ox(t.zIndex),t.customStyle);return tr(t.duration)&&(v.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:v,class:[py(),t.className]},r),[(x=i.default)==null?void 0:x.call(i)]),[[_.vShow,t.show]])});return Mu("touchmove",f,{target:c}),()=>{const x=_.createVNode(_.Transition,{name:"van-fade",appear:!0},{default:m});return t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[x]}):x}}});const xy=lo(gy),yy=Pn({},cy,{round:Boolean,position:dn("center"),closeIcon:dn("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:dn("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[wy,il]=yr("popup");var _y=_.defineComponent({name:wy,inheritAttrs:!1,props:yy,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:i,slots:c}){let d,f;const m=_.ref(),x=_.ref(),v=Vu(()=>t.show||!t.lazyRender),g=_.computed(()=>{const B={zIndex:m.value};if(tr(t.duration)){const L=t.position==="center"?"animationDuration":"transitionDuration";B[L]=`${t.duration}s`}return B}),E=()=>{d||(d=!0,m.value=t.zIndex!==void 0?+t.zIndex:Gx(),r("open"))},A=()=>{d&&Vx(t.beforeClose,{done(){d=!1,r("close"),r("update:show",!1)}})},D=B=>{r("clickOverlay",B),t.closeOnClickOverlay&&A()},T=()=>{if(t.overlay){const B=Pn({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 _.createVNode(xy,_.mergeProps(B,ol(),{onClick:D}),{default:c["overlay-content"]})}},S=B=>{r("clickCloseIcon",B),A()},P=()=>{if(t.closeable)return _.createVNode(rs,{role:"button",tabindex:0,name:t.closeIcon,class:[il("close-icon",t.closeIconPosition),zx],classPrefix:t.iconPrefix,onClick:S},null)};let M;const ee=()=>{M&&clearTimeout(M),M=setTimeout(()=>{r("opened")})},$=()=>r("closed"),F=B=>r("keydown",B),re=v(()=>{var B;const{destroyOnClose:L,round:W,position:z,safeAreaInsetTop:we,safeAreaInsetBottom:G,show:me}=t;if(!(!me&&L))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:x,style:g.value,role:"dialog",tabindex:0,class:[il({round:W,[z]:z}),{"van-safe-area-top":we,"van-safe-area-bottom":G}],onKeydown:F},i,ol()),[(B=c.default)==null?void 0:B.call(c),P()]),[[_.vShow,me]])}),Z=()=>{const{position:B,transition:L,transitionAppear:W}=t,z=B==="center"?"van-fade":`van-popup-slide-${B}`;return _.createVNode(_.Transition,{name:L||z,appear:W,onAfterEnter:ee,onAfterLeave:$},{default:re})};return _.watch(()=>t.show,B=>{B&&!d&&(E(),i.tabindex===0&&_.nextTick(()=>{var L;(L=x.value)==null||L.focus()})),!B&&d&&(d=!1,r("close"))}),Lu({popupRef:x}),fy(x,()=>t.show&&t.lockScroll),Mu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),_.onMounted(()=>{t.show&&E()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),_.provide(Zx,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[T(),Z()]}):_.createVNode(_.Fragment,null,[T(),Z()])}});const vy=lo(_y);let Wr=0;function Cy(t){t?(Wr||document.body.classList.add("van-toast--unclickable"),Wr++):Wr&&(Wr--,Wr||document.body.classList.remove("van-toast--unclickable"))}const[by,Or]=yr("toast"),Ay=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Ey={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:bx(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:Po,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Po,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var Iy=_.defineComponent({name:by,props:Ey,emits:["update:show"],setup(t,{emit:r,slots:i}){let c,d=!1;const f=()=>{const A=t.show&&t.forbidClick;d!==A&&(d=A,Cy(d))},m=A=>r("update:show",A),x=()=>{t.closeOnClick&&m(!1)},v=()=>clearTimeout(c),g=()=>{const{icon:A,type:D,iconSize:T,iconPrefix:S,loadingType:P}=t;if(A||D==="success"||D==="fail")return _.createVNode(rs,{name:A||D,size:T,class:Or("icon"),classPrefix:S},null);if(D==="loading")return _.createVNode(ly,{class:Or("loading"),size:T,type:P},null)},E=()=>{const{type:A,message:D}=t;if(i.message)return _.createVNode("div",{class:Or("text")},[i.message()]);if(tr(D)&&D!=="")return A==="html"?_.createVNode("div",{key:0,class:Or("text"),innerHTML:String(D)},null):_.createVNode("div",{class:Or("text")},[D])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(vy,_.mergeProps({class:[Or([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:x,onClosed:v,"onUpdate:show":m},Cx(t,Ay)),{default:()=>[g(),E()]})}});function Sy(){const t=_.reactive({show:!1}),r=d=>{t.show=d},i=d=>{Pn(t,d,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Lu({open:i,close:c,toggle:r}),{open:i,close:c,state:t,toggle:r}}function Ty(t){const r=_.createApp(t),i=document.createElement("div");return document.body.appendChild(i),{instance:r.mount(i),unmount(){r.unmount(),document.body.removeChild(i)}}}const Ny={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 So=[],Oy=!1,sl=Pn({},Ny);const ky=new Map;function Zu(t){return Zo(t)?t:{message:t}}function Ry(){const{instance:t}=Ty({setup(){const r=_.ref(""),{open:i,state:c,close:d,toggle:f}=Sy(),m=()=>{},x=()=>{const v={onClosed:m,"onUpdate:show":f};return _.createVNode(Iy,_.mergeProps(c,v),null)};return _.watch(r,v=>{c.message=v}),_.getCurrentInstance().render=x,{open:i,close:d,message:r}}});return t}function My(){if(!So.length||Oy){const t=Ry();So.push(t)}return So[So.length-1]}function it(t={}){if(!ts)return{};const r=My(),i=Zu(t);return r.open(Pn({},sl,ky.get(i.type||sl.type),i)),r}const Dy=t=>r=>it(Pn({type:t},Zu(r))),$u=Dy("loading"),Py=t=>{try{const r=JSON.parse(t),i=[];if(!r.mcpServers||typeof r.mcpServers!="object")throw new Error("JSON 格式错误:缺少 mcpServers 字段");for(const[c,d]of Object.entries(r.mcpServers)){const f=By(d);f&&i.push({name:c,config:f})}return i}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},By=t=>{if(!t||typeof t!="object"||!t.url)return null;const{type:r,url:i,sessionId:c,headers:d}=t;return r==="streamableHttp"||r==="sse"?{type:r,url:i,headers:d,useAISdkClient:!0}:{type:"streamableHttp",url:i,headers:d,useAISdkClient:!0}},Ly=(t,r,i)=>{const c=async(f,m,x,v,g)=>{if(await t.insertMcpServer(f,m)){const A=t.mcpTools[f];if(A){const T={id:`plugin-${f.replace("mcp-server-","")}`,name:x,icon:g||i,description:v||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(S=>({id:S,name:S,description:A[S].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(T),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{$u("添加工具中...");try{if(f==="code"){if(typeof m!="string"){it("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=Py(m);if($.length===0){it("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let F=0,re=0;for(const{name:Z,config:B}of $){const L=`mcp-server-${Z}`;await c(L,B,Z)?F++:re++}await t.closeAll(),re===0?it(`成功添加 ${F} 个工具`):F>0?it(`成功添加 ${F} 个工具,${re} 个失败`):it("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){it("添加工具失败:数据格式不正确");return}const{description:x,headers:v,name:g,thumbnail:E,type:A,url:D}=m;if(!g||!D||!A){it("添加工具失败:缺少必要参数(名称、URL或类型)");return}const S=`mcp-server-${`custom-${g}-${Date.now()}`}`;let P;if(typeof v=="string"&&v.trim())try{P=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(P=v);await c(S,{type:A,url:D,headers:P,useAISdkClient:!0},g,x,E)?(await t.closeAll(),it("添加工具完成")):it("重复添加工具或无法获取工具列表")}catch(x){console.error("handleCustomAdd error:",x),it(`添加工具失败:${x instanceof Error?x.message:"未知错误"}`)}}}};function Fy(t,r,i){const c=_.ref([]),d=_.ref([]),f=_.ref(!1),m=Z=>t.mcpServers[Z]?.type==="local",x=(Z,B)=>{B?t.ignoreToolnames=t.ignoreToolnames.filter(L=>L!==Z):t.ignoreToolnames.includes(Z)||t.ignoreToolnames.push(Z)},v=(Z,B)=>{r.value||(r.value={});const L={...r.value};Z===null?Object.keys(L).forEach(W=>{L[W]=B}):L[Z]=B,r.value=L},g=Z=>{const B=d.value.find(L=>L.id===Z);B&&(B.addState="idle")},E=Z=>{const B=t.mcpTools[Z];if(!B)return[];const L=m(Z),W=r.value||{};return Object.keys(B).map(z=>{const we=Object.prototype.hasOwnProperty.call(W,z),G=L&&we?W[z]:!0;return x(z,G),{id:z,name:z,description:B[z].description,enabled:G}})},A=()=>{c.value.forEach(B=>{const L=new Map(B.tools.map(z=>[z.id,z.enabled])),W=E(B.id).map(z=>{const we=L.has(z.id)?!!L.get(z.id):z.enabled;return x(z.id,we),{...z,enabled:we}});B.tools=W});const Z=new Set(c.value.flatMap(B=>B.tools.map(L=>L.id)));t.ignoreToolnames=t.ignoreToolnames.filter(B=>Z.has(B))},D=async Z=>{const B=Z.pluginId;if(!await t.insertMcpServer(B,Z.mcpServer))return!1;if(!t.mcpTools[B])return await t.removeMcpServer(B),!1;const z=E(B);if(z.length===0&&Z.mcpServer?.type!=="builtin")return await t.removeMcpServer(B),!1;const we=c.value.find(me=>me.id===Z.pluginId);if(we)return we.tools=z,we.originMcpConfig=_.markRaw(Z.mcpServer),!0;const G={id:Z.pluginId,name:Z.name,icon:Z.icon||i,description:Z.description,enabled:!0,expanded:!1,tools:z,originMcpConfig:_.markRaw(Z.mcpServer)};return c.value.push(G),!0};return{installedPlugins:c,marketPlugins:d,pluginVisible:f,loadMcpServerToPlugin:async(Z,B)=>{let L=B.name,W=B.description;if(!L||!W){if("type"in B&&B.type==="local")L=L||"本地工具",W=W||"本地工具列表";else if("type"in B&&B.type==="builtin")L=L||"浏览器内置工具",W=W||"通过 document.modelContext 暴露的浏览器原生 MCP 工具";else if("url"in B)try{const z=new URL(B.url);L=L||z.origin,W=W||z.searchParams.get("sessionId")||("sessionId"in B?B.sessionId:"")||""}catch(z){console.error("[usePlugin] Failed to parse MCP server URL:",B.url,z),L=L||"未知插件",W=W||""}}await D({pluginId:Z,name:L||"",description:W||"",mcpServer:B})},togglePlugin:(Z,B)=>{const L=m(Z.id);Z.tools.forEach(W=>{W.enabled=B,x(W.id,B),L&&v(W.id,B)})},toggleTool:(Z,B,L)=>{const W=m(Z.id);Z.tools.forEach(z=>{z.id===B&&(z.enabled=L)}),x(B,L),W&&v(B,L)},deletePlugin:async Z=>{const B=c.value.find(W=>W.id===Z.id);if(!B)return;c.value=c.value.filter(W=>W.id!==B.id),g(B.id);const L=Z.id;await t.removeMcpServer(L)},addPluginCore:D,addPluginFromMarket:async Z=>{Z.addState="loading";const B={type:Z.type,url:Z.url,headers:Z.headers,useAISdkClient:!0},L=await D({pluginId:Z.id,name:Z.name,description:Z.description||"",icon:Z.icon,mcpServer:B});Z.addState=L?"added":"idle"},addPluginFromScan:async(Z,B)=>{const L={type:"streamableHttp",url:`${B}mcp?sessionId=${Z}`};let W="未知插件";try{W=new URL(`${B}mcp?sessionId=${Z}`).origin}catch(z){console.error("[usePlugin] Failed to parse scan URL:",z)}return await D({pluginId:`plugin-${Z}`,name:W,description:Z,mcpServer:L})},handleClientDisconnected:async Z=>{const B=Z,L=c.value.find(W=>W.id===B);return await t.removeMcpServer(Z),L?(c.value=c.value.filter(W=>W.id!==B),g(B),L):null},searchPlugin:(Z,B)=>Z.trim()===""||B.name.toLowerCase().includes(Z.toLowerCase()),syncInstalledPluginTools:A}}function Uy(t){const{onToolCatalogChanged:r}=t,i=typeof window<"u"&&window!==window.top,c=D=>D===window||i&&D===window.parent;let d=!1,f=!1,m=!1;const x=async()=>{if(!(!r||d)){if(f){m=!0;return}f=!0;try{do{m=!1;try{await r()}catch(D){console.warn("[useRouteBasedTools] refresh tool catalog failed:",D)}}while(m&&!d)}finally{f=!1}}},v=D=>{!c(D.source)||D.data?.type!==Jn.MSG_TOOL_REGISTERED&&D.data?.type!==Jn.MSG_TOOL_UNREGISTERED||x()};let g=!1;const E=()=>{g||(d=!1,g=!0,window.addEventListener("message",v),i&&window.parent&&window.parent.postMessage({type:Jn.MSG_REMOTER_READY},"*"))},A=()=>{g&&(d=!0,m=!1,g=!1,window.removeEventListener("message",v))};_.onMounted(()=>{E()}),_.onUnmounted(()=>{A()})}function zy(t){const{skillsRef:r,customAgentProvider:i}=t,c=_.shallowRef([]);_.watchEffect(async()=>{const x=r?.value;c.value=x?await Jn.getSkillOverviews(x):[]});const d=_.computed(()=>{const x=c.value;return x.length>0?Jn.formatSkillsForSystemPrompt(x):""}),f=_.computed(()=>{const x=r?.value;return x?Jn.createSkillTools(x):{}});return _.watchEffect(()=>{if(i.promptManager.setSkillMeta(d.value),i.llmConfig){const x=i.llmConfig.extraTools??{};i.llmConfig.extraTools={...x,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:d,skillTools:f,skillOverviews:c}}const Vy=["title"],Zy=_.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,i=_.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return{cachedInputTokens:[E/x*100+"%",E],inputTokens:[(f-E)/x*100+"%",f],reasoningTokens:[A/x*100+"%",A],outputTokens:[(m-A)/x*100+"%",m]}}),d=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:x=0,inputTokenDetails:v,outputTokenDetails:g}=r.usage,E=v?.cacheReadTokens||0,A=g?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${x}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
61
+ `)});return(f,m)=>i.value?_.createCommentVNode("",!0):(_.openBlock(),_.createElementBlock("div",{key:0,class:"token-usage-wrap",title:d.value},[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(c.value,(x,v)=>(_.openBlock(),_.createElementBlock("div",{key:v,class:_.normalizeClass(v),style:_.normalizeStyle({width:x[0]})},null,6))),128))],8,Vy))}}),nr=(t,r)=>{const i=t.__vccOpts||t;for(const[c,d]of r)i[c]=d;return i},$y=nr(Zy,[["__scopeId","data-v-000098b4"]]),jy={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 Hy(t,r){return _.openBlock(),_.createElementBlock("svg",jy,[...r[0]||(r[0]=[_.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),_.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[_.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),_.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 ju={render:Hy};function Wy(t){const{messages:r,messageState:i,inputMessage:c,handleSendMessage:d}=t,f=_.h(ju,{style:{width:"48px",height:"48px"}}),m=_.ref({}),x=_.computed(()=>Kn.GeneratingStatus.includes(i.status)),v=_.computed(()=>r.value.findLastIndex(T=>T.role==="assistant")),g=T=>T===void 0?"复制":m.value[T]?"复制成功":"复制",E=async T=>{const P=r.value[T].uiContent.map(M=>M.content).join(`
62
+ `);try{await navigator.clipboard.writeText(P),T!==void 0&&(m.value[T]=!0,setTimeout(()=>{m.value[T]=!1},3e3))}catch(M){console.error("复制失败:",M),it("复制失败,请重试")}},A=async T=>{const S=r.value.findLastIndex((M,ee)=>M.role==="user"&&ee<=T);if(S===-1){console.warn("未找到可重新生成的用户消息"),it("无法重新生成消息");return}const P=r.value[S];if(r.value=r.value.slice(0,S),Array.isArray(P.content)){const ee=P.content.find(F=>F.type==="text")?.text||"",$=P.content.filter(F=>F.type!=="text");c.value=ee,await d(ee,$.length>0?$:void 0)}else c.value=P.content,await d(P.content)},D={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:T})=>{const S=v.value===T;return x.value&&S?"":_.h("div",{class:["assistant-actions",{"latest-assistant":S,"historical-assistant":!S}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Vt.IconButton,{icon:Mr.IconRefresh,size:24,onClick:()=>A(T)}),_.h(Id,{effect:"light",content:g(T),placement:"right",visibleArrow:!1},()=>_.h(Vt.IconButton,{icon:Mr.IconCopy,size:24,onClick:()=>E(T)})),r.value[T].usage?_.h($y,{usage:r.value[T].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:D,copyingStates:m,isProcessing:x,latestAssistantMessageIndex:v,copyTooltipContent:g,copyMessageToClipboard:E,regenerateMessage:A}}function Gy(t){const{createConversation:r,switchConversation:i,deleteConversation:c,getCurrentConversation:d,abortRequest:f,conversationState:m,customAgentProvider:x}=t,v=_.ref(!1),g=()=>{_.nextTick(()=>{const S=document.querySelector("div.tr-bubble-list");S&&S.scrollTo({top:S.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const S=[];x.agent.responseMessages=S,r();const P=d();P.aiSdkMessages=S},handleHistorySelect:S=>{f(),i(S.id);const P=d();x.agent.responseMessages=P.aiSdkMessages,v.value=!1,g()},handleHistoryUpdateTitle:(S,P)=>{P.title=S},handleHistoryDelete:(S,P)=>{if(S.id==="delete"){if(m.currentId===P.id){it("不允许删除当前会话");return}c(P.id)}},scrollToBottom:g}}function qy(t){const{sessionId:r,agentRoot:i,mode:c,qrCodeUrl:d,remoteUrl:f,menuItems:m,AILogoUrl:x,show:v,addPluginFromScan:g,inputMessage:E}=t;let A=null,D=!1;const T=async $=>{if($u("添加工具中..."),$){const F=await g($,i.value);it(F?"添加工具完成":"重复添加工具或添加失败")}else it("添加工具失败")},S=async $=>{if(/^\/[A-Za-z0-9-]{6,}$/.test($)){try{const F=await fetch(`${i.value}client?sessionId=${$.slice(1)}`);if(!F.ok)throw new Error(`HTTP ${F.status}`);const Z=(await F.json())?.data?.sessionId;Z?await T(Z):it("添加工具失败,请检查识别码是否正确"),E.value=""}catch(F){console.error("识别码处理失败:",F),it("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},P=()=>{const $=F=>{A&&(A.destroy(),A=null),A=Jn.createRemoter({sessionId:F||void 0,qrCodeUrl:d,remoteUrl:f,menuItems:m?.value,logoUrl:x,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};_.watch(r,F=>{if(c!=="remoter")return;const re=!!F;A?!D&&re&&($(F),D=!0):($(F),D=re)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&A&&$(r.value)},{deep:!0}),_.watch(v,F=>{A&&(F?A.hide():A.show())},{immediate:!0})},M=()=>{_.watch(r,$=>{$&&T($)})};return{handleScanSuccess:T,handleSessionIdInput:S,initialize:()=>{r.value&&T(r.value),c==="remoter"&&P(),M()},initializeRemoter:P,watchSessionIdChanges:M}}function Xy(t){return new Promise((r,i)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=i,c.readAsDataURL(t)})}function Yy(t){return t.type.startsWith("image/")}function Ky(t,r){const i=r*1024*1024;return t.size<=i}async function Jy(t){if(t.length===0)return[];const r=[];for(const i of t)if(i.rawFile)try{const c=await Xy(i.rawFile);Yy(i.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),it({type:"fail",message:"文件处理失败"})}return r}function Qy(t={}){const r=_.ref([]),i=async d=>{if(!d||d.length===0)return;c();const f=_.unref(t.maxFileSize)||10,m=_.unref(t.supportedTypes)||["image/"];for(const x of d){if(!m.some(g=>x.type.startsWith(g))){it({type:"fail",message:`不支持的文件类型: ${x.type}`});continue}if(!Ky(x,f)){it({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:x,url:URL.createObjectURL(x)})}},c=()=>{r.value.forEach(d=>{d.url&&URL.revokeObjectURL(d.url)}),r.value=[]};return{attachments:r,handleFilesSelected:i,clearAttachments:c}}function ew(t){const{selectedModel:r,selectedModelId:i}=t,c=_.computed(()=>r.value?.multimodal?.supportImages??!1),d=_.computed(()=>r.value?.multimodal?.maxFileSize||10),f=_.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:m,handleFilesSelected:x,clearAttachments:v}=Qy({maxFileSize:d,supportedTypes:f});return _.watch(i,()=>{if(m.value.length>0&&r.value){const T=r.value.multimodal?.maxFileSize||10,S=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(M=>{if(!M.rawFile||!S.some(F=>M.rawFile.type.startsWith(F)))return!0;const $=T*1024*1024;return M.rawFile.size>$}).length>0&&(v(),it("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:T=>{x(T)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(it("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await Jy(m.value),cleanupAttachments:()=>{m.value.length>0&&v()},clearAttachments:v}}var Ce;(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"})(Ce||(Ce={}));var al=new Map([[Ce.QR_CODE,"QR_CODE"],[Ce.AZTEC,"AZTEC"],[Ce.CODABAR,"CODABAR"],[Ce.CODE_39,"CODE_39"],[Ce.CODE_93,"CODE_93"],[Ce.CODE_128,"CODE_128"],[Ce.DATA_MATRIX,"DATA_MATRIX"],[Ce.MAXICODE,"MAXICODE"],[Ce.ITF,"ITF"],[Ce.EAN_13,"EAN_13"],[Ce.EAN_8,"EAN_8"],[Ce.PDF_417,"PDF_417"],[Ce.RSS_14,"RSS_14"],[Ce.RSS_EXPANDED,"RSS_EXPANDED"],[Ce.UPC_A,"UPC_A"],[Ce.UPC_E,"UPC_E"],[Ce.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),ll;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(ll||(ll={}));function tw(t){return Object.values(Ce).includes(t)}var oo;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(oo||(oo={}));var nw=(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=[oo.SCAN_TYPE_CAMERA,oo.SCAN_TYPE_FILE],t})(),Hu=(function(){function t(r,i){this.format=r,this.formatName=i}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!al.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,al.get(r))},t})(),cl=(function(){function t(){}return t.createFromText=function(r){var i={text:r};return{decodedText:r,result:i}},t.createFromQrcodeResult=function(r){return{decodedText:r.text,result:r}},t})(),Li;(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"})(Li||(Li={}));var rw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Li.UNKWOWN_ERROR}},t})(),ow=(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,i){(this.verbose||i===!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 zn(t){return typeof t>"u"||t===null}var Rr=(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})(),Wu=(function(){function t(){}return t.isMediaStreamConstraintsValid=function(r,i){if(typeof r!="object"){var c=typeof r;return i.logError("videoConstraints should be of type object, the "+"object passed is of type ".concat(c,"."),!0),!1}for(var d=["autoGainControl","channelCount","echoCancellation","latency","noiseSuppression","sampleRate","sampleSize","volume"],f=new Set(d),m=Object.keys(r),x=0,v=m;x<v.length;x++){var g=v[x];if(f.has(g))return i.logError("".concat(g," is not supported videoConstaints."),!0),!1}return!0},t})(),To=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function iw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var qr={exports:{}},sw=qr.exports,ul;function aw(){return ul||(ul=1,(function(t,r){(function(i,c){c(r)})(sw,(function(i){function c(C){return C==null}var d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(C,e){C.__proto__=e}||function(C,e){for(var n in e)e.hasOwnProperty(n)&&(C[n]=e[n])};function f(C,e){d(C,e);function n(){this.constructor=C}C.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function x(C,e){e===void 0&&(e=C.constructor);var n=Error.captureStackTrace;n&&n(C,e)}var v=(function(C){f(e,C);function e(n){var o=this.constructor,s=C.call(this,n)||this;return Object.defineProperty(s,"name",{value:o.name,enumerable:!1}),m(s,o.prototype),x(s),s}return e})(Error);class g extends v{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}g.kind="Exception";class E extends g{}E.kind="ArgumentException";class A extends g{}A.kind="IllegalArgumentException";class D{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,o,s){const a=this.binarizer.getLuminanceSource().crop(e,n,o,s);return new D(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new D(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new D(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class T extends g{static getChecksumInstance(){return new T}}T.kind="ChecksumException";class S{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,o,s,a){for(;a--;)o[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class M extends g{}M.kind="IndexOutOfBoundsException";class ee extends M{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}ee.kind="ArrayIndexOutOfBoundsException";class ${static fill(e,n){for(let o=0,s=e.length;o<s;o++)e[o]=n}static fillWithin(e,n,o,s){$.rangeCheck(e.length,n,o);for(let a=n;a<o;a++)e[a]=s}static rangeCheck(e,n,o){if(n>o)throw new A("fromIndex("+n+") > toIndex("+o+")");if(n<0)throw new ee(n);if(o>e)throw new ee(o)}static asList(...e){return e}static create(e,n,o){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(o))}static createInt32Array(e,n,o){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(o))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let o=0,s=e.length;o<s;o++)if(e[o]!==n[o])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const o of e)n=31*n+o;return n}static fillUint8Array(e,n){for(let o=0;o!==e.length;o++)e[o]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const o=new Uint8Array(n);return o.set(e),o}return e.slice(0,n)}static copyOfRange(e,n,o){const s=o-n,a=new Int32Array(s);return P.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,o){o===void 0&&(o=$.numberComparator);let s=0,a=e.length-1;for(;s<=a;){const l=a+s>>1,u=o(n,e[l]);if(u>0)s=l+1;else if(u<0)a=l-1;else return l}return-s-1}static numberComparator(e,n){return e-n}}class F{static numberOfTrailingZeros(e){let n;if(e===0)return 32;let o=31;return n=e<<16,n!==0&&(o-=16,e=n),n=e<<8,n!==0&&(o-=8,e=n),n=e<<4,n!==0&&(o-=4,e=n),n=e<<2,n!==0&&(o-=2,e=n),o-(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)}}F.MIN_VALUE_32_BITS=-2147483648,F.MAX_VALUE=Number.MAX_SAFE_INTEGER;class re{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=re.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=re.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 o=this.bits;let s=Math.floor(e/32),a=o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}getNextUnset(e){const n=this.size;if(e>=n)return n;const o=this.bits;let s=Math.floor(e/32),a=~o[s];a&=~((1<<(e&31))-1);const l=o.length;for(;a===0;){if(++s===l)return n;a=~o[s]}const u=s*32+F.numberOfTrailingZeros(a);return u>n?n:u}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 o=Math.floor(e/32),s=Math.floor(n/32),a=this.bits;for(let l=o;l<=s;l++){const u=l>o?0:e&31,p=(2<<(l<s?31:n&31))-(1<<u);a[l]|=p}}clear(){const e=this.bits.length,n=this.bits;for(let o=0;o<e;o++)n[o]=0}isRange(e,n,o){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 u=s;u<=a;u++){const h=u>s?0:e&31,y=(2<<(u<a?31:n&31))-(1<<h)&4294967295;if((l[u]&y)!==(o?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 o=n;o>0;o--)this.appendBit((e>>o-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let o=0;o<n;o++)this.appendBit(e.get(o))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let o=0,s=n.length;o<s;o++)n[o]^=e.bits[o]}toBytes(e,n,o,s){for(let a=0;a<s;a++){let l=0;for(let u=0;u<8;u++)this.get(e)&&(l|=1<<7-u),e++;n[o+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),o=n+1,s=this.bits;for(let a=0;a<o;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!==o*32){const a=o*32-this.size;let l=e[0]>>>a;for(let u=1;u<o;u++){const h=e[u];l|=h<<32-a,e[u-1]=l,l=h>>>a}e[o-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof re))return!1;const n=e;return this.size===n.size&&$.equals(this.bits,n.bits)}hashCode(){return 31*this.size+$.hashCode(this.bits)}toString(){let e="";for(let n=0,o=this.size;n<o;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new re(this.size,this.bits.slice())}}var Z;(function(C){C[C.OTHER=0]="OTHER",C[C.PURE_BARCODE=1]="PURE_BARCODE",C[C.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",C[C.TRY_HARDER=3]="TRY_HARDER",C[C.CHARACTER_SET=4]="CHARACTER_SET",C[C.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",C[C.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",C[C.ASSUME_GS1=7]="ASSUME_GS1",C[C.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",C[C.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",C[C.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(Z||(Z={}));var B=Z;class L extends g{static getFormatInstance(){return new L}}L.kind="FormatException";var W;(function(C){C[C.Cp437=0]="Cp437",C[C.ISO8859_1=1]="ISO8859_1",C[C.ISO8859_2=2]="ISO8859_2",C[C.ISO8859_3=3]="ISO8859_3",C[C.ISO8859_4=4]="ISO8859_4",C[C.ISO8859_5=5]="ISO8859_5",C[C.ISO8859_6=6]="ISO8859_6",C[C.ISO8859_7=7]="ISO8859_7",C[C.ISO8859_8=8]="ISO8859_8",C[C.ISO8859_9=9]="ISO8859_9",C[C.ISO8859_10=10]="ISO8859_10",C[C.ISO8859_11=11]="ISO8859_11",C[C.ISO8859_13=12]="ISO8859_13",C[C.ISO8859_14=13]="ISO8859_14",C[C.ISO8859_15=14]="ISO8859_15",C[C.ISO8859_16=15]="ISO8859_16",C[C.SJIS=16]="SJIS",C[C.Cp1250=17]="Cp1250",C[C.Cp1251=18]="Cp1251",C[C.Cp1252=19]="Cp1252",C[C.Cp1256=20]="Cp1256",C[C.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",C[C.UTF8=22]="UTF8",C[C.ASCII=23]="ASCII",C[C.Big5=24]="Big5",C[C.GB18030=25]="GB18030",C[C.EUC_KR=26]="EUC_KR"})(W||(W={}));class z{constructor(e,n,o,...s){this.valueIdentifier=e,this.name=o,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,z.VALUE_IDENTIFIER_TO_ECI.set(e,this),z.NAME_TO_ECI.set(o,this);const a=this.values;for(let l=0,u=a.length;l!==u;l++){const h=a[l];z.VALUES_TO_ECI.set(h,this)}for(const l of s)z.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 L("incorect value");const n=z.VALUES_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}static getCharacterSetECIByName(e){const n=z.NAME_TO_ECI.get(e);if(n===void 0)throw new L("incorect value");return n}equals(e){if(!(e instanceof z))return!1;const n=e;return this.getName()===n.getName()}}z.VALUE_IDENTIFIER_TO_ECI=new Map,z.VALUES_TO_ECI=new Map,z.NAME_TO_ECI=new Map,z.Cp437=new z(W.Cp437,Int32Array.from([0,2]),"Cp437"),z.ISO8859_1=new z(W.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),z.ISO8859_2=new z(W.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),z.ISO8859_3=new z(W.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),z.ISO8859_4=new z(W.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),z.ISO8859_5=new z(W.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),z.ISO8859_6=new z(W.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),z.ISO8859_7=new z(W.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),z.ISO8859_8=new z(W.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),z.ISO8859_9=new z(W.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),z.ISO8859_10=new z(W.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),z.ISO8859_11=new z(W.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),z.ISO8859_13=new z(W.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),z.ISO8859_14=new z(W.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),z.ISO8859_15=new z(W.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),z.ISO8859_16=new z(W.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),z.SJIS=new z(W.SJIS,20,"SJIS","Shift_JIS"),z.Cp1250=new z(W.Cp1250,21,"Cp1250","windows-1250"),z.Cp1251=new z(W.Cp1251,22,"Cp1251","windows-1251"),z.Cp1252=new z(W.Cp1252,23,"Cp1252","windows-1252"),z.Cp1256=new z(W.Cp1256,24,"Cp1256","windows-1256"),z.UnicodeBigUnmarked=new z(W.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),z.UTF8=new z(W.UTF8,26,"UTF8","UTF-8"),z.ASCII=new z(W.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),z.Big5=new z(W.Big5,28,"Big5"),z.GB18030=new z(W.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),z.EUC_KR=new z(W.EUC_KR,30,"EUC_KR","EUC-KR");class we extends g{}we.kind="UnsupportedOperationException";class G{static decode(e,n){const o=this.encodingName(n);return this.customDecoder?this.customDecoder(e,o):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(o)?this.decodeFallback(e,o):new TextDecoder(o).decode(e)}static shouldDecodeOnFallback(e){return!G.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const o=this.encodingName(n);return this.customEncoder?this.customEncoder(e,o):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 z?e:z.getCharacterSetECIByName(e)}static decodeFallback(e,n){const o=this.encodingCharacterSet(n);if(G.isDecodeFallbackSupported(o)){let s="";for(let a=0,l=e.length;a<l;a++){let u=e[a].toString(16);u.length<2&&(u="0"+u),s+="%"+u}return decodeURIComponent(s)}if(o.equals(z.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(z.UTF8)||e.equals(z.ISO8859_1)||e.equals(z.ASCII)}static encodeFallback(e){const o=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<o.length;a++)s.push(o[a].charCodeAt(0));return new Uint8Array(s)}}class me{static castAsNonUtf8Char(e,n=null){const o=n?n.getName():this.ISO88591;return G.decode(new Uint8Array([e]),o)}static guessEncoding(e,n){if(n!=null&&n.get(B.CHARACTER_SET)!==void 0)return n.get(B.CHARACTER_SET).toString();const o=e.length;let s=!0,a=!0,l=!0,u=0,h=0,p=0,y=0,b=0,I=0,R=0,U=0,V=0,H=0,Q=0;const he=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let pe=0;pe<o&&(s||a||l);pe++){const ce=e[pe]&255;l&&(u>0?(ce&128)===0?l=!1:u--:(ce&128)!==0&&((ce&64)===0?l=!1:(u++,(ce&32)===0?h++:(u++,(ce&16)===0?p++:(u++,(ce&8)===0?y++:l=!1))))),s&&(ce>127&&ce<160?s=!1:ce>159&&(ce<192||ce===215||ce===247)&&Q++),a&&(b>0?ce<64||ce===127||ce>252?a=!1:b--:ce===128||ce===160||ce>239?a=!1:ce>160&&ce<224?(I++,U=0,R++,R>V&&(V=R)):ce>127?(b++,R=0,U++,U>H&&(H=U)):(R=0,U=0))}return l&&u>0&&(l=!1),a&&b>0&&(a=!1),l&&(he||h+p+y>0)?me.UTF8:a&&(me.ASSUME_SHIFT_JIS||V>=3||H>=3)?me.SHIFT_JIS:s&&a?V===2&&I===2||Q*10>=o?me.SHIFT_JIS:me.ISO88591:s?me.ISO88591:a?me.SHIFT_JIS:l?me.UTF8:me.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return G.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}me.SHIFT_JIS=z.SJIS.getName(),me.GB2312="GB2312",me.ISO88591=z.ISO8859_1.getName(),me.EUC_JP="EUC_JP",me.UTF8=z.UTF8.getName(),me.PLATFORM_DEFAULT_ENCODING=me.UTF8,me.ASSUME_SHIFT_JIS=!1;class fe{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+=me.castAsNonUtf8Char(e,this.encoding):this.value+=String.fromCharCode(e),this}appendChars(e,n,o){for(let s=n;n<n+o;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 te{constructor(e,n,o,s){if(this.width=e,this.height=n,this.rowSize=o,this.bits=s,n==null&&(n=e),this.height=n,e<1||n<1)throw new A("Both dimensions must be greater than 0");o==null&&(o=Math.floor((e+31)/32)),this.rowSize=o,s==null&&(this.bits=new Int32Array(this.rowSize*this.height))}static parseFromBooleanArray(e){const n=e.length,o=e[0].length,s=new te(o,n);for(let a=0;a<n;a++){const l=e[a];for(let u=0;u<o;u++)l[u]&&s.set(u,a)}return s}static parseFromString(e,n,o){if(e===null)throw new A("stringRepresentation cannot be null");const s=new Array(e.length);let a=0,l=0,u=-1,h=0,p=0;for(;p<e.length;)if(e.charAt(p)===`
63
+ `||e.charAt(p)==="\r"){if(a>l){if(u===-1)u=a-l;else if(a-l!==u)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+o.length)===o)p+=o.length,s[a]=!1,a++;else throw new A("illegal character encountered: "+e.substring(p));if(a>l){if(u===-1)u=a-l;else if(a-l!==u)throw new A("row lengths do not match");h++}const y=new te(u,h);for(let b=0;b<a;b++)s[b]&&y.set(Math.floor(b%u),Math.floor(b/u));return y}get(e,n){const o=n*this.rowSize+Math.floor(e/32);return(this.bits[o]>>>(e&31)&1)!==0}set(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]|=1<<(e&31)&4294967295}unset(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]&=~(1<<(e&31)&4294967295)}flip(e,n){const o=n*this.rowSize+Math.floor(e/32);this.bits[o]^=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 re(Math.floor(this.width/32)+1),o=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const u=a*o,h=e.getRow(a,n).getBitArray();for(let p=0;p<o;p++)s[u+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let o=0;o<n;o++)e[o]=0}setRegion(e,n,o,s){if(n<0||e<0)throw new A("Left and top must be nonnegative");if(s<1||o<1)throw new A("Height and width must be at least 1");const a=e+o,l=n+s;if(l>this.height||a>this.width)throw new A("The region must fit inside the matrix");const u=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*u;for(let b=e;b<a;b++)h[y+Math.floor(b/32)]|=1<<(b&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new re(this.width):n.clear();const o=this.rowSize,s=this.bits,a=e*o;for(let l=0;l<o;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){P.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let o=new re(e),s=new re(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)o=this.getRow(a,o),s=this.getRow(n-1-a,s),o.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,o)}getEnclosingRectangle(){const e=this.width,n=this.height,o=this.rowSize,s=this.bits;let a=e,l=n,u=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<o;y++){const b=s[p*o+y];if(b!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(b<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>u){let I=31;for(;!(b>>>I);)I--;y*32+I>u&&(u=y*32+I)}}}return u<a||h<l?null:Int32Array.from([a,l,u-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let o=0;for(;o<n.length&&n[o]===0;)o++;if(o===n.length)return null;const s=o/e;let a=o%e*32;const l=n[o];let u=0;for(;(l<<31-u&4294967295)===0;)u++;return a+=u,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let o=n.length-1;for(;o>=0&&n[o]===0;)o--;if(o<0)return null;const s=Math.floor(o/e);let a=Math.floor(o%e)*32;const l=n[o];let u=31;for(;!(l>>>u);)u--;return a+=u,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof te))return!1;const n=e;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&$.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+$.hashCode(this.bits),e}toString(e="X ",n=" ",o=`
64
+ `){return this.buildToString(e,n,o)}buildToString(e,n,o){let s=new fe;for(let a=0,l=this.height;a<l;a++){for(let u=0,h=this.width;u<h;u++)s.append(this.get(u,a)?e:n);s.append(o)}return s.toString()}clone(){return new te(this.width,this.height,this.rowSize,this.bits.slice())}}class q extends g{static getNotFoundInstance(){return new q}}q.kind="NotFoundException";class ke extends S{constructor(e){super(e),this.luminances=ke.EMPTY,this.buckets=new Int32Array(ke.LUMINANCE_BUCKETS)}getBlackRow(e,n){const o=this.getLuminanceSource(),s=o.getWidth();n==null||n.getSize()<s?n=new re(s):n.clear(),this.initArrays(s);const a=o.getRow(e,this.luminances),l=this.buckets;for(let h=0;h<s;h++)l[(a[h]&255)>>ke.LUMINANCE_SHIFT]++;const u=ke.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<u&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const b=a[y+1]&255;(p*4-h-b)/2<u&&n.set(y),h=p,p=b}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight(),s=new te(n,o);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(o*h/5),y=e.getRow(p,this.luminances),b=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<b;I++){const R=y[I]&255;a[R>>ke.LUMINANCE_SHIFT]++}}const l=ke.estimateBlackPoint(a),u=e.getMatrix();for(let h=0;h<o;h++){const p=h*n;for(let y=0;y<n;y++)(u[p+y]&255)<l&&s.set(y,h)}return s}createBinarizer(e){return new ke(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let o=0;o<ke.LUMINANCE_BUCKETS;o++)n[o]=0}static estimateBlackPoint(e){const n=e.length;let o=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>o&&(o=e[y]);let l=0,u=0;for(let y=0;y<n;y++){const b=y-s,I=e[y]*b*b;I>u&&(l=y,u=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new q;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const b=y-s,I=b*b*(l-y)*(o-e[y]);I>p&&(h=y,p=I)}return h<<ke.LUMINANCE_SHIFT}}ke.LUMINANCE_BITS=5,ke.LUMINANCE_SHIFT=8-ke.LUMINANCE_BITS,ke.LUMINANCE_BUCKETS=1<<ke.LUMINANCE_BITS,ke.EMPTY=Uint8ClampedArray.from([0]);class le extends ke{constructor(e){super(e),this.matrix=null}getBlackMatrix(){if(this.matrix!==null)return this.matrix;const e=this.getLuminanceSource(),n=e.getWidth(),o=e.getHeight();if(n>=le.MINIMUM_DIMENSION&&o>=le.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>le.BLOCK_SIZE_POWER;(n&le.BLOCK_SIZE_MASK)!==0&&a++;let l=o>>le.BLOCK_SIZE_POWER;(o&le.BLOCK_SIZE_MASK)!==0&&l++;const u=le.calculateBlackPoints(s,a,l,n,o),h=new te(n,o);le.calculateThresholdForBlock(s,a,l,n,o,u,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new le(e)}static calculateThresholdForBlock(e,n,o,s,a,l,u){const h=a-le.BLOCK_SIZE,p=s-le.BLOCK_SIZE;for(let y=0;y<o;y++){let b=y<<le.BLOCK_SIZE_POWER;b>h&&(b=h);const I=le.cap(y,2,o-3);for(let R=0;R<n;R++){let U=R<<le.BLOCK_SIZE_POWER;U>p&&(U=p);const V=le.cap(R,2,n-3);let H=0;for(let he=-2;he<=2;he++){const pe=l[I+he];H+=pe[V-2]+pe[V-1]+pe[V]+pe[V+1]+pe[V+2]}const Q=H/25;le.thresholdBlock(e,U,b,Q,s,u)}}}static cap(e,n,o){return e<n?n:e>o?o:e}static thresholdBlock(e,n,o,s,a,l){for(let u=0,h=o*a+n;u<le.BLOCK_SIZE;u++,h+=a)for(let p=0;p<le.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,o+u)}static calculateBlackPoints(e,n,o,s,a){const l=a-le.BLOCK_SIZE,u=s-le.BLOCK_SIZE,h=new Array(o);for(let p=0;p<o;p++){h[p]=new Int32Array(n);let y=p<<le.BLOCK_SIZE_POWER;y>l&&(y=l);for(let b=0;b<n;b++){let I=b<<le.BLOCK_SIZE_POWER;I>u&&(I=u);let R=0,U=255,V=0;for(let Q=0,he=y*s+I;Q<le.BLOCK_SIZE;Q++,he+=s){for(let pe=0;pe<le.BLOCK_SIZE;pe++){const ce=e[he+pe]&255;R+=ce,ce<U&&(U=ce),ce>V&&(V=ce)}if(V-U>le.MIN_DYNAMIC_RANGE)for(Q++,he+=s;Q<le.BLOCK_SIZE;Q++,he+=s)for(let pe=0;pe<le.BLOCK_SIZE;pe++)R+=e[he+pe]&255}let H=R>>le.BLOCK_SIZE_POWER*2;if(V-U<=le.MIN_DYNAMIC_RANGE&&(H=U/2,p>0&&b>0)){const Q=(h[p-1][b]+2*h[p][b-1]+h[p-1][b-1])/4;U<Q&&(H=Q)}h[p][b]=H}}return h}}le.BLOCK_SIZE_POWER=3,le.BLOCK_SIZE=1<<le.BLOCK_SIZE_POWER,le.BLOCK_SIZE_MASK=le.BLOCK_SIZE-1,le.MINIMUM_DIMENSION=le.BLOCK_SIZE*5,le.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,o,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 fe;for(let o=0;o<this.height;o++){const s=this.getRow(o,e);for(let a=0;a<this.width;a++){const l=s[a]&255;let u;l<64?u="#":l<128?u="+":l<192?u=".":u=" ",n.append(u)}n.append(`
65
+ `)}return n.toString()}}class Je extends Te{constructor(e){super(e.getWidth(),e.getHeight()),this.delegate=e}getRow(e,n){const o=this.delegate.getRow(e,n),s=this.getWidth();for(let a=0;a<s;a++)o[a]=255-(o[a]&255);return o}getMatrix(){const e=this.delegate.getMatrix(),n=this.getWidth()*this.getHeight(),o=new Uint8ClampedArray(n);for(let s=0;s<n;s++)o[s]=255-(e[s]&255);return o}isCropSupported(){return this.delegate.isCropSupported()}crop(e,n,o,s){return new Je(this.delegate.crop(e,n,o,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new Je(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new Je(this.delegate.rotateCounterClockwise45())}}class xe extends Te{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=xe.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return xe.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,o){const s=new Uint8ClampedArray(n*o);for(let a=0,l=0,u=e.length;a<u;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],b=e[a+1],I=e[a+2];h=306*y+601*b+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 o=this.getWidth(),s=e*o;return n===null?n=this.buffer.slice(s,s+o):(n.length<o&&(n=new Uint8ClampedArray(o)),n.set(this.buffer.slice(s,s+o))),n}getMatrix(){return this.buffer}isCropSupported(){return!0}crop(e,n,o,s){return super.crop(e,n,o,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(),o=n.getContext("2d"),s=e*xe.DEGREE_TO_RADIANS,a=this.canvas.width,l=this.canvas.height,u=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=u,n.height=h,o.translate(u/2,h/2),o.rotate(s),o.drawImage(this.canvas,a/-2,l/-2),this.buffer=xe.makeBufferFromCanvasImageData(n),this}invert(){return new Je(this)}}xe.DEGREE_TO_RADIANS=Math.PI/180;class $e{constructor(e,n,o){this.deviceId=e,this.label=n,this.kind="videoinput",this.groupId=o||void 0}toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}}}var Ue=(globalThis||To||self||window||void 0)&&(globalThis||To||self||window||void 0).__awaiter||function(C,e,n,o){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function u(y){try{p(o.next(y))}catch(b){l(b)}}function h(y){try{p(o.throw(y))}catch(b){l(b)}}function p(y){y.done?a(y.value):s(y.value).then(u,h)}p((o=o.apply(C,e||[])).next())})};class Ze{constructor(e,n=500,o){this.reader=e,this.timeBetweenScansMillis=n,this._hints=o,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 Ue(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 o of e){const s=o.kind==="video"?"videoinput":o.kind;if(s!=="videoinput")continue;const a=o.deviceId||o.id,l=o.label||`Video device ${n.length+1}`,u=o.groupId,h={deviceId:a,label:l,kind:s,groupId:u};n.push(h)}return n})}getVideoInputDevices(){return Ue(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new $e(n.deviceId,n.label))})}findDeviceById(e){return Ue(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(o=>o.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return Ue(this,void 0,void 0,function*(){this.reset();let o;e?o={deviceId:{exact:e}}:o={facingMode:"environment"};const s={video:o};return yield this.decodeOnceFromConstraints(s,n)})}decodeOnceFromConstraints(e,n){return Ue(this,void 0,void 0,function*(){const o=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(o,n)})}decodeOnceFromStream(e,n){return Ue(this,void 0,void 0,function*(){this.reset();const o=yield this.attachStreamToVideo(e,n);return yield this.decodeOnce(o)})}decodeFromInputVideoDeviceContinuously(e,n,o){return Ue(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,o)})}decodeFromVideoDevice(e,n,o){return Ue(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,o)})}decodeFromConstraints(e,n,o){return Ue(this,void 0,void 0,function*(){const s=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeFromStream(s,n,o)})}decodeFromStream(e,n,o){return Ue(this,void 0,void 0,function*(){this.reset();const s=yield this.attachStreamToVideo(e,n);return yield this.decodeContinuously(s,o)})}stopAsyncDecode(){this._stopAsyncDecode=!0}stopContinuousDecode(){this._stopContinuousDecode=!0}attachStreamToVideo(e,n){return Ue(this,void 0,void 0,function*(){const o=this.prepareVideoElement(n);return this.addVideoSource(o,e),this.videoElement=o,this.stream=e,yield this.playVideoOnLoadAsync(o),o})}playVideoOnLoadAsync(e){return new Promise((n,o)=>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 Ue(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 o=document.getElementById(e);if(!o)throw new E(`element with id '${e}' not found`);if(o.nodeName.toLowerCase()!==n.toLowerCase())throw new E(`element with id '${e}' must be an ${n} element`);return o}decodeFromImage(e,n){if(!e&&!n)throw new E("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 E("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,o){if(e===void 0&&n===void 0)throw new E("Either an element with a src set or an URL must be provided");return n&&!e?this.decodeFromVideoUrlContinuously(n,o):this.decodeFromVideoElementContinuously(e,o)}decodeFromImageElement(e){if(!e)throw new E("An image element must be provided.");this.reset();const n=this.prepareImageElement(e);this.imageElement=n;let o;return this.isImageLoaded(n)?o=this.decodeOnce(n,!1,!0):o=this._decodeOnLoadImage(n),o}decodeFromVideoElement(e){const n=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideo(n)}decodeFromVideoElementContinuously(e,n){const o=this._decodeFromVideoElementSetup(e);return this._decodeOnLoadVideoContinuously(o,n)}_decodeFromVideoElementSetup(e){if(!e)throw new E("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareImageElement();this.imageElement=n;const o=this._decodeOnLoadImage(n);return n.src=e,o}decodeFromVideoUrl(e){if(!e)throw new E("An URL must be provided.");this.reset();const n=this.prepareVideoElement(),o=this.decodeFromVideoElement(n);return n.src=e,o}decodeFromVideoUrlContinuously(e,n){if(!e)throw new E("An URL must be provided.");this.reset();const o=this.prepareVideoElement(),s=this.decodeFromVideoElementContinuously(o,n);return o.src=e,s}_decodeOnLoadImage(e){return new Promise((n,o)=>{this.imageLoadedListener=()=>this.decodeOnce(e,!1,!0).then(n,o),e.addEventListener("load",this.imageLoadedListener)})}_decodeOnLoadVideo(e){return Ue(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return Ue(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,o=!0){this._stopAsyncDecode=!1;const s=(a,l)=>{if(this._stopAsyncDecode){l(new q("Video stream has ended before any code could be detected.")),this._stopAsyncDecode=void 0;return}try{const u=this.decode(e);a(u)}catch(u){const h=n&&u instanceof q,y=(u instanceof T||u instanceof L)&&o;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(u)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const o=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(o,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof T||s instanceof L,l=s instanceof q;(a||l)&&setTimeout(o,this._timeBetweenDecodingAttempts)}};o()}decode(e){const n=this.createBinaryBitmap(e);return this.decodeBitmap(n)}_isHTMLVideoElement(e){return e.videoWidth!==0}drawFrameOnCanvas(e,n,o){n||(n={sx:0,sy:0,sWidth:e.videoWidth,sHeight:e.videoHeight,dx:0,dy:0,dWidth:e.videoWidth,dHeight:e.videoHeight}),o||(o=this.captureCanvasContext),o.drawImage(e,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)}drawImageOnCanvas(e,n,o=this.captureCanvasContext){n||(n={sx:0,sy:0,sWidth:e.naturalWidth,sHeight:e.naturalHeight,dx:0,dy:0,dWidth:e.naturalWidth,dHeight:e.naturalHeight}),o||(o=this.captureCanvasContext),o.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),o=new xe(n),s=new le(o);return new D(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const o=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=o}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 o,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(o=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(o=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=o+"px",n.style.height=s+"px",n.width=o,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 qe{constructor(e,n,o=n==null?0:8*n.length,s,a,l=P.currentTimeMillis()){this.text=e,this.rawBytes=n,this.numBits=o,this.resultPoints=s,this.format=a,this.timestamp=l,this.text=e,this.rawBytes=n,o==null?this.numBits=n==null?0:8*n.length:this.numBits=o,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 o=new Array(n.length+e.length);P.arraycopy(n,0,o,0,n.length),P.arraycopy(e,0,o,n.length,e.length),this.resultPoints=o}}getTimestamp(){return this.timestamp}toString(){return this.text}}var ze;(function(C){C[C.AZTEC=0]="AZTEC",C[C.CODABAR=1]="CODABAR",C[C.CODE_39=2]="CODE_39",C[C.CODE_93=3]="CODE_93",C[C.CODE_128=4]="CODE_128",C[C.DATA_MATRIX=5]="DATA_MATRIX",C[C.EAN_8=6]="EAN_8",C[C.EAN_13=7]="EAN_13",C[C.ITF=8]="ITF",C[C.MAXICODE=9]="MAXICODE",C[C.PDF_417=10]="PDF_417",C[C.QR_CODE=11]="QR_CODE",C[C.RSS_14=12]="RSS_14",C[C.RSS_EXPANDED=13]="RSS_EXPANDED",C[C.UPC_A=14]="UPC_A",C[C.UPC_E=15]="UPC_E",C[C.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(ze||(ze={}));var ie=ze,de;(function(C){C[C.OTHER=0]="OTHER",C[C.ORIENTATION=1]="ORIENTATION",C[C.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",C[C.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",C[C.ISSUE_NUMBER=4]="ISSUE_NUMBER",C[C.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",C[C.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",C[C.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",C[C.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",C[C.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",C[C.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(de||(de={}));var _e=de;class Pe{constructor(e,n,o,s,a=-1,l=-1){this.rawBytes=e,this.text=n,this.byteSegments=o,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 ae{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 J{constructor(e,n){if(n.length===0)throw new A;this.field=e;const o=n.length;if(o>1&&n[0]===0){let s=1;for(;s<o&&n[s]===0;)s++;s===o?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(o-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 o;if(e===1){o=0;for(let l=0,u=n.length;l!==u;l++){const h=n[l];o=ae.addOrSubtract(o,h)}return o}o=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)o=ae.addOrSubtract(a.multiply(e,o),n[l]);return o}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,o=e.coefficients;if(n.length>o.length){const l=n;n=o,o=l}let s=new Int32Array(o.length);const a=o.length-n.length;P.arraycopy(o,0,s,0,a);for(let l=a;l<o.length;l++)s[l]=ae.addOrSubtract(n[l-a],o[l]);return new J(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,o=n.length,s=e.coefficients,a=s.length,l=new Int32Array(o+a-1),u=this.field;for(let h=0;h<o;h++){const p=n[h];for(let y=0;y<a;y++)l[h+y]=ae.addOrSubtract(l[h+y],u.multiply(p,s[y]))}return new J(u,l)}multiplyScalar(e){if(e===0)return this.field.getZero();if(e===1)return this;const n=this.coefficients.length,o=this.field,s=new Int32Array(n),a=this.coefficients;for(let l=0;l<n;l++)s[l]=o.multiply(a[l],e);return new J(o,s)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return this.field.getZero();const o=this.coefficients,s=o.length,a=new Int32Array(s+e),l=this.field;for(let u=0;u<s;u++)a[u]=l.multiply(o[u],n);return new J(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 o=n.getZero(),s=this;const a=e.getCoefficient(e.getDegree()),l=n.inverse(a);for(;s.getDegree()>=e.getDegree()&&!s.isZero();){const u=s.getDegree()-e.getDegree(),h=n.multiply(s.getCoefficient(s.getDegree()),l),p=e.multiplyByMonomial(u,h),y=n.buildMonomial(u,h);o=o.addOrSubtract(y),s=s.addOrSubtract(p)}return[o,s]}toString(){let e="";for(let n=this.getDegree();n>=0;n--){let o=this.getCoefficient(n);if(o!==0){if(o<0?(e+=" - ",o=-o):e.length>0&&(e+=" + "),n===0||o!==1){const s=this.field.log(o);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 ye extends g{}ye.kind="ArithmeticException";class Se extends ae{constructor(e,n,o){super(),this.primitive=e,this.size=n,this.generatorBase=o;const s=new Int32Array(n);let a=1;for(let u=0;u<n;u++)s[u]=a,a*=2,a>=n&&(a^=e,a&=n-1);this.expTable=s;const l=new Int32Array(n);for(let u=0;u<n-1;u++)l[s[u]]=u;this.logTable=l,this.zero=new J(this,Int32Array.from([0])),this.one=new J(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 o=new Int32Array(e+1);return o[0]=n,new J(this,o)}inverse(e){if(e===0)throw new ye;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"+F.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Se.AZTEC_DATA_12=new Se(4201,4096,1),Se.AZTEC_DATA_10=new Se(1033,1024,1),Se.AZTEC_DATA_6=new Se(67,64,1),Se.AZTEC_PARAM=new Se(19,16,1),Se.QR_CODE_FIELD_256=new Se(285,256,0),Se.DATA_MATRIX_FIELD_256=new Se(301,256,1),Se.AZTEC_DATA_8=Se.DATA_MATRIX_FIELD_256,Se.MAXICODE_FIELD_64=Se.AZTEC_DATA_6;class Ve extends g{}Ve.kind="ReedSolomonException";class St extends g{}St.kind="IllegalStateException";class vt{constructor(e){this.field=e}decode(e,n){const o=this.field,s=new J(o,e),a=new Int32Array(n);let l=!0;for(let R=0;R<n;R++){const U=s.evaluateAt(o.exp(R+o.getGeneratorBase()));a[a.length-1-R]=U,U!==0&&(l=!1)}if(l)return;const u=new J(o,a),h=this.runEuclideanAlgorithm(o.buildMonomial(n,1),u,n),p=h[0],y=h[1],b=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,b);for(let R=0;R<b.length;R++){const U=e.length-1-o.log(b[R]);if(U<0)throw new Ve("Bad error location");e[U]=Se.addOrSubtract(e[U],I[R])}}runEuclideanAlgorithm(e,n,o){if(e.getDegree()<n.getDegree()){const R=e;e=n,n=R}const s=this.field;let a=e,l=n,u=s.getZero(),h=s.getOne();for(;l.getDegree()>=(o/2|0);){let R=a,U=u;if(a=l,u=h,a.isZero())throw new Ve("r_{i-1} was zero");l=R;let V=s.getZero();const H=a.getCoefficient(a.getDegree()),Q=s.inverse(H);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const he=l.getDegree()-a.getDegree(),pe=s.multiply(l.getCoefficient(l.getDegree()),Q);V=V.addOrSubtract(s.buildMonomial(he,pe)),l=l.addOrSubtract(a.multiplyByMonomial(he,pe))}if(h=V.multiply(u).addOrSubtract(U),l.getDegree()>=a.getDegree())throw new St("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Ve("sigmaTilde(0) was zero");const y=s.inverse(p),b=h.multiplyScalar(y),I=l.multiplyScalar(y);return[b,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const o=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(o[s]=a.inverse(l),s++);if(s!==n)throw new Ve("Error locator degree does not match number of roots");return o}findErrorMagnitudes(e,n){const o=n.length,s=new Int32Array(o),a=this.field;for(let l=0;l<o;l++){const u=a.inverse(n[l]);let h=1;for(let p=0;p<o;p++)if(l!==p){const y=a.multiply(n[p],u),b=(y&1)===0?y|1:y&-2;h=a.multiply(h,b)}s[l]=a.multiply(e.evaluateAt(u),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],u))}return s}}var et;(function(C){C[C.UPPER=0]="UPPER",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.DIGIT=3]="DIGIT",C[C.PUNCT=4]="PUNCT",C[C.BINARY=5]="BINARY"})(et||(et={}));class nt{decode(e){this.ddata=e;let n=e.getBits(),o=this.extractBits(n),s=this.correctBits(o),a=nt.convertBoolArrayToByteArray(s),l=nt.getEncodedData(s),u=new Pe(a,l,null,null);return u.setNumBits(s.length),u}static highLevelDecode(e){return this.getEncodedData(e)}static getEncodedData(e){let n=e.length,o=et.UPPER,s=et.UPPER,a="",l=0;for(;l<n;)if(s===et.BINARY){if(n-l<5)break;let u=nt.readCode(e,l,5);if(l+=5,u===0){if(n-l<11)break;u=nt.readCode(e,l,11)+31,l+=11}for(let h=0;h<u;h++){if(n-l<8){l=n;break}const p=nt.readCode(e,l,8);a+=me.castAsNonUtf8Char(p),l+=8}s=o}else{let u=s===et.DIGIT?4:5;if(n-l<u)break;let h=nt.readCode(e,l,u);l+=u;let p=nt.getCharacter(s,h);p.startsWith("CTRL_")?(o=s,s=nt.getTable(p.charAt(5)),p.charAt(6)==="L"&&(o=s)):(a+=p,s=o)}return a}static getTable(e){switch(e){case"L":return et.LOWER;case"P":return et.PUNCT;case"M":return et.MIXED;case"D":return et.DIGIT;case"B":return et.BINARY;case"U":default:return et.UPPER}}static getCharacter(e,n){switch(e){case et.UPPER:return nt.UPPER_TABLE[n];case et.LOWER:return nt.LOWER_TABLE[n];case et.MIXED:return nt.MIXED_TABLE[n];case et.PUNCT:return nt.PUNCT_TABLE[n];case et.DIGIT:return nt.DIGIT_TABLE[n];default:throw new St("Bad table")}}correctBits(e){let n,o;this.ddata.getNbLayers()<=2?(o=6,n=Se.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(o=8,n=Se.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(o=10,n=Se.AZTEC_DATA_10):(o=12,n=Se.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/o;if(a<s)throw new L;let l=e.length%o,u=new Int32Array(a);for(let I=0;I<a;I++,l+=o)u[I]=nt.readCode(e,l,o);try{new vt(n).decode(u,a-s)}catch(I){throw new L(I)}let h=(1<<o)-1,p=0;for(let I=0;I<s;I++){let R=u[I];if(R===0||R===h)throw new L;(R===1||R===h-1)&&p++}let y=new Array(s*o-p),b=0;for(let I=0;I<s;I++){let R=u[I];if(R===1||R===h-1)y.fill(R>1,b,b+o-1),b+=o-1;else for(let U=o-1;U>=0;--U)y[b++]=(R&1<<U)!==0}return y}extractBits(e){let n=this.ddata.isCompact(),o=this.ddata.getNbLayers(),s=(n?11:14)+o*4,a=new Int32Array(s),l=new Array(this.totalBitsInLayer(o,n));if(n)for(let u=0;u<a.length;u++)a[u]=u;else{let u=s+1+2*F.truncDivision(F.truncDivision(s,2)-1,15),h=s/2,p=F.truncDivision(u,2);for(let y=0;y<h;y++){let b=y+F.truncDivision(y,15);a[h-y-1]=p-b-1,a[h+y]=p+b+1}}for(let u=0,h=0;u<o;u++){let p=(o-u)*4+(n?9:12),y=u*2,b=s-1-y;for(let I=0;I<p;I++){let R=I*2;for(let U=0;U<2;U++)l[h+R+U]=e.get(a[y+U],a[y+I]),l[h+2*p+R+U]=e.get(a[y+I],a[b-U]),l[h+4*p+R+U]=e.get(a[b-U],a[b-I]),l[h+6*p+R+U]=e.get(a[b-I],a[y+U])}h+=p*8}return l}static readCode(e,n,o){let s=0;for(let a=n;a<n+o;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let o=e.length-n;return o>=8?nt.readCode(e,n,8):nt.readCode(e,n,o)<<8-o}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let o=0;o<n.length;o++)n[o]=nt.readByte(e,8*o);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}nt.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"],nt.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"],nt.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
66
+ `,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],nt.PUNCT_TABLE=["","\r",`\r
67
+ `,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],nt.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class Xe{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,o,s){const a=e-o,l=n-s;return Math.sqrt(a*a+l*l)}static sum(e){let n=0;for(let o=0,s=e.length;o!==s;o++){const a=e[o];n+=a}return n}}class In{static floatToIntBits(e){return e}}In.MAX_VALUE=Number.MAX_SAFE_INTEGER;class be{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof be){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*In.floatToIntBits(this.x)+In.floatToIntBits(this.y)}toString(){return"("+this.x+","+this.y+")"}static orderBestPatterns(e){const n=this.distance(e[0],e[1]),o=this.distance(e[1],e[2]),s=this.distance(e[0],e[2]);let a,l,u;if(o>=n&&o>=s?(l=e[0],a=e[1],u=e[2]):s>=o&&s>=n?(l=e[1],a=e[0],u=e[2]):(l=e[2],a=e[0],u=e[1]),this.crossProductZ(a,l,u)<0){const h=a;a=u,u=h}e[0]=a,e[1]=l,e[2]=u}static distance(e,n){return Xe.distance(e.x,e.y,n.x,n.y)}static crossProductZ(e,n,o){const s=n.x,a=n.y;return(o.x-s)*(e.y-a)-(o.y-a)*(e.x-s)}}class Bn{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class $n extends Bn{constructor(e,n,o,s,a){super(e,n),this.compact=o,this.nbDatablocks=s,this.nbLayers=a}getNbLayers(){return this.nbLayers}getNbDatablocks(){return this.nbDatablocks}isCompact(){return this.compact}}class qt{constructor(e,n,o,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=qt.INIT_SIZE),o==null&&(o=e.getWidth()/2|0),s==null&&(s=e.getHeight()/2|0);const a=n/2|0;if(this.leftInit=o-a,this.rightInit=o+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 q}detect(){let e=this.leftInit,n=this.rightInit,o=this.upInit,s=this.downInit,a=!1,l=!0,u=!1,h=!1,p=!1,y=!1,b=!1;const I=this.width,R=this.height;for(;l;){l=!1;let U=!0;for(;(U||!h)&&n<I;)U=this.containsBlackPoint(o,s,n,!1),U?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let V=!0;for(;(V||!p)&&s<R;)V=this.containsBlackPoint(e,n,s,!0),V?(s++,l=!0,p=!0):p||s++;if(s>=R){a=!0;break}let H=!0;for(;(H||!y)&&e>=0;)H=this.containsBlackPoint(o,s,e,!1),H?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let Q=!0;for(;(Q||!b)&&o>=0;)Q=this.containsBlackPoint(e,n,o,!0),Q?(o--,l=!0,b=!0):b||o--;if(o<0){a=!0;break}l&&(u=!0)}if(!a&&u){const U=n-e;let V=null;for(let pe=1;V===null&&pe<U;pe++)V=this.getBlackPointOnSegment(e,s-pe,e+pe,s);if(V==null)throw new q;let H=null;for(let pe=1;H===null&&pe<U;pe++)H=this.getBlackPointOnSegment(e,o+pe,e+pe,o);if(H==null)throw new q;let Q=null;for(let pe=1;Q===null&&pe<U;pe++)Q=this.getBlackPointOnSegment(n,o+pe,n-pe,o);if(Q==null)throw new q;let he=null;for(let pe=1;he===null&&pe<U;pe++)he=this.getBlackPointOnSegment(n,s-pe,n-pe,s);if(he==null)throw new q;return this.centerEdges(he,V,Q,H)}else throw new q}getBlackPointOnSegment(e,n,o,s){const a=Xe.round(Xe.distance(e,n,o,s)),l=(o-e)/a,u=(s-n)/a,h=this.image;for(let p=0;p<a;p++){const y=Xe.round(e+p*l),b=Xe.round(n+p*u);if(h.get(y,b))return new be(y,b)}return null}centerEdges(e,n,o,s){const a=e.getX(),l=e.getY(),u=n.getX(),h=n.getY(),p=o.getX(),y=o.getY(),b=s.getX(),I=s.getY(),R=qt.CORR;return a<this.width/2?[new be(b-R,I+R),new be(u+R,h+R),new be(p-R,y-R),new be(a+R,l-R)]:[new be(b+R,I+R),new be(u+R,h-R),new be(p-R,y+R),new be(a-R,l-R)]}containsBlackPoint(e,n,o,s){const a=this.image;if(s){for(let l=e;l<=n;l++)if(a.get(l,o))return!0}else for(let l=e;l<=n;l++)if(a.get(o,l))return!0;return!1}}qt.INIT_SIZE=10,qt.CORR=1;class jn{static checkAndNudgePoints(e,n){const o=e.getWidth(),s=e.getHeight();let a=!0;for(let l=0;l<n.length&&a;l+=2){const u=Math.floor(n[l]),h=Math.floor(n[l+1]);if(u<-1||u>o||h<-1||h>s)throw new q;a=!1,u===-1?(n[l]=0,a=!0):u===o&&(n[l]=o-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 u=Math.floor(n[l]),h=Math.floor(n[l+1]);if(u<-1||u>o||h<-1||h>s)throw new q;a=!1,u===-1?(n[l]=0,a=!0):u===o&&(n[l]=o-1,a=!0),h===-1?(n[l+1]=0,a=!0):h===s&&(n[l+1]=s-1,a=!0)}}}class Ft{constructor(e,n,o,s,a,l,u,h,p){this.a11=e,this.a21=n,this.a31=o,this.a12=s,this.a22=a,this.a32=l,this.a13=u,this.a23=h,this.a33=p}static quadrilateralToQuadrilateral(e,n,o,s,a,l,u,h,p,y,b,I,R,U,V,H){const Q=Ft.quadrilateralToSquare(e,n,o,s,a,l,u,h);return Ft.squareToQuadrilateral(p,y,b,I,R,U,V,H).times(Q)}transformPoints(e){const n=e.length,o=this.a11,s=this.a12,a=this.a13,l=this.a21,u=this.a22,h=this.a23,p=this.a31,y=this.a32,b=this.a33;for(let I=0;I<n;I+=2){const R=e[I],U=e[I+1],V=a*R+h*U+b;e[I]=(o*R+l*U+p)/V,e[I+1]=(s*R+u*U+y)/V}}transformPointsWithValues(e,n){const o=this.a11,s=this.a12,a=this.a13,l=this.a21,u=this.a22,h=this.a23,p=this.a31,y=this.a32,b=this.a33,I=e.length;for(let R=0;R<I;R++){const U=e[R],V=n[R],H=a*U+h*V+b;e[R]=(o*U+l*V+p)/H,n[R]=(s*U+u*V+y)/H}}static squareToQuadrilateral(e,n,o,s,a,l,u,h){const p=e-o+a-u,y=n-s+l-h;if(p===0&&y===0)return new Ft(o-e,a-o,e,s-n,l-s,n,0,0,1);{const b=o-a,I=u-a,R=s-l,U=h-l,V=b*U-I*R,H=(p*U-I*y)/V,Q=(b*y-p*R)/V;return new Ft(o-e+H*o,u-e+Q*u,e,s-n+H*s,h-n+Q*h,n,H,Q,1)}}static quadrilateralToSquare(e,n,o,s,a,l,u,h){return Ft.squareToQuadrilateral(e,n,o,s,a,l,u,h).buildAdjoint()}buildAdjoint(){return new Ft(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 Ft(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 rr extends jn{sampleGrid(e,n,o,s,a,l,u,h,p,y,b,I,R,U,V,H,Q,he,pe){const ce=Ft.quadrilateralToQuadrilateral(s,a,l,u,h,p,y,b,I,R,U,V,H,Q,he,pe);return this.sampleGridWithTransform(e,n,o,ce)}sampleGridWithTransform(e,n,o,s){if(n<=0||o<=0)throw new q;const a=new te(n,o),l=new Float32Array(2*n);for(let u=0;u<o;u++){const h=l.length,p=u+.5;for(let y=0;y<h;y+=2)l[y]=y/2+.5,l[y+1]=p;s.transformPoints(l),jn.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,u)}catch{throw new q}}return a}}class sn{static setGridSampler(e){sn.gridSampler=e}static getInstance(){return sn.gridSampler}}sn.gridSampler=new rr;class At{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new be(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class or{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(),o=this.getBullsEyeCorners(n);if(e){let l=o[0];o[0]=o[2],o[2]=l}this.extractParameters(o);let s=this.sampleGrid(this.image,o[this.shift%4],o[(this.shift+1)%4],o[(this.shift+2)%4],o[(this.shift+3)%4]),a=this.getMatrixCornerPoints(o);return new $n(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 q;let n=2*this.nbCenterLayers,o=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(o,n);let s=0;for(let l=0;l<4;l++){let u=o[(this.shift+l)%4];this.compact?(s<<=7,s+=u>>1&127):(s<<=10,s+=(u>>2&992)+(u>>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 o=0;e.forEach((s,a,l)=>{let u=(s>>n-2<<1)+(s&1);o=(o<<3)+u}),o=((o&1)<<11)+(o>>1);for(let s=0;s<4;s++)if(F.bitCount(o^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new q}getCorrectedParameterData(e,n){let o,s;n?(o=7,s=2):(o=10,s=4);let a=o-s,l=new Int32Array(o);for(let h=o-1;h>=0;--h)l[h]=e&15,e>>=4;try{new vt(Se.AZTEC_PARAM).decode(l,a)}catch{throw new q}let u=0;for(let h=0;h<s;h++)u=(u<<4)+l[h];return u}getBullsEyeCorners(e){let n=e,o=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let b=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(o,l,1,1),R=this.getFirstDifferent(s,l,-1,1),U=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let V=this.distancePoint(U,b)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(V<.75||V>1.25||!this.isWhiteOrBlackRectangle(b,I,R,U))break}n=b,o=I,s=R,a=U,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new q;this.compact=this.nbCenterLayers===5;let u=new be(n.getX()+.5,n.getY()-.5),h=new be(o.getX()+.5,o.getY()+.5),p=new be(s.getX()-.5,s.getY()+.5),y=new be(a.getX()-.5,a.getY()-.5);return this.expandSquare([u,h,p,y],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,o,s;try{let u=new qt(this.image).detect();e=u[0],n=u[1],o=u[2],s=u[3]}catch{let h=this.image.getWidth()/2,p=this.image.getHeight()/2;e=this.getFirstDifferent(new At(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new At(h+7,p+7),!1,1,1).toResultPoint(),o=this.getFirstDifferent(new At(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new At(h-7,p-7),!1,-1,-1).toResultPoint()}let a=Xe.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Xe.round((e.getY()+s.getY()+n.getY()+o.getY())/4);try{let u=new qt(this.image,15,a,l).detect();e=u[0],n=u[1],o=u[2],s=u[3]}catch{e=this.getFirstDifferent(new At(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new At(a+7,l+7),!1,1,1).toResultPoint(),o=this.getFirstDifferent(new At(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new At(a-7,l-7),!1,-1,-1).toResultPoint()}return a=Xe.round((e.getX()+s.getX()+n.getX()+o.getX())/4),l=Xe.round((e.getY()+s.getY()+n.getY()+o.getY())/4),new At(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,o,s,a){let l=sn.getInstance(),u=this.getDimension(),h=u/2-this.nbCenterLayers,p=u/2+this.nbCenterLayers;return l.sampleGrid(e,u,u,h,h,p,h,p,p,h,p,n.getX(),n.getY(),o.getX(),o.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,o){let s=0,a=this.distanceResultPoint(e,n),l=a/o,u=e.getX(),h=e.getY(),p=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let b=0;b<o;b++)this.image.get(Xe.round(u+b*p),Xe.round(h+b*y))&&(s|=1<<o-b-1);return s}isWhiteOrBlackRectangle(e,n,o,s){let a=3;e=new At(e.getX()-a,e.getY()+a),n=new At(n.getX()-a,n.getY()-a),o=new At(o.getX()+a,o.getY()-a),s=new At(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let u=this.getColor(e,n);return u!==l||(u=this.getColor(n,o),u!==l)?!1:(u=this.getColor(o,s),u===l)}getColor(e,n){let o=this.distancePoint(e,n),s=(n.getX()-e.getX())/o,a=(n.getY()-e.getY())/o,l=0,u=e.getX(),h=e.getY(),p=this.image.get(e.getX(),e.getY()),y=Math.ceil(o);for(let I=0;I<y;I++)u+=s,h+=a,this.image.get(Xe.round(u),Xe.round(h))!==p&&l++;let b=l/o;return b>.1&&b<.9?0:b<=.1===p?1:-1}getFirstDifferent(e,n,o,s){let a=e.getX()+o,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=o,l+=s;for(a-=o,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=o;for(a-=o;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new At(a,l)}expandSquare(e,n,o){let s=o/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),u=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,p=new be(u+s*a,h+s*l),y=new be(u-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),u=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let b=new be(u+s*a,h+s*l),I=new be(u-s*a,h-s*l);return[p,b,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=Xe.round(e.getX()),o=Xe.round(e.getY());return this.isValid(n,o)}distancePoint(e,n){return Xe.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return Xe.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*(F.truncDivision(this.nbLayers-4,8)+1)+15}}class Ln{decode(e,n=null){let o=null,s=new or(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new nt().decode(y)}catch(y){o=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new nt().decode(y)}catch(y){throw o??y}let u=new qe(l.getText(),l.getRawBytes(),l.getNumBits(),a,ie.AZTEC,P.currentTimeMillis()),h=l.getByteSegments();h!=null&&u.putMetadata(_e.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&u.putMetadata(_e.ERROR_CORRECTION_LEVEL,p),u}reportFoundResultPoints(e,n){if(e!=null){let o=e.get(B.NEED_RESULT_POINT_CALLBACK);o!=null&&n.forEach((s,a,l)=>{o.foundPossibleResultPoint(s)})}}reset(){}}class wr extends Ze{constructor(e=500){super(new Ln,e)}}class gt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(B.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),u=l.getResultMetadata();let h=270;u!==null&&u.get(_e.ORIENTATION)===!0&&(h=h+u.get(_e.ORIENTATION)%360),l.putMetadata(_e.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const y=a.getHeight();for(let b=0;b<p.length;b++)p[b]=new be(y-p[b].getY()-1,p[b].getX())}return l}else throw new q}}reset(){}doDecode(e,n){const o=e.getWidth(),s=e.getHeight();let a=new re(o);const l=n&&n.get(B.TRY_HARDER)===!0,u=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 b=Math.trunc((y+1)/2),I=(y&1)===0,R=p+u*(I?b:-b);if(R<0||R>=s)break;try{a=e.getBlackRow(R,a)}catch{continue}for(let U=0;U<2;U++){if(U===1&&(a.reverse(),n&&n.get(B.NEED_RESULT_POINT_CALLBACK)===!0)){const V=new Map;n.forEach((H,Q)=>V.set(Q,H)),V.delete(B.NEED_RESULT_POINT_CALLBACK),n=V}try{const V=this.decodeRow(R,a,n);if(U===1){V.putMetadata(_e.ORIENTATION,180);const H=V.getResultPoints();H!==null&&(H[0]=new be(o-H[0].getX()-1,H[0].getY()),H[1]=new be(o-H[1].getX()-1,H[1].getY()))}return V}catch{}}}throw new q}static recordPattern(e,n,o){const s=o.length;for(let p=0;p<s;p++)o[p]=0;const a=e.getSize();if(n>=a)throw new q;let l=!e.get(n),u=0,h=n;for(;h<a;){if(e.get(h)!==l)o[u]++;else{if(++u===s)break;o[u]=1,l=!l}h++}if(!(u===s||u===s-1&&h===a))throw new q}static recordPatternInReverse(e,n,o){let s=o.length,a=e.get(n);for(;n>0&&s>=0;)e.get(--n)!==a&&(s--,a=!a);if(s>=0)throw new q;gt.recordPattern(e,n+1,o)}static patternMatchVariance(e,n,o){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 u=a/l;o*=u;let h=0;for(let p=0;p<s;p++){const y=e[p],b=n[p]*u,I=y>b?y-b:b-y;if(I>o)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class ge extends gt{static findStartPattern(e){const n=e.getSize(),o=e.getNextSet(0);let s=0,a=Int32Array.from([0,0,0,0,0,0]),l=o,u=!1;const h=6;for(let p=o;p<n;p++)if(e.get(p)!==u)a[s]++;else{if(s===h-1){let y=ge.MAX_AVG_VARIANCE,b=-1;for(let I=ge.CODE_START_A;I<=ge.CODE_START_C;I++){const R=gt.patternMatchVariance(a,ge.CODE_PATTERNS[I],ge.MAX_INDIVIDUAL_VARIANCE);R<y&&(y=R,b=I)}if(b>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,b]);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,u=!u}throw new q}static decodeCode(e,n,o){gt.recordPattern(e,o,n);let s=ge.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<ge.CODE_PATTERNS.length;l++){const u=ge.CODE_PATTERNS[l],h=this.patternMatchVariance(n,u,ge.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new q}decodeRow(e,n,o){const s=o&&o.get(B.ASSUME_GS1)===!0,a=ge.findStartPattern(n),l=a[2];let u=0;const h=new Uint8Array(20);h[u++]=l;let p;switch(l){case ge.CODE_START_A:p=ge.CODE_CODE_A;break;case ge.CODE_START_B:p=ge.CODE_CODE_B;break;case ge.CODE_START_C:p=ge.CODE_CODE_C;break;default:throw new L}let y=!1,b=!1,I="",R=a[0],U=a[1];const V=Int32Array.from([0,0,0,0,0,0]);let H=0,Q=0,he=l,pe=0,ce=!0,Ke=!1,He=!1;for(;!y;){const Tr=b;switch(b=!1,H=Q,Q=ge.decodeCode(n,V,U),h[u++]=Q,Q!==ge.CODE_STOP&&(ce=!0),Q!==ge.CODE_STOP&&(pe++,he+=pe*Q),R=U,U+=V.reduce((bd,Ad)=>bd+Ad,0),Q){case ge.CODE_START_A:case ge.CODE_START_B:case ge.CODE_START_C:throw new L}switch(p){case ge.CODE_CODE_A:if(Q<64)He===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),He=!1;else if(Q<96)He===Ke?I+=String.fromCharCode(Q-64):I+=String.fromCharCode(Q+64),He=!1;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_FNC_2:case ge.CODE_FNC_3:break;case ge.CODE_FNC_4_A:!Ke&&He?(Ke=!0,He=!1):Ke&&He?(Ke=!1,He=!1):He=!0;break;case ge.CODE_SHIFT:b=!0,p=ge.CODE_CODE_B;break;case ge.CODE_CODE_B:p=ge.CODE_CODE_B;break;case ge.CODE_CODE_C:p=ge.CODE_CODE_C;break;case ge.CODE_STOP:y=!0;break}break;case ge.CODE_CODE_B:if(Q<96)He===Ke?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),He=!1;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_FNC_2:case ge.CODE_FNC_3:break;case ge.CODE_FNC_4_B:!Ke&&He?(Ke=!0,He=!1):Ke&&He?(Ke=!1,He=!1):He=!0;break;case ge.CODE_SHIFT:b=!0,p=ge.CODE_CODE_A;break;case ge.CODE_CODE_A:p=ge.CODE_CODE_A;break;case ge.CODE_CODE_C:p=ge.CODE_CODE_C;break;case ge.CODE_STOP:y=!0;break}break;case ge.CODE_CODE_C:if(Q<100)Q<10&&(I+="0"),I+=Q;else switch(Q!==ge.CODE_STOP&&(ce=!1),Q){case ge.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case ge.CODE_CODE_A:p=ge.CODE_CODE_A;break;case ge.CODE_CODE_B:p=ge.CODE_CODE_B;break;case ge.CODE_STOP:y=!0;break}break}Tr&&(p=p===ge.CODE_CODE_A?ge.CODE_CODE_B:ge.CODE_CODE_A)}const tn=U-R;if(U=n.getNextUnset(U),!n.isRange(U,Math.min(n.getSize(),U+(U-R)/2),!1))throw new q;if(he-=pe*H,he%103!==H)throw new T;const yn=I.length;if(yn===0)throw new q;yn>0&&ce&&(p===ge.CODE_CODE_C?I=I.substring(0,yn-2):I=I.substring(0,yn-1));const nn=(a[1]+a[0])/2,ft=R+tn/2,Ht=h.length,an=new Uint8Array(Ht);for(let Tr=0;Tr<Ht;Tr++)an[Tr]=h[Tr];const Sr=[new be(nn,e),new be(ft,e)];return new qe(I,an,0,Sr,ie.CODE_128,new Date().getTime())}}ge.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])],ge.MAX_AVG_VARIANCE=.25,ge.MAX_INDIVIDUAL_VARIANCE=.7,ge.CODE_SHIFT=98,ge.CODE_CODE_C=99,ge.CODE_CODE_B=100,ge.CODE_CODE_A=101,ge.CODE_FNC_1=102,ge.CODE_FNC_2=97,ge.CODE_FNC_3=96,ge.CODE_FNC_4_A=101,ge.CODE_FNC_4_B=100,ge.CODE_START_A=103,ge.CODE_START_B=104,ge.CODE_START_C=105,ge.CODE_STOP=106;class O extends gt{constructor(e=!1,n=!1){super(),this.usingCheckDigit=e,this.extendedMode=n,this.decodeRowResult="",this.counters=new Int32Array(9)}decodeRow(e,n,o){let s=this.counters;s.fill(0),this.decodeRowResult="";let a=O.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),u=n.getSize(),h,p;do{O.recordPattern(n,l,s);let V=O.toNarrowWidePattern(s);if(V<0)throw new q;h=O.patternToChar(V),this.decodeRowResult+=h,p=l;for(let H of s)l+=H;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let y=0;for(let V of s)y+=V;let b=l-p-y;if(l!==u&&b*2<y)throw new q;if(this.usingCheckDigit){let V=this.decodeRowResult.length-1,H=0;for(let Q=0;Q<V;Q++)H+=O.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Q));if(this.decodeRowResult.charAt(V)!==O.ALPHABET_STRING.charAt(H%43))throw new T;this.decodeRowResult=this.decodeRowResult.substring(0,V)}if(this.decodeRowResult.length===0)throw new q;let I;this.extendedMode?I=O.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let R=(a[1]+a[0])/2,U=p+y/2;return new qe(I,null,0,[new be(R,e),new be(U,e)],ie.CODE_39,new Date().getTime())}static findAsteriskPattern(e,n){let o=e.getSize(),s=e.getNextSet(0),a=0,l=s,u=!1,h=n.length;for(let p=s;p<o;p++)if(e.get(p)!==u)n[a]++;else{if(a===h-1){if(this.toNarrowWidePattern(n)===O.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,u=!u}throw new q}static toNarrowWidePattern(e){let n=e.length,o=0,s;do{let a=2147483647;for(let h of e)h<a&&h>o&&(a=h);o=a,s=0;let l=0,u=0;for(let h=0;h<n;h++){let p=e[h];p>o&&(u|=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>o&&(s--,p*2>=l))return-1}return u}}while(s>3);return-1}static patternToChar(e){for(let n=0;n<O.CHARACTER_ENCODINGS.length;n++)if(O.CHARACTER_ENCODINGS[n]===e)return O.ALPHABET_STRING.charAt(n);if(e===O.ASTERISK_ENCODING)return"*";throw new q}static decodeExtended(e){let n=e.length,o="";for(let s=0;s<n;s++){let a=e.charAt(s);if(a==="+"||a==="$"||a==="%"||a==="/"){let l=e.charAt(s+1),u="\0";switch(a){case"+":if(l>="A"&&l<="Z")u=String.fromCharCode(l.charCodeAt(0)+32);else throw new L;break;case"$":if(l>="A"&&l<="Z")u=String.fromCharCode(l.charCodeAt(0)-64);else throw new L;break;case"%":if(l>="A"&&l<="E")u=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")u=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")u=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")u=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")u="\0";else if(l==="V")u="@";else if(l==="W")u="`";else if(l==="X"||l==="Y"||l==="Z")u="";else throw new L;break;case"/":if(l>="A"&&l<="O")u=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")u=":";else throw new L;break}o+=u,s++}else o+=a}return o}}O.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",O.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],O.ASTERISK_ENCODING=148;class ne extends gt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,o){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new fe;ne.decodeMiddle(n,s[1],a[0],l);let u=l.toString(),h=null;o!=null&&(h=o.get(B.ALLOWED_LENGTHS)),h==null&&(h=ne.DEFAULT_ALLOWED_LENGTHS);let p=u.length,y=!1,b=0;for(let U of h){if(p===U){y=!0;break}U>b&&(b=U)}if(!y&&p>b&&(y=!0),!y)throw new L;const I=[new be(s[1],e),new be(a[0],e)];return new qe(u,null,0,I,ie.ITF,new Date().getTime())}static decodeMiddle(e,n,o,s){let a=new Int32Array(10),l=new Int32Array(5),u=new Int32Array(5);for(a.fill(0),l.fill(0),u.fill(0);n<o;){gt.recordPattern(e,n,a);for(let p=0;p<5;p++){let y=2*p;l[p]=a[y],u[p]=a[y+1]}let h=ne.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(u),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=ne.skipWhiteSpace(e),o=ne.findGuardPattern(e,n,ne.START_PATTERN);return this.narrowLineWidth=(o[1]-o[0])/4,this.validateQuietZone(e,o[0]),o}validateQuietZone(e,n){let o=this.narrowLineWidth*10;o=o<n?o:n;for(let s=n-1;o>0&&s>=0&&!e.get(s);s--)o--;if(o!==0)throw new q}static skipWhiteSpace(e){const n=e.getSize(),o=e.getNextSet(0);if(o===n)throw new q;return o}decodeEnd(e){e.reverse();try{let n=ne.skipWhiteSpace(e),o;try{o=ne.findGuardPattern(e,n,ne.END_PATTERN_REVERSED[0])}catch(a){a instanceof q&&(o=ne.findGuardPattern(e,n,ne.END_PATTERN_REVERSED[1]))}this.validateQuietZone(e,o[0]);let s=o[0];return o[0]=e.getSize()-o[1],o[1]=e.getSize()-s,o}finally{e.reverse()}}static findGuardPattern(e,n,o){let s=o.length,a=new Int32Array(s),l=e.getSize(),u=!1,h=0,p=n;a.fill(0);for(let y=n;y<l;y++)if(e.get(y)!==u)a[h]++;else{if(h===s-1){if(gt.patternMatchVariance(a,o,ne.MAX_INDIVIDUAL_VARIANCE)<ne.MAX_AVG_VARIANCE)return[p,y];p+=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,u=!u}throw new q}static decodeDigit(e){let n=ne.MAX_AVG_VARIANCE,o=-1,s=ne.PATTERNS.length;for(let a=0;a<s;a++){let l=ne.PATTERNS[a],u=gt.patternMatchVariance(e,l,ne.MAX_INDIVIDUAL_VARIANCE);u<n?(n=u,o=a):u===n&&(o=-1)}if(o>=0)return o%10;throw new q}}ne.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])],ne.MAX_AVG_VARIANCE=.38,ne.MAX_INDIVIDUAL_VARIANCE=.5,ne.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],ne.START_PATTERN=Int32Array.from([1,1,1,1]),ne.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class Me extends gt{constructor(){super(...arguments),this.decodeRowStringBuffer=""}static findStartGuardPattern(e){let n=!1,o,s=0,a=Int32Array.from([0,0,0]);for(;!n;){a=Int32Array.from([0,0,0]),o=Me.findGuardPattern(e,s,!1,this.START_END_PATTERN,a);let l=o[0];s=o[1];let u=l-(s-l);u>=0&&(n=e.isRange(u,l,!1))}return o}static checkChecksum(e){return Me.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let o=parseInt(e.charAt(n-1),10);return Me.getStandardUPCEANChecksum(e.substring(0,n-1))===o}static getStandardUPCEANChecksum(e){let n=e.length,o=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 L;o+=a}o*=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 L;o+=a}return(1e3-o)%10}static decodeEnd(e,n){return Me.findGuardPattern(e,n,!1,Me.START_END_PATTERN,new Int32Array(Me.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,o,s){return this.findGuardPattern(e,n,o,s,new Int32Array(s.length))}static findGuardPattern(e,n,o,s,a){let l=e.getSize();n=o?e.getNextUnset(n):e.getNextSet(n);let u=0,h=n,p=s.length,y=o;for(let b=n;b<l;b++)if(e.get(b)!==y)a[u]++;else{if(u===p-1){if(gt.patternMatchVariance(a,s,Me.MAX_INDIVIDUAL_VARIANCE)<Me.MAX_AVG_VARIANCE)return Int32Array.from([h,b]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let R=0;R<u-1;R++)a[R]=I[R];a[u-1]=0,a[u]=0,u--}else u++;a[u]=1,y=!y}throw new q}static decodeDigit(e,n,o,s){this.recordPattern(e,o,n);let a=this.MAX_AVG_VARIANCE,l=-1,u=s.length;for(let h=0;h<u;h++){let p=s[h],y=gt.patternMatchVariance(n,p,Me.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new q}}Me.MAX_AVG_VARIANCE=.48,Me.MAX_INDIVIDUAL_VARIANCE=.7,Me.START_END_PATTERN=Int32Array.from([1,1,1]),Me.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),Me.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),Me.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 Ee{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,o){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,o,s),l=s.toString(),u=Ee.parseExtensionString(l),h=[new be((o[0]+o[1])/2,e),new be(a,e)],p=new qe(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return u!=null&&p.putAllMetadata(u),p}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let p=0;p<5&&l<a;p++){let y=Me.decodeDigit(e,s,l,Me.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(o.length!==5)throw new q;let h=this.determineCheckDigit(u);if(Ee.extensionChecksum(o.toString())!==h)throw new q;return l}static extensionChecksum(e){let n=e.length,o=0;for(let s=n-2;s>=0;s-=2)o+=e.charAt(s).charCodeAt(0)-48;o*=3;for(let s=n-1;s>=0;s-=2)o+=e.charAt(s).charCodeAt(0)-48;return o*=3,o%10}determineCheckDigit(e){for(let n=0;n<10;n++)if(e===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new q}static parseExtensionString(e){if(e.length!==5)return null;let n=Ee.parseExtension5String(e);return n==null?null:new Map([[_e.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 o=parseInt(e.substring(1)),s=(o/100).toString(),a=o%100,l=a<10?"0"+a:a.toString();return n+s+"."+l}}class Oe{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}decodeRow(e,n,o){let s=this.decodeRowStringBuffer,a=this.decodeMiddle(n,o,s),l=s.toString(),u=Oe.parseExtensionString(l),h=[new be((o[0]+o[1])/2,e),new be(a,e)],p=new qe(l,null,0,h,ie.UPC_EAN_EXTENSION,new Date().getTime());return u!=null&&p.putAllMetadata(u),p}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let h=0;h<2&&l<a;h++){let p=Me.decodeDigit(e,s,l,Me.L_AND_G_PATTERNS);o+=String.fromCharCode(48+p%10);for(let y of s)l+=y;p>=10&&(u|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(o.length!==2)throw new q;if(parseInt(o.toString())%4!==u)throw new q;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[_e.ISSUE_NUMBER,parseInt(e)]])}}class rt{static decodeRow(e,n,o){let s=Me.findGuardPattern(n,o,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new Ee().decodeRow(e,n,s)}catch{return new Oe().decodeRow(e,n,s)}}}rt.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class Ye extends Me{constructor(){super(),this.decodeRowStringBuffer="",Ye.L_AND_G_PATTERNS=Ye.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=Ye.L_PATTERNS[e-10],o=new Int32Array(n.length);for(let s=0;s<n.length;s++)o[s]=n[n.length-s-1];Ye.L_AND_G_PATTERNS[e]=o}}decodeRow(e,n,o){let s=Ye.findStartGuardPattern(n),a=o==null?null:o.get(B.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ce=new be((s[0]+s[1])/2,e);a.foundPossibleResultPoint(ce)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),u=l.rowOffset,h=l.resultString;if(a!=null){const ce=new be(u,e);a.foundPossibleResultPoint(ce)}let p=this.decodeEnd(n,u);if(a!=null){const ce=new be((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ce)}let y=p[1],b=y+(y-p[0]);if(b>=n.getSize()||!n.isRange(y,b,!1))throw new q;let I=h.toString();if(I.length<8)throw new L;if(!Ye.checkChecksum(I))throw new T;let R=(s[1]+s[0])/2,U=(p[1]+p[0])/2,V=this.getBarcodeFormat(),H=[new be(R,e),new be(U,e)],Q=new qe(I,null,0,H,V,new Date().getTime()),he=0;try{let ce=rt.decodeRow(e,n,p[1]);Q.putMetadata(_e.UPC_EAN_EXTENSION,ce.getText()),Q.putAllMetadata(ce.getResultMetadata()),Q.addResultPoints(ce.getResultPoints()),he=ce.getText().length}catch{}let pe=o==null?null:o.get(B.ALLOWED_EAN_EXTENSIONS);if(pe!=null){let ce=!1;for(let Ke in pe)if(he.toString()===Ke){ce=!0;break}if(!ce)throw new q}return Q}decodeEnd(e,n){return Ye.findGuardPattern(e,n,!1,Ye.START_END_PATTERN,new Int32Array(Ye.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return Ye.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let o=parseInt(e.charAt(n-1),10);return Ye.getStandardUPCEANChecksum(e.substring(0,n-1))===o}static getStandardUPCEANChecksum(e){let n=e.length,o=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 L;o+=a}o*=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 L;o+=a}return(1e3-o)%10}}class Fn extends Ye{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,o){let s=this.decodeMiddleCounters;s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l=n[1],u=0;for(let p=0;p<6&&l<a;p++){let y=Ye.decodeDigit(e,s,l,Ye.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<5-p)}o=Fn.determineFirstDigit(o,u),l=Ye.findGuardPattern(e,l,!0,Ye.MIDDLE_PATTERN,new Int32Array(Ye.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+y);for(let b of s)l+=b}return{rowOffset:l,resultString:o}}getBarcodeFormat(){return ie.EAN_13}static determineFirstDigit(e,n){for(let o=0;o<10;o++)if(n===this.FIRST_DIGIT_ENCODINGS[o])return e=String.fromCharCode(48+o)+e,e;throw new q}}Fn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class as extends Ye{constructor(){super(),this.decodeMiddleCounters=Int32Array.from([0,0,0,0])}decodeMiddle(e,n,o){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=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+p);for(let y of s)l+=y}l=Ye.findGuardPattern(e,l,!0,Ye.MIDDLE_PATTERN,new Int32Array(Ye.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=Ye.decodeDigit(e,s,l,Ye.L_PATTERNS);o+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:o}}getBarcodeFormat(){return ie.EAN_8}}class ls extends Ye{constructor(){super(...arguments),this.ean13Reader=new Fn}getBarcodeFormat(){return ie.UPC_A}decode(e,n){return this.maybeReturnResult(this.ean13Reader.decode(e))}decodeRow(e,n,o){return this.maybeReturnResult(this.ean13Reader.decodeRow(e,n,o))}decodeMiddle(e,n,o){return this.ean13Reader.decodeMiddle(e,n,o)}maybeReturnResult(e){let n=e.getText();if(n.charAt(0)==="0"){let o=new qe(n.substring(1),null,null,e.getResultPoints(),ie.UPC_A);return e.getResultMetadata()!=null&&o.putAllMetadata(e.getResultMetadata()),o}else throw new q}reset(){this.ean13Reader.reset()}}class xn extends Ye{constructor(){super(),this.decodeMiddleCounters=new Int32Array(4)}decodeMiddle(e,n,o){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],u=0;for(let p=0;p<6&&l<a;p++){const y=xn.decodeDigit(e,s,l,xn.L_AND_G_PATTERNS);o+=String.fromCharCode(48+y%10);for(let b of s)l+=b;y>=10&&(u|=1<<5-p)}let h=xn.determineNumSysAndCheckDigit(o,u);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return xn.findGuardPatternWithoutCounters(e,n,!0,xn.MIDDLE_END_PATTERN)}checkChecksum(e){return Ye.checkChecksum(xn.convertUPCEtoUPCA(e))}static determineNumSysAndCheckDigit(e,n){for(let o=0;o<=1;o++)for(let s=0;s<10;s++)if(n===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[o][s]){let a=String.fromCharCode(48+o),l=String.fromCharCode(48+s);return a+e+l}throw q.getNotFoundInstance()}getBarcodeFormat(){return ie.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),o=new fe;o.append(e.charAt(0));let s=n[5];switch(s){case 0:case 1:case 2:o.appendChars(n,0,2),o.append(s),o.append("0000"),o.appendChars(n,2,3);break;case 3:o.appendChars(n,0,3),o.append("00000"),o.appendChars(n,3,2);break;case 4:o.appendChars(n,0,4),o.append("00000"),o.append(n[4]);break;default:o.appendChars(n,0,5),o.append("0000"),o.append(s);break}return e.length>=8&&o.append(e.charAt(7)),o.toString()}}xn.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),xn.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 $o extends gt{constructor(e){super();let n=e==null?null:e.get(B.POSSIBLE_FORMATS),o=[];c(n)?(o.push(new Fn),o.push(new ls),o.push(new as),o.push(new xn)):(n.indexOf(ie.EAN_13)>-1&&o.push(new Fn),n.indexOf(ie.UPC_A)>-1&&o.push(new ls),n.indexOf(ie.EAN_8)>-1&&o.push(new as),n.indexOf(ie.UPC_E)>-1&&o.push(new xn)),this.readers=o}decodeRow(e,n,o){for(let s of this.readers)try{const a=s.decodeRow(e,n,o),l=a.getBarcodeFormat()===ie.EAN_13&&a.getText().charAt(0)==="0",u=o==null?null:o.get(B.POSSIBLE_FORMATS),h=u==null||u.includes(ie.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new qe(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 q}reset(){for(let e of this.readers)e.reset()}}class Wt extends gt{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 o=0;o<n.length;o++)if(gt.patternMatchVariance(e,n[o],Wt.MAX_INDIVIDUAL_VARIANCE)<Wt.MAX_AVG_VARIANCE)return o;throw new q}static count(e){return Xe.sum(new Int32Array(e))}static increment(e,n){let o=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],o=a);e[o]++}static decrement(e,n){let o=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],o=a);e[o]--}static isFinderPattern(e){let n=e[0]+e[1],o=n+e[2]+e[3],s=n/o;if(s>=Wt.MIN_FINDER_PATTERN_RATIO&&s<=Wt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let u of e)u>l&&(l=u),u<a&&(a=u);return l<10*a}return!1}}Wt.MAX_AVG_VARIANCE=.2,Wt.MAX_INDIVIDUAL_VARIANCE=.45,Wt.MIN_FINDER_PATTERN_RATIO=9.5/12,Wt.MAX_FINDER_PATTERN_RATIO=12.5/14;class _r{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 _r))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class co{constructor(e,n,o,s,a){this.value=e,this.startEnd=n,this.value=e,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new be(o,a)),this.resultPoints.push(new be(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof co))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class Sn{constructor(){}static getRSSvalue(e,n,o){let s=0;for(let h of e)s+=h;let a=0,l=0,u=e.length;for(let h=0;h<u-1;h++){let p;for(p=1,l|=1<<h;p<e[h];p++,l&=~(1<<h)){let y=Sn.combins(s-p-1,u-h-2);if(o&&l===0&&s-p-(u-h-1)>=u-h-1&&(y-=Sn.combins(s-p-(u-h),u-h-2)),u-h-1>1){let b=0;for(let I=s-p-(u-h-2);I>n;I--)b+=Sn.combins(s-p-I-1,u-h-3);y-=b*(u-1-h)}else s-p>n&&y--;a+=y}s-=p}return a}static combins(e,n){let o,s;e-n>n?(s=n,o=e-n):(s=e-n,o=n);let a=1,l=1;for(let u=e;u>o;u--)a*=u,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Xu{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let o=12*n,s=new re(o),a=0,u=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(u&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 b=11;b>=0;--b)(y&1<<b)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let b=p.getRightChar().getValue();for(let I=11;I>=0;--I)(b&1<<I)!=0&&s.set(a),a++}}return s}}class ir{constructor(e,n){n?this.decodedInformation=null:(this.finished=e,this.decodedInformation=n)}getDecodedInformation(){return this.decodedInformation}isFinished(){return this.finished}}class jo{constructor(e){this.newPosition=e}getNewPosition(){return this.newPosition}}class Jt extends jo{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Jt.FNC1}}Jt.FNC1="$";class sr extends jo{constructor(e,n,o){super(e),o?(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 hn extends jo{constructor(e,n,o){if(super(e),n<0||n>10||o<0||o>10)throw new L;this.firstDigit=n,this.secondDigit=o}getFirstDigit(){return this.firstDigit}getSecondDigit(){return this.secondDigit}getValue(){return this.firstDigit*10+this.secondDigit}isFirstDigitFNC1(){return this.firstDigit===hn.FNC1}isSecondDigitFNC1(){return this.secondDigit===hn.FNC1}isAnyFNC1(){return this.firstDigit===hn.FNC1||this.secondDigit===hn.FNC1}}hn.FNC1=10;class ve{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new q;let n=e.substring(0,2);for(let a of ve.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(2,a[2],e):ve.processFixedAI(2,a[1],e);if(e.length<3)throw new q;let o=e.substring(0,3);for(let a of ve.THREE_DIGIT_DATA_LENGTH)if(a[0]===o)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(3,a[2],e):ve.processFixedAI(3,a[1],e);for(let a of ve.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===o)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(4,a[2],e):ve.processFixedAI(4,a[1],e);if(e.length<4)throw new q;let s=e.substring(0,4);for(let a of ve.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===ve.VARIABLE_LENGTH?ve.processVariableAI(4,a[2],e):ve.processFixedAI(4,a[1],e);throw new q}static processFixedAI(e,n,o){if(o.length<e)throw new q;let s=o.substring(0,e);if(o.length<e+n)throw new q;let a=o.substring(e,e+n),l=o.substring(e+n),u="("+s+")"+a,h=ve.parseFieldsInGeneralPurpose(l);return h==null?u:u+h}static processVariableAI(e,n,o){let s=o.substring(0,e),a;o.length<e+n?a=o.length:a=e+n;let l=o.substring(e,a),u=o.substring(a),h="("+s+")"+l,p=ve.parseFieldsInGeneralPurpose(u);return p==null?h:h+p}}ve.VARIABLE_LENGTH=[],ve.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",ve.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",ve.VARIABLE_LENGTH,20],["22",ve.VARIABLE_LENGTH,29],["30",ve.VARIABLE_LENGTH,8],["37",ve.VARIABLE_LENGTH,8],["90",ve.VARIABLE_LENGTH,30],["91",ve.VARIABLE_LENGTH,30],["92",ve.VARIABLE_LENGTH,30],["93",ve.VARIABLE_LENGTH,30],["94",ve.VARIABLE_LENGTH,30],["95",ve.VARIABLE_LENGTH,30],["96",ve.VARIABLE_LENGTH,30],["97",ve.VARIABLE_LENGTH,3],["98",ve.VARIABLE_LENGTH,30],["99",ve.VARIABLE_LENGTH,30]],ve.THREE_DIGIT_DATA_LENGTH=[["240",ve.VARIABLE_LENGTH,30],["241",ve.VARIABLE_LENGTH,30],["242",ve.VARIABLE_LENGTH,6],["250",ve.VARIABLE_LENGTH,30],["251",ve.VARIABLE_LENGTH,30],["253",ve.VARIABLE_LENGTH,17],["254",ve.VARIABLE_LENGTH,20],["400",ve.VARIABLE_LENGTH,30],["401",ve.VARIABLE_LENGTH,30],["402",17],["403",ve.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",ve.VARIABLE_LENGTH,20],["421",ve.VARIABLE_LENGTH,15],["422",3],["423",ve.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],ve.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",ve.VARIABLE_LENGTH,15],["391",ve.VARIABLE_LENGTH,18],["392",ve.VARIABLE_LENGTH,15],["393",ve.VARIABLE_LENGTH,18],["703",ve.VARIABLE_LENGTH,30]],ve.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",ve.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",ve.VARIABLE_LENGTH,20],["8003",ve.VARIABLE_LENGTH,30],["8004",ve.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",ve.VARIABLE_LENGTH,30],["8008",ve.VARIABLE_LENGTH,12],["8018",18],["8020",ve.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",ve.VARIABLE_LENGTH,70],["8200",ve.VARIABLE_LENGTH,70]];class vr{constructor(e){this.buffer=new fe,this.information=e}decodeAllCodes(e,n){let o=n,s=null;do{let a=this.decodeGeneralPurposeField(o,s),l=ve.parseFieldsInGeneralPurpose(a.getNewString());if(l!=null&&e.append(l),a.isRemaining()?s=""+a.getRemainingValue():s=null,o===a.getNewPosition())break;o=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 hn(this.information.getSize(),hn.FNC1,hn.FNC1):new hn(this.information.getSize(),a-1,hn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),o=(n-8)/11,s=(n-8)%11;return new hn(e+7,o,s)}extractNumericValueFromBitArray(e,n){return vr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,o){let s=0;for(let a=0;a<o;++a)e.get(n+a)&&(s|=1<<o-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let o=this.parseBlocks();return o!=null&&o.isRemaining()?new sr(this.current.getPosition(),this.buffer.toString(),o.getRemainingValue()):new sr(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let o=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()),!(o!==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 sr(this.current.getPosition(),this.buffer.toString()):n=new sr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new ir(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new sr(this.current.getPosition(),this.buffer.toString());return new ir(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new ir(!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 sr(this.current.getPosition(),this.buffer.toString());return new ir(!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 ir(!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 sr(this.current.getPosition(),this.buffer.toString());return new ir(!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 ir(!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 o=this.extractNumericValueFromBitArray(e,7);if(o>=64&&o<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 Jt(e+5,Jt.FNC1);if(n>=5&&n<15)return new Jt(e+5,"0"+(n-5));let o=this.extractNumericValueFromBitArray(e,7);if(o>=64&&o<90)return new Jt(e+7,""+(o+1));if(o>=90&&o<116)return new Jt(e+7,""+(o+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 L}return new Jt(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 o=this.extractNumericValueFromBitArray(e,6);return o>=16&&o<63}decodeAlphanumeric(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new Jt(e+5,Jt.FNC1);if(n>=5&&n<15)return new Jt(e+5,"0"+(n-5));let o=this.extractNumericValueFromBitArray(e,6);if(o>=32&&o<58)return new Jt(e+6,""+(o+33));let s;switch(o){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new St("Decoding invalid alphanumeric value: "+o)}return new Jt(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 Ho{constructor(e){this.information=e,this.generalDecoder=new vr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class Qt extends Ho{constructor(e){super(e)}encodeCompressedGtin(e,n){e.append("(01)");let o=e.length();e.append("9"),this.encodeCompressedGtinWithoutAI(e,n,o)}encodeCompressedGtinWithoutAI(e,n,o){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)}Qt.appendCheckDigit(e,o)}static appendCheckDigit(e,n){let o=0;for(let s=0;s<13;s++){let a=e.charAt(s+n).charCodeAt(0)-48;o+=(s&1)===0?3*a:a}o=10-o%10,o===10&&(o=0),e.append(o)}}Qt.GTIN_SIZE=40;class Cr extends Qt{constructor(e){super(e)}parseInformation(){let e=new fe;e.append("(01)");let n=e.length(),o=this.getGeneralDecoder().extractNumericValueFromBitArray(Cr.HEADER_SIZE,4);return e.append(o),this.encodeCompressedGtinWithoutAI(e,Cr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,Cr.HEADER_SIZE+44)}}Cr.HEADER_SIZE=4;class uo extends Ho{constructor(e){super(e)}parseInformation(){let e=new fe;return this.getGeneralDecoder().decodeAllCodes(e,uo.HEADER_SIZE)}}uo.HEADER_SIZE=5;class fo extends Qt{constructor(e){super(e)}encodeCompressedWeight(e,n,o){let s=this.getGeneralDecoder().extractNumericValueFromBitArray(n,o);this.addWeightCode(e,s);let a=this.checkWeight(s),l=1e5;for(let u=0;u<5;++u)a/l===0&&e.append("0"),l/=10;e.append(a)}}class Tn extends fo{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Tn.HEADER_SIZE+fo.GTIN_SIZE+Tn.WEIGHT_SIZE)throw new q;let e=new fe;return this.encodeCompressedGtin(e,Tn.HEADER_SIZE),this.encodeCompressedWeight(e,Tn.HEADER_SIZE+fo.GTIN_SIZE,Tn.WEIGHT_SIZE),e.toString()}}Tn.HEADER_SIZE=5,Tn.WEIGHT_SIZE=15;class Yu extends Tn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Ku extends Tn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class Nn extends Qt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Nn.HEADER_SIZE+Qt.GTIN_SIZE)throw new q;let e=new fe;this.encodeCompressedGtin(e,Nn.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Nn.HEADER_SIZE+Qt.GTIN_SIZE,Nn.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let o=this.getGeneralDecoder().decodeGeneralPurposeField(Nn.HEADER_SIZE+Qt.GTIN_SIZE+Nn.LAST_DIGIT_SIZE,null);return e.append(o.getNewString()),e.toString()}}Nn.HEADER_SIZE=8,Nn.LAST_DIGIT_SIZE=2;class Xt extends Qt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<Xt.HEADER_SIZE+Qt.GTIN_SIZE)throw new q;let e=new fe;this.encodeCompressedGtin(e,Xt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(Xt.HEADER_SIZE+Qt.GTIN_SIZE,Xt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let o=this.getGeneralDecoder().extractNumericValueFromBitArray(Xt.HEADER_SIZE+Qt.GTIN_SIZE+Xt.LAST_DIGIT_SIZE,Xt.FIRST_THREE_DIGITS_SIZE);o/100==0&&e.append("0"),o/10==0&&e.append("0"),e.append(o);let s=this.getGeneralDecoder().decodeGeneralPurposeField(Xt.HEADER_SIZE+Qt.GTIN_SIZE+Xt.LAST_DIGIT_SIZE+Xt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}Xt.HEADER_SIZE=8,Xt.LAST_DIGIT_SIZE=2,Xt.FIRST_THREE_DIGITS_SIZE=10;class Ct extends fo{constructor(e,n,o){super(e),this.dateCode=o,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=Ct.HEADER_SIZE+Ct.GTIN_SIZE+Ct.WEIGHT_SIZE+Ct.DATE_SIZE)throw new q;let e=new fe;return this.encodeCompressedGtin(e,Ct.HEADER_SIZE),this.encodeCompressedWeight(e,Ct.HEADER_SIZE+Ct.GTIN_SIZE,Ct.WEIGHT_SIZE),this.encodeCompressedDate(e,Ct.HEADER_SIZE+Ct.GTIN_SIZE+Ct.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let o=this.getGeneralDecoder().extractNumericValueFromBitArray(n,Ct.DATE_SIZE);if(o==38400)return;e.append("("),e.append(this.dateCode),e.append(")");let s=o%32;o/=32;let a=o%12+1;o/=12;let l=o;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}}Ct.HEADER_SIZE=8,Ct.WEIGHT_SIZE=20,Ct.DATE_SIZE=16;function cs(C){try{if(C.get(1))return new Cr(C);if(!C.get(2))return new uo(C);switch(vr.extractNumericValueFromBitArray(C,1,4)){case 4:return new Yu(C);case 5:return new Ku(C)}switch(vr.extractNumericValueFromBitArray(C,1,5)){case 12:return new Nn(C);case 13:return new Xt(C)}switch(vr.extractNumericValueFromBitArray(C,1,7)){case 56:return new Ct(C,"310","11");case 57:return new Ct(C,"320","11");case 58:return new Ct(C,"310","13");case 59:return new Ct(C,"320","13");case 60:return new Ct(C,"310","15");case 61:return new Ct(C,"320","15");case 62:return new Ct(C,"310","17");case 63:return new Ct(C,"320","17")}}catch(e){throw console.log(e),new St("unknown decoder: "+C)}}class Hn{constructor(e,n,o,s){this.leftchar=e,this.rightchar=n,this.finderpattern=o,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 Hn?Hn.equalsOrNull(e.leftchar,n.leftchar)&&Hn.equalsOrNull(e.rightchar,n.rightchar)&&Hn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:Hn.equals(e,n)}hashCode(){return this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue()}}class Wo{constructor(e,n,o){this.pairs=e,this.rowNumber=n,this.wasReversed=o}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 Wo?this.checkEqualitity(e,n)&&e.wasReversed===n.wasReversed:!1}checkEqualitity(e,n){if(!e||!n)return;let o;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()&&(o=!0)})}),o}}class se extends Wt{constructor(e){super(...arguments),this.pairs=new Array(se.MAX_PAIRS),this.rows=new Array,this.startEnd=[2],this.verbose=e===!0}decodeRow(e,n,o){this.pairs.length=0,this.startFromEven=!1;try{return se.constructResult(this.decodeRow2pairs(e,n))}catch(s){this.verbose&&console.log(s)}return this.pairs.length=0,this.startFromEven=!0,se.constructResult(this.decodeRow2pairs(e,n))}reset(){this.pairs.length=0,this.rows.length=0}decodeRow2pairs(e,n){let o=!1;for(;!o;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof q){if(!this.pairs.length)throw new q;o=!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 q}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(o){this.verbose&&console.log(o)}return e&&(this.rows=this.rows.reverse()),n}checkRows(e,n){for(let o=n;o<this.rows.length;o++){let s=this.rows[o];this.pairs.length=0;for(let l of e)this.pairs.push(l.getPairs());if(this.pairs.push(s.getPairs()),!se.isValidSequence(this.pairs))continue;if(this.checkChecksum())return this.pairs;let a=new Array(e);a.push(s);try{return this.checkRows(a,o+1)}catch(l){this.verbose&&console.log(l)}}throw new q}static isValidSequence(e){for(let n of se.FINDER_PATTERN_SEQUENCES){if(e.length>n.length)continue;let o=!0;for(let s=0;s<e.length;s++)if(e[s].getFinderPattern().getValue()!=n[s]){o=!1;break}if(o)return!0}return!1}storeRow(e,n){let o=0,s=!1,a=!1;for(;o<this.rows.length;){let l=this.rows[o];if(l.getRowNumber()>e){a=l.isEquivalent(this.pairs);break}s=l.isEquivalent(this.pairs),o++}a||s||se.isPartialRow(this.pairs,this.rows)||(this.rows.push(o,new Wo(this.pairs,e,n)),this.removePartialRows(this.pairs,this.rows))}removePartialRows(e,n){for(let o of n)if(o.getPairs().length!==e.length){for(let s of o.getPairs())for(let a of e)if(Hn.equals(s,a))break}}static isPartialRow(e,n){for(let o of n){let s=!0;for(let a of e){let l=!1;for(let u of o.getPairs())if(a.equals(u)){l=!0;break}if(!l){s=!1;break}}if(s)return!0}return!1}getRows(){return this.rows}static constructResult(e){let n=Xu.buildBitArray(e),s=cs(n).parseInformation(),a=e[0].getFinderPattern().getResultPoints(),l=e[e.length-1].getFinderPattern().getResultPoints(),u=[a[0],a[1],l[0],l[1]];return new qe(s,null,null,u,ie.RSS_EXPANDED,null)}checkChecksum(){let e=this.pairs.get(0),n=e.getLeftChar(),o=e.getRightChar();if(o==null)return!1;let s=o.getChecksumPortion(),a=2;for(let u=1;u<this.pairs.size();++u){let h=this.pairs.get(u);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 o;return e.get(n)?(o=e.getNextUnset(n),o=e.getNextSet(o)):(o=e.getNextSet(n),o=e.getNextUnset(o)),o}retrieveNextPair(e,n,o){let s=n.length%2==0;this.startFromEven&&(s=!s);let a,l=!0,u=-1;do this.findNextPair(e,n,u),a=this.parseFoundFinderPattern(e,o,s),a==null?u=se.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 q;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new Hn(h,p,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,o){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;o>=0?l=o:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let u=n.length%2!=0;this.startFromEven&&(u=!u);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let p=0,y=l;for(let b=l;b<a;b++)if(e.get(b)!=h)s[p]++;else{if(p==3){if(u&&se.reverseCounters(s),se.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=b;return}u&&se.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 q}static reverseCounters(e){let n=e.length;for(let o=0;o<n/2;++o){let s=e[o];e[o]=e[n-o-1],e[n-o-1]=s}}parseFoundFinderPattern(e,n,o){let s,a,l;if(o){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 u=this.getDecodeFinderCounters();P.arraycopy(u,0,u,1,u.length-1),u[0]=s;let h;try{h=this.parseFinderValue(u,se.FINDER_PATTERNS)}catch{return null}return new co(h,[a,l],a,l,n)}decodeDataCharacter(e,n,o,s){let a=this.getDataCharacterCounters();for(let ft=0;ft<a.length;ft++)a[ft]=0;if(s)se.recordPatternInReverse(e,n.getStartEnd()[0],a);else{se.recordPattern(e,n.getStartEnd()[1],a);for(let ft=0,Ht=a.length-1;ft<Ht;ft++,Ht--){let an=a[ft];a[ft]=a[Ht],a[Ht]=an}}let l=17,u=Xe.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(u-h)/h>.3)throw new q;let p=this.getOddCounts(),y=this.getEvenCounts(),b=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let ft=0;ft<a.length;ft++){let Ht=1*a[ft]/u,an=Ht+.5;if(an<1){if(Ht<.3)throw new q;an=1}else if(an>8){if(Ht>8.7)throw new q;an=8}let Sr=ft/2;(ft&1)==0?(p[Sr]=an,b[Sr]=Ht-an):(y[Sr]=an,I[Sr]=Ht-an)}this.adjustOddEvenCounts(l);let R=4*n.getValue()+(o?0:2)+(s?0:1)-1,U=0,V=0;for(let ft=p.length-1;ft>=0;ft--){if(se.isNotA1left(n,o,s)){let Ht=se.WEIGHTS[R][2*ft];V+=p[ft]*Ht}U+=p[ft]}let H=0;for(let ft=y.length-1;ft>=0;ft--)if(se.isNotA1left(n,o,s)){let Ht=se.WEIGHTS[R][2*ft+1];H+=y[ft]*Ht}let Q=V+H;if((U&1)!=0||U>13||U<4)throw new q;let he=(13-U)/2,pe=se.SYMBOL_WIDEST[he],ce=9-pe,Ke=Sn.getRSSvalue(p,pe,!0),He=Sn.getRSSvalue(y,ce,!1),tn=se.EVEN_TOTAL_SUBSET[he],yn=se.GSUM[he],nn=Ke*tn+He+yn;return new _r(nn,Q)}static isNotA1left(e,n,o){return!(e.getValue()==0&&n&&o)}adjustOddEvenCounts(e){let n=Xe.sum(new Int32Array(this.getOddCounts())),o=Xe.sum(new Int32Array(this.getEvenCounts())),s=!1,a=!1;n>13?a=!0:n<4&&(s=!0);let l=!1,u=!1;o>13?u=!0:o<4&&(l=!0);let h=n+o-e,p=(n&1)==1,y=(o&1)==0;if(h==1)if(p){if(y)throw new q;a=!0}else{if(!y)throw new q;u=!0}else if(h==-1)if(p){if(y)throw new q;s=!0}else{if(!y)throw new q;l=!0}else if(h==0){if(p){if(!y)throw new q;n<o?(s=!0,u=!0):(a=!0,l=!0)}else if(y)throw new q}else throw new q;if(s){if(a)throw new q;se.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&se.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(u)throw new q;se.increment(this.getEvenCounts(),this.getOddRoundingErrors())}u&&se.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}se.SYMBOL_WIDEST=[7,5,4,3,1],se.EVEN_TOTAL_SUBSET=[4,20,52,104,204],se.GSUM=[0,348,1388,2948,3988],se.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])],se.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]],se.FINDER_PAT_A=0,se.FINDER_PAT_B=1,se.FINDER_PAT_C=2,se.FINDER_PAT_D=3,se.FINDER_PAT_E=4,se.FINDER_PAT_F=5,se.FINDER_PATTERN_SEQUENCES=[[se.FINDER_PAT_A,se.FINDER_PAT_A],[se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B],[se.FINDER_PAT_A,se.FINDER_PAT_C,se.FINDER_PAT_B,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_C],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_E,se.FINDER_PAT_B,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F],[se.FINDER_PAT_A,se.FINDER_PAT_A,se.FINDER_PAT_B,se.FINDER_PAT_B,se.FINDER_PAT_C,se.FINDER_PAT_D,se.FINDER_PAT_D,se.FINDER_PAT_E,se.FINDER_PAT_E,se.FINDER_PAT_F,se.FINDER_PAT_F]],se.MAX_PAIRS=11;class Ju extends _r{constructor(e,n,o){super(e,n),this.count=0,this.finderPattern=o}getFinderPattern(){return this.finderPattern}getCount(){return this.count}incrementCount(){this.count++}}class Tt extends Wt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,o){const s=this.decodePair(n,!1,e,o);Tt.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,o);Tt.addOrTally(this.possibleRightPairs,a),n.reverse();for(let l of this.possibleLeftPairs)if(l.getCount()>1){for(let u of this.possibleRightPairs)if(u.getCount()>1&&Tt.checkChecksum(l,u))return Tt.constructResult(l,u)}throw new q}static addOrTally(e,n){if(n==null)return;let o=!1;for(let s of e)if(s.getValue()===n.getValue()){s.incrementCount(),o=!0;break}o||e.push(n)}reset(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0}static constructResult(e,n){let o=4537077*e.getValue()+n.getValue(),s=new String(o).toString(),a=new fe;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 u=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new qe(a.toString(),null,0,[u[0],u[1],h[0],h[1]],ie.RSS_14,new Date().getTime())}static checkChecksum(e,n){let o=(e.getChecksumPortion()+16*n.getChecksumPortion())%79,s=9*e.getFinderPattern().getValue()+n.getFinderPattern().getValue();return s>72&&s--,s>8&&s--,o===s}decodePair(e,n,o,s){try{let a=this.findFinderPattern(e,n),l=this.parseFoundFinderPattern(e,o,n,a),u=s==null?null:s.get(B.NEED_RESULT_POINT_CALLBACK);if(u!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),u.foundPossibleResultPoint(new be(y,o))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Ju(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,o){let s=this.getDataCharacterCounters();for(let H=0;H<s.length;H++)s[H]=0;if(o)gt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{gt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let H=0,Q=s.length-1;H<Q;H++,Q--){let he=s[H];s[H]=s[Q],s[Q]=he}}let a=o?16:15,l=Xe.sum(new Int32Array(s))/a,u=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let H=0;H<s.length;H++){let Q=s[H]/l,he=Math.floor(Q+.5);he<1?he=1:he>8&&(he=8);let pe=Math.floor(H/2);(H&1)===0?(u[pe]=he,p[pe]=Q-he):(h[pe]=he,y[pe]=Q-he)}this.adjustOddEvenCounts(o,a);let b=0,I=0;for(let H=u.length-1;H>=0;H--)I*=9,I+=u[H],b+=u[H];let R=0,U=0;for(let H=h.length-1;H>=0;H--)R*=9,R+=h[H],U+=h[H];let V=I+3*R;if(o){if((b&1)!==0||b>12||b<4)throw new q;let H=(12-b)/2,Q=Tt.OUTSIDE_ODD_WIDEST[H],he=9-Q,pe=Sn.getRSSvalue(u,Q,!1),ce=Sn.getRSSvalue(h,he,!0),Ke=Tt.OUTSIDE_EVEN_TOTAL_SUBSET[H],He=Tt.OUTSIDE_GSUM[H];return new _r(pe*Ke+ce+He,V)}else{if((U&1)!==0||U>10||U<4)throw new q;let H=(10-U)/2,Q=Tt.INSIDE_ODD_WIDEST[H],he=9-Q,pe=Sn.getRSSvalue(u,Q,!0),ce=Sn.getRSSvalue(h,he,!1),Ke=Tt.INSIDE_ODD_TOTAL_SUBSET[H],He=Tt.INSIDE_GSUM[H];return new _r(ce*Ke+pe+He,V)}}findFinderPattern(e,n){let o=this.getDecodeFinderCounters();o[0]=0,o[1]=0,o[2]=0,o[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let u=0,h=l;for(let p=l;p<s;p++)if(e.get(p)!==a)o[u]++;else{if(u===3){if(Wt.isFinderPattern(o))return[h,p];h+=o[0]+o[1],o[0]=o[2],o[1]=o[3],o[2]=0,o[3]=0,u--}else u++;o[u]=1,a=!a}throw new q}parseFoundFinderPattern(e,n,o,s){let a=e.get(s[0]),l=s[0]-1;for(;l>=0&&a!==e.get(l);)l--;l++;const u=s[0]-l,h=this.getDecodeFinderCounters(),p=new Int32Array(h.length);P.arraycopy(h,0,p,1,h.length-1),p[0]=u;const y=this.parseFinderValue(p,Tt.FINDER_PATTERNS);let b=l,I=s[1];return o&&(b=e.getSize()-1-b,I=e.getSize()-1-I),new co(y,[l,s[1]],b,I,n)}adjustOddEvenCounts(e,n){let o=Xe.sum(new Int32Array(this.getOddCounts())),s=Xe.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,u=!1,h=!1;e?(o>12?l=!0:o<4&&(a=!0),s>12?h=!0:s<4&&(u=!0)):(o>11?l=!0:o<5&&(a=!0),s>10?h=!0:s<4&&(u=!0));let p=o+s-n,y=(o&1)===(e?1:0),b=(s&1)===1;if(p===1)if(y){if(b)throw new q;l=!0}else{if(!b)throw new q;h=!0}else if(p===-1)if(y){if(b)throw new q;a=!0}else{if(!b)throw new q;u=!0}else if(p===0){if(y){if(!b)throw new q;o<s?(a=!0,h=!0):(l=!0,u=!0)}else if(b)throw new q}else throw new q;if(a){if(l)throw new q;Wt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Wt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),u){if(h)throw new q;Wt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Wt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}Tt.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],Tt.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],Tt.OUTSIDE_GSUM=[0,161,961,2015,2715],Tt.INSIDE_GSUM=[0,336,1036,1516],Tt.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],Tt.INSIDE_ODD_WIDEST=[2,4,6,8],Tt.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 br extends gt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const o=e?e.get(B.POSSIBLE_FORMATS):null,s=e&&e.get(B.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;o?((o.includes(ie.EAN_13)||o.includes(ie.UPC_A)||o.includes(ie.EAN_8)||o.includes(ie.UPC_E))&&this.readers.push(new $o(e)),o.includes(ie.CODE_39)&&this.readers.push(new O(s)),o.includes(ie.CODE_128)&&this.readers.push(new ge),o.includes(ie.ITF)&&this.readers.push(new ne),o.includes(ie.RSS_14)&&this.readers.push(new Tt),o.includes(ie.RSS_EXPANDED)&&this.readers.push(new se(this.verbose))):(this.readers.push(new $o(e)),this.readers.push(new O),this.readers.push(new $o(e)),this.readers.push(new ge),this.readers.push(new ne),this.readers.push(new Tt),this.readers.push(new se(this.verbose)))}decodeRow(e,n,o){for(let s=0;s<this.readers.length;s++)try{return this.readers[s].decodeRow(e,n,o)}catch{}throw new q}reset(){this.readers.forEach(e=>e.reset())}}class Qu extends Ze{constructor(e=500,n){super(new br(n),e,n)}}class at{constructor(e,n,o){this.ecCodewords=e,this.ecBlocks=[n],o&&this.ecBlocks.push(o)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class ot{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Qe{constructor(e,n,o,s,a,l){this.versionNumber=e,this.symbolSizeRows=n,this.symbolSizeColumns=o,this.dataRegionSizeRows=s,this.dataRegionSizeColumns=a,this.ecBlocks=l;let u=0;const h=l.getECCodewords(),p=l.getECBlocks();for(let y of p)u+=y.getCount()*(y.getDataCodewords()+h);this.totalCodewords=u}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 L;for(let o of Qe.VERSIONS)if(o.symbolSizeRows===e&&o.symbolSizeColumns===n)return o;throw new L}toString(){return""+this.versionNumber}static buildVersions(){return[new Qe(1,10,10,8,8,new at(5,new ot(1,3))),new Qe(2,12,12,10,10,new at(7,new ot(1,5))),new Qe(3,14,14,12,12,new at(10,new ot(1,8))),new Qe(4,16,16,14,14,new at(12,new ot(1,12))),new Qe(5,18,18,16,16,new at(14,new ot(1,18))),new Qe(6,20,20,18,18,new at(18,new ot(1,22))),new Qe(7,22,22,20,20,new at(20,new ot(1,30))),new Qe(8,24,24,22,22,new at(24,new ot(1,36))),new Qe(9,26,26,24,24,new at(28,new ot(1,44))),new Qe(10,32,32,14,14,new at(36,new ot(1,62))),new Qe(11,36,36,16,16,new at(42,new ot(1,86))),new Qe(12,40,40,18,18,new at(48,new ot(1,114))),new Qe(13,44,44,20,20,new at(56,new ot(1,144))),new Qe(14,48,48,22,22,new at(68,new ot(1,174))),new Qe(15,52,52,24,24,new at(42,new ot(2,102))),new Qe(16,64,64,14,14,new at(56,new ot(2,140))),new Qe(17,72,72,16,16,new at(36,new ot(4,92))),new Qe(18,80,80,18,18,new at(48,new ot(4,114))),new Qe(19,88,88,20,20,new at(56,new ot(4,144))),new Qe(20,96,96,22,22,new at(68,new ot(4,174))),new Qe(21,104,104,24,24,new at(56,new ot(6,136))),new Qe(22,120,120,18,18,new at(68,new ot(6,175))),new Qe(23,132,132,20,20,new at(62,new ot(8,163))),new Qe(24,144,144,22,22,new at(62,new ot(8,156),new ot(2,155))),new Qe(25,8,18,6,16,new at(7,new ot(1,5))),new Qe(26,8,32,6,14,new at(11,new ot(1,10))),new Qe(27,12,26,10,24,new at(14,new ot(1,16))),new Qe(28,12,36,10,16,new at(18,new ot(1,22))),new Qe(29,16,36,14,16,new at(24,new ot(1,32))),new Qe(30,16,48,14,22,new at(28,new ot(1,49)))]}}Qe.VERSIONS=Qe.buildVersions();class Go{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new L;this.version=Go.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new te(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),o=e.getWidth();return Qe.getVersionForDimensions(n,o)}readCodewords(){const e=new Int8Array(this.version.getTotalCodewords());let n=0,o=4,s=0;const a=this.mappingBitMatrix.getHeight(),l=this.mappingBitMatrix.getWidth();let u=!1,h=!1,p=!1,y=!1;do if(o===a&&s===0&&!u)e[n++]=this.readCorner1(a,l)&255,o-=2,s+=2,u=!0;else if(o===a-2&&s===0&&(l&3)!==0&&!h)e[n++]=this.readCorner2(a,l)&255,o-=2,s+=2,h=!0;else if(o===a+4&&s===2&&(l&7)===0&&!p)e[n++]=this.readCorner3(a,l)&255,o-=2,s+=2,p=!0;else if(o===a-2&&s===0&&(l&7)===4&&!y)e[n++]=this.readCorner4(a,l)&255,o-=2,s+=2,y=!0;else{do o<a&&s>=0&&!this.readMappingMatrix.get(s,o)&&(e[n++]=this.readUtah(o,s,a,l)&255),o-=2,s+=2;while(o>=0&&s<l);o+=1,s+=3;do o>=0&&s<l&&!this.readMappingMatrix.get(s,o)&&(e[n++]=this.readUtah(o,s,a,l)&255),o+=2,s-=2;while(o<a&&s>=0);o+=3,s+=1}while(o<a||s<l);if(n!==this.version.getTotalCodewords())throw new L;return e}readModule(e,n,o,s){return e<0&&(e+=o,n+=4-(o+4&7)),n<0&&(n+=s,e+=4-(s+4&7)),this.readMappingMatrix.set(n,e),this.mappingBitMatrix.get(n,e)}readUtah(e,n,o,s){let a=0;return this.readModule(e-2,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e-2,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e-1,n,o,s)&&(a|=1),a<<=1,this.readModule(e,n-2,o,s)&&(a|=1),a<<=1,this.readModule(e,n-1,o,s)&&(a|=1),a<<=1,this.readModule(e,n,o,s)&&(a|=1),a}readCorner1(e,n){let o=0;return this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,1,e,n)&&(o|=1),o<<=1,this.readModule(e-1,2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(2,n-1,e,n)&&(o|=1),o<<=1,this.readModule(3,n-1,e,n)&&(o|=1),o}readCorner2(e,n){let o=0;return this.readModule(e-3,0,e,n)&&(o|=1),o<<=1,this.readModule(e-2,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(0,n-4,e,n)&&(o|=1),o<<=1,this.readModule(0,n-3,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o}readCorner3(e,n){let o=0;return this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(0,n-3,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-3,e,n)&&(o|=1),o<<=1,this.readModule(1,n-2,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o}readCorner4(e,n){let o=0;return this.readModule(e-3,0,e,n)&&(o|=1),o<<=1,this.readModule(e-2,0,e,n)&&(o|=1),o<<=1,this.readModule(e-1,0,e,n)&&(o|=1),o<<=1,this.readModule(0,n-2,e,n)&&(o|=1),o<<=1,this.readModule(0,n-1,e,n)&&(o|=1),o<<=1,this.readModule(1,n-1,e,n)&&(o|=1),o<<=1,this.readModule(2,n-1,e,n)&&(o|=1),o<<=1,this.readModule(3,n-1,e,n)&&(o|=1),o}extractDataRegion(e){const n=this.version.getSymbolSizeRows(),o=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,u=o/a|0,h=l*s,p=u*a,y=new te(p,h);for(let b=0;b<l;++b){const I=b*s;for(let R=0;R<u;++R){const U=R*a;for(let V=0;V<s;++V){const H=b*(s+2)+1+V,Q=I+V;for(let he=0;he<a;++he){const pe=R*(a+2)+1+he;if(e.get(pe,H)){const ce=U+he;y.set(ce,Q)}}}}}return y}}class qo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n){const o=n.getECBlocks();let s=0;const a=o.getECBlocks();for(let V of a)s+=V.getCount();const l=new Array(s);let u=0;for(let V of a)for(let H=0;H<V.getCount();H++){const Q=V.getDataCodewords(),he=o.getECCodewords()+Q;l[u++]=new qo(Q,new Uint8Array(he))}const p=l[0].codewords.length-o.getECCodewords(),y=p-1;let b=0;for(let V=0;V<y;V++)for(let H=0;H<u;H++)l[H].codewords[V]=e[b++];const I=n.getVersionNumber()===24,R=I?8:u;for(let V=0;V<R;V++)l[V].codewords[p-1]=e[b++];const U=l[0].codewords.length;for(let V=p;V<U;V++)for(let H=0;H<u;H++){const Q=I?(H+8)%u:H,he=I&&Q>7?V-1:V;l[Q].codewords[he]=e[b++]}if(b!==e.length)throw new A;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Xo{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,o=this.bitOffset,s=this.byteOffset;const a=this.bytes;if(o>0){const l=8-o,u=e<l?e:l,h=l-u,p=255>>8-u<<h;n=(a[s]&p)>>h,e-=u,o+=u,o===8&&(o=0,s++)}if(e>0){for(;e>=8;)n=n<<8|a[s]&255,s++,e-=8;if(e>0){const l=8-e,u=255>>l<<l;n=n<<e|(a[s]&u)>>l,o+=e}}return this.bitOffset=o,this.byteOffset=s,n}available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset}}var Pt;(function(C){C[C.PAD_ENCODE=0]="PAD_ENCODE",C[C.ASCII_ENCODE=1]="ASCII_ENCODE",C[C.C40_ENCODE=2]="C40_ENCODE",C[C.TEXT_ENCODE=3]="TEXT_ENCODE",C[C.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",C[C.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",C[C.BASE256_ENCODE=6]="BASE256_ENCODE"})(Pt||(Pt={}));class Wn{static decode(e){const n=new Xo(e),o=new fe,s=new fe,a=new Array;let l=Pt.ASCII_ENCODE;do if(l===Pt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,o,s);else{switch(l){case Pt.C40_ENCODE:this.decodeC40Segment(n,o);break;case Pt.TEXT_ENCODE:this.decodeTextSegment(n,o);break;case Pt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,o);break;case Pt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,o);break;case Pt.BASE256_ENCODE:this.decodeBase256Segment(n,o,a);break;default:throw new L}l=Pt.ASCII_ENCODE}while(l!==Pt.PAD_ENCODE&&n.available()>0);return s.length()>0&&o.append(s.toString()),new Pe(e,o.toString(),a.length===0?null:a,null)}static decodeAsciiSegment(e,n,o){let s=!1;do{let a=e.readBits(8);if(a===0)throw new L;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Pt.ASCII_ENCODE;if(a===129)return Pt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Pt.C40_ENCODE;case 231:return Pt.BASE256_ENCODE;case 232:n.append("");break;case 233:case 234:break;case 235:s=!0;break;case 236:n.append("[)>05"),o.insert(0,"");break;case 237:n.append("[)>06"),o.insert(0,"");break;case 238:return Pt.ANSIX12_ENCODE;case 239:return Pt.TEXT_ENCODE;case 240:return Pt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new L;break}}while(e.available()>0);return Pt.ASCII_ENCODE}static decodeC40Segment(e,n){let o=!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 u=0;u<3;u++){const h=s[u];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];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else throw new L;break;case 1:o?(n.append(String.fromCharCode(h+128)),o=!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];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:o=!0;break;default:throw new L}a=0;break;case 3:o?(n.append(String.fromCharCode(h+224)),o=!1):n.append(String.fromCharCode(h+96)),a=0;break;default:throw new L}}}while(e.available()>0)}static decodeTextSegment(e,n){let o=!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 u=0;u<3;u++){const h=s[u];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];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else throw new L;break;case 1:o?(n.append(String.fromCharCode(h+128)),o=!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];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p)}else switch(h){case 27:n.append("");break;case 30:o=!0;break;default:throw new L}a=0;break;case 3:if(h<this.TEXT_SHIFT3_SET_CHARS.length){const p=this.TEXT_SHIFT3_SET_CHARS[h];o?(n.append(String.fromCharCode(p.charCodeAt(0)+128)),o=!1):n.append(p),a=0}else throw new L;break;default:throw new L}}}while(e.available()>0)}static decodeAnsiX12Segment(e,n){const o=[];do{if(e.available()===8)return;const s=e.readBits(8);if(s===254)return;this.parseTwoBytes(s,e.readBits(8),o);for(let a=0;a<3;a++){const l=o[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 L;break}}}while(e.available()>0)}static parseTwoBytes(e,n,o){let s=(e<<8)+n-1,a=Math.floor(s/1600);o[0]=a,s-=a*1600,a=Math.floor(s/40),o[1]=a,o[2]=s-a*40}static decodeEdifactSegment(e,n){do{if(e.available()<=16)return;for(let o=0;o<4;o++){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,o){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 L;const u=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new L;u[h]=this.unrandomize255State(e.readBits(8),s++)}o.push(u);try{n.append(G.decode(u,me.ISO88591))}catch(h){throw new St("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const o=149*n%255+1,s=e-o;return s>=0?s:s+256}}Wn.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"],Wn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],Wn.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"],Wn.TEXT_SHIFT2_SET_CHARS=Wn.C40_SHIFT2_SET_CHARS,Wn.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 ed{constructor(){this.rsDecoder=new vt(Se.DATA_MATRIX_FIELD_256)}decode(e){const n=new Go(e),o=n.getVersion(),s=n.readCodewords(),a=qo.getDataBlocks(s,o);let l=0;for(let p of a)l+=p.getNumDataCodewords();const u=new Uint8Array(l),h=a.length;for(let p=0;p<h;p++){const y=a[p],b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)u[R*h+p]=b[R]}return Wn.decode(u)}correctErrors(e,n){const o=new Int32Array(e);try{this.rsDecoder.decode(o,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=o[s]}}class Rt{constructor(e){this.image=e,this.rectangleDetector=new qt(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 q;n=this.shiftToModuleCenter(n);const o=n[0],s=n[1],a=n[2],l=n[3];let u=this.transitionsBetween(o,l)+1,h=this.transitionsBetween(a,l)+1;(u&1)===1&&(u+=1),(h&1)===1&&(h+=1),4*u<7*h&&4*h<7*u&&(u=h=Math.max(u,h));let p=Rt.sampleGrid(this.image,o,s,a,l,u,h);return new Bn(p,[o,s,a,l])}static shiftPoint(e,n,o){let s=(n.getX()-e.getX())/(o+1),a=(n.getY()-e.getY())/(o+1);return new be(e.getX()+s,e.getY()+a)}static moveAway(e,n,o){let s=e.getX(),a=e.getY();return s<n?s-=1:s+=1,a<o?a-=1:a+=1,new be(s,a)}detectSolid1(e){let n=e[0],o=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,o),u=this.transitionsBetween(o,s),h=this.transitionsBetween(s,a),p=this.transitionsBetween(a,n),y=l,b=[a,n,o,s];return y>u&&(y=u,b[0]=n,b[1]=o,b[2]=s,b[3]=a),y>h&&(y=h,b[0]=o,b[1]=s,b[2]=a,b[3]=n),y>p&&(b[0]=s,b[1]=a,b[2]=n,b[3]=o),b}detectSolid2(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),u=Rt.shiftPoint(o,s,(l+1)*4),h=Rt.shiftPoint(s,o,(l+1)*4),p=this.transitionsBetween(u,n),y=this.transitionsBetween(h,a);return p<y?(e[0]=n,e[1]=o,e[2]=s,e[3]=a):(e[0]=o,e[1]=s,e[2]=a,e[3]=n),e}correctTopRight(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),u=this.transitionsBetween(o,a),h=Rt.shiftPoint(n,o,(u+1)*4),p=Rt.shiftPoint(s,o,(l+1)*4);l=this.transitionsBetween(h,a),u=this.transitionsBetween(p,a);let y=new be(a.getX()+(s.getX()-o.getX())/(l+1),a.getY()+(s.getY()-o.getY())/(l+1)),b=new be(a.getX()+(n.getX()-o.getX())/(u+1),a.getY()+(n.getY()-o.getY())/(u+1));if(!this.isValid(y))return this.isValid(b)?b:null;if(!this.isValid(b))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),R=this.transitionsBetween(h,b)+this.transitionsBetween(p,b);return I>R?y:b}shiftToModuleCenter(e){let n=e[0],o=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,u=this.transitionsBetween(s,a)+1,h=Rt.shiftPoint(n,o,u*4),p=Rt.shiftPoint(s,o,l*4);l=this.transitionsBetween(h,a)+1,u=this.transitionsBetween(p,a)+1,(l&1)===1&&(l+=1),(u&1)===1&&(u+=1);let y=(n.getX()+o.getX()+s.getX()+a.getX())/4,b=(n.getY()+o.getY()+s.getY()+a.getY())/4;n=Rt.moveAway(n,y,b),o=Rt.moveAway(o,y,b),s=Rt.moveAway(s,y,b),a=Rt.moveAway(a,y,b);let I,R;return h=Rt.shiftPoint(n,o,u*4),h=Rt.shiftPoint(h,a,l*4),I=Rt.shiftPoint(o,n,u*4),I=Rt.shiftPoint(I,s,l*4),p=Rt.shiftPoint(s,a,u*4),p=Rt.shiftPoint(p,o,l*4),R=Rt.shiftPoint(a,s,u*4),R=Rt.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,o,s,a,l,u){return sn.getInstance().sampleGrid(e,l,u,.5,.5,l-.5,.5,l-.5,u-.5,.5,u-.5,n.getX(),n.getY(),a.getX(),a.getY(),s.getX(),s.getY(),o.getX(),o.getY())}transitionsBetween(e,n){let o=Math.trunc(e.getX()),s=Math.trunc(e.getY()),a=Math.trunc(n.getX()),l=Math.trunc(n.getY()),u=Math.abs(l-s)>Math.abs(a-o);if(u){let V=o;o=s,s=V,V=a,a=l,l=V}let h=Math.abs(a-o),p=Math.abs(l-s),y=-h/2,b=s<l?1:-1,I=o<a?1:-1,R=0,U=this.image.get(u?s:o,u?o:s);for(let V=o,H=s;V!==a;V+=I){let Q=this.image.get(u?H:V,u?V:H);if(Q!==U&&(R++,U=Q),y+=p,y>0){if(H===l)break;H+=b,y-=h}}return R}}class Gn{constructor(){this.decoder=new ed}decode(e,n=null){let o,s;if(n!=null&&n.has(B.PURE_BARCODE)){const p=Gn.extractPureBits(e.getBlackMatrix());o=this.decoder.decode(p),s=Gn.NO_POINTS}else{const p=new Rt(e.getBlackMatrix()).detect();o=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=o.getRawBytes(),l=new qe(o.getText(),a,8*a.length,s,ie.DATA_MATRIX,P.currentTimeMillis()),u=o.getByteSegments();u!=null&&l.putMetadata(_e.BYTE_SEGMENTS,u);const h=o.getECLevel();return h!=null&&l.putMetadata(_e.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),o=e.getBottomRightOnBit();if(n==null||o==null)throw new q;const s=this.moduleSize(n,e);let a=n[1];const l=o[1];let u=n[0];const p=(o[0]-u+1)/s,y=(l-a+1)/s;if(p<=0||y<=0)throw new q;const b=s/2;a+=b,u+=b;const I=new te(p,y);for(let R=0;R<y;R++){const U=a+R*s;for(let V=0;V<p;V++)e.get(u+V*s,U)&&I.set(V,R)}return I}static moduleSize(e,n){const o=n.getWidth();let s=e[0];const a=e[1];for(;s<o&&n.get(s,a);)s++;if(s===o)throw new q;const l=s-e[0];if(l===0)throw new q;return l}}Gn.NO_POINTS=[];class td extends Ze{constructor(e=500){super(new Gn,e)}}var Ar;(function(C){C[C.L=0]="L",C[C.M=1]="M",C[C.Q=2]="Q",C[C.H=3]="H"})(Ar||(Ar={}));class pt{constructor(e,n,o){this.value=e,this.stringValue=n,this.bits=o,pt.FOR_BITS.set(o,this),pt.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return pt.L;case"M":return pt.M;case"Q":return pt.Q;case"H":return pt.H;default:throw new E(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof pt))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=pt.FOR_BITS.size)throw new A;return pt.FOR_BITS.get(e)}}pt.FOR_BITS=new Map,pt.FOR_VALUE=new Map,pt.L=new pt(Ar.L,"L",1),pt.M=new pt(Ar.M,"M",0),pt.Q=new pt(Ar.Q,"Q",3),pt.H=new pt(Ar.H,"H",2);class Gt{constructor(e){this.errorCorrectionLevel=pt.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return F.bitCount(e^n)}static decodeFormatInformation(e,n){const o=Gt.doDecodeFormatInformation(e,n);return o!==null?o:Gt.doDecodeFormatInformation(e^Gt.FORMAT_INFO_MASK_QR,n^Gt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let o=Number.MAX_SAFE_INTEGER,s=0;for(const a of Gt.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new Gt(a[1]);let u=Gt.numBitsDiffering(e,l);u<o&&(s=a[1],o=u),e!==n&&(u=Gt.numBitsDiffering(n,l),u<o&&(s=a[1],o=u))}return o<=3?new Gt(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof Gt))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}Gt.FORMAT_INFO_MASK_QR=21522,Gt.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 X{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const o of n)e+=o.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class k{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ne{constructor(e,n,...o){this.versionNumber=e,this.alignmentPatternCenters=n,this.ecBlocks=o;let s=0;const a=o[0].getECCodewordsPerBlock(),l=o[0].getECBlocks();for(const u of l)s+=u.getCount()*(u.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 L;try{return this.getVersionForNumber((e-17)/4)}catch{throw new L}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return Ne.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,o=0;for(let s=0;s<Ne.VERSION_DECODE_INFO.length;s++){const a=Ne.VERSION_DECODE_INFO[s];if(a===e)return Ne.getVersionForNumber(s+7);const l=Gt.numBitsDiffering(e,a);l<n&&(o=s+7,n=l)}return n<=3?Ne.getVersionForNumber(o):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new te(e);n.setRegion(0,0,9,9),n.setRegion(e-8,0,8,9),n.setRegion(0,e-8,9,8);const o=this.alignmentPatternCenters.length;for(let s=0;s<o;s++){const a=this.alignmentPatternCenters[s]-2;for(let l=0;l<o;l++)s===0&&(l===0||l===o-1)||s===o-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}}Ne.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]),Ne.VERSIONS=[new Ne(1,new Int32Array(0),new X(7,new k(1,19)),new X(10,new k(1,16)),new X(13,new k(1,13)),new X(17,new k(1,9))),new Ne(2,Int32Array.from([6,18]),new X(10,new k(1,34)),new X(16,new k(1,28)),new X(22,new k(1,22)),new X(28,new k(1,16))),new Ne(3,Int32Array.from([6,22]),new X(15,new k(1,55)),new X(26,new k(1,44)),new X(18,new k(2,17)),new X(22,new k(2,13))),new Ne(4,Int32Array.from([6,26]),new X(20,new k(1,80)),new X(18,new k(2,32)),new X(26,new k(2,24)),new X(16,new k(4,9))),new Ne(5,Int32Array.from([6,30]),new X(26,new k(1,108)),new X(24,new k(2,43)),new X(18,new k(2,15),new k(2,16)),new X(22,new k(2,11),new k(2,12))),new Ne(6,Int32Array.from([6,34]),new X(18,new k(2,68)),new X(16,new k(4,27)),new X(24,new k(4,19)),new X(28,new k(4,15))),new Ne(7,Int32Array.from([6,22,38]),new X(20,new k(2,78)),new X(18,new k(4,31)),new X(18,new k(2,14),new k(4,15)),new X(26,new k(4,13),new k(1,14))),new Ne(8,Int32Array.from([6,24,42]),new X(24,new k(2,97)),new X(22,new k(2,38),new k(2,39)),new X(22,new k(4,18),new k(2,19)),new X(26,new k(4,14),new k(2,15))),new Ne(9,Int32Array.from([6,26,46]),new X(30,new k(2,116)),new X(22,new k(3,36),new k(2,37)),new X(20,new k(4,16),new k(4,17)),new X(24,new k(4,12),new k(4,13))),new Ne(10,Int32Array.from([6,28,50]),new X(18,new k(2,68),new k(2,69)),new X(26,new k(4,43),new k(1,44)),new X(24,new k(6,19),new k(2,20)),new X(28,new k(6,15),new k(2,16))),new Ne(11,Int32Array.from([6,30,54]),new X(20,new k(4,81)),new X(30,new k(1,50),new k(4,51)),new X(28,new k(4,22),new k(4,23)),new X(24,new k(3,12),new k(8,13))),new Ne(12,Int32Array.from([6,32,58]),new X(24,new k(2,92),new k(2,93)),new X(22,new k(6,36),new k(2,37)),new X(26,new k(4,20),new k(6,21)),new X(28,new k(7,14),new k(4,15))),new Ne(13,Int32Array.from([6,34,62]),new X(26,new k(4,107)),new X(22,new k(8,37),new k(1,38)),new X(24,new k(8,20),new k(4,21)),new X(22,new k(12,11),new k(4,12))),new Ne(14,Int32Array.from([6,26,46,66]),new X(30,new k(3,115),new k(1,116)),new X(24,new k(4,40),new k(5,41)),new X(20,new k(11,16),new k(5,17)),new X(24,new k(11,12),new k(5,13))),new Ne(15,Int32Array.from([6,26,48,70]),new X(22,new k(5,87),new k(1,88)),new X(24,new k(5,41),new k(5,42)),new X(30,new k(5,24),new k(7,25)),new X(24,new k(11,12),new k(7,13))),new Ne(16,Int32Array.from([6,26,50,74]),new X(24,new k(5,98),new k(1,99)),new X(28,new k(7,45),new k(3,46)),new X(24,new k(15,19),new k(2,20)),new X(30,new k(3,15),new k(13,16))),new Ne(17,Int32Array.from([6,30,54,78]),new X(28,new k(1,107),new k(5,108)),new X(28,new k(10,46),new k(1,47)),new X(28,new k(1,22),new k(15,23)),new X(28,new k(2,14),new k(17,15))),new Ne(18,Int32Array.from([6,30,56,82]),new X(30,new k(5,120),new k(1,121)),new X(26,new k(9,43),new k(4,44)),new X(28,new k(17,22),new k(1,23)),new X(28,new k(2,14),new k(19,15))),new Ne(19,Int32Array.from([6,30,58,86]),new X(28,new k(3,113),new k(4,114)),new X(26,new k(3,44),new k(11,45)),new X(26,new k(17,21),new k(4,22)),new X(26,new k(9,13),new k(16,14))),new Ne(20,Int32Array.from([6,34,62,90]),new X(28,new k(3,107),new k(5,108)),new X(26,new k(3,41),new k(13,42)),new X(30,new k(15,24),new k(5,25)),new X(28,new k(15,15),new k(10,16))),new Ne(21,Int32Array.from([6,28,50,72,94]),new X(28,new k(4,116),new k(4,117)),new X(26,new k(17,42)),new X(28,new k(17,22),new k(6,23)),new X(30,new k(19,16),new k(6,17))),new Ne(22,Int32Array.from([6,26,50,74,98]),new X(28,new k(2,111),new k(7,112)),new X(28,new k(17,46)),new X(30,new k(7,24),new k(16,25)),new X(24,new k(34,13))),new Ne(23,Int32Array.from([6,30,54,78,102]),new X(30,new k(4,121),new k(5,122)),new X(28,new k(4,47),new k(14,48)),new X(30,new k(11,24),new k(14,25)),new X(30,new k(16,15),new k(14,16))),new Ne(24,Int32Array.from([6,28,54,80,106]),new X(30,new k(6,117),new k(4,118)),new X(28,new k(6,45),new k(14,46)),new X(30,new k(11,24),new k(16,25)),new X(30,new k(30,16),new k(2,17))),new Ne(25,Int32Array.from([6,32,58,84,110]),new X(26,new k(8,106),new k(4,107)),new X(28,new k(8,47),new k(13,48)),new X(30,new k(7,24),new k(22,25)),new X(30,new k(22,15),new k(13,16))),new Ne(26,Int32Array.from([6,30,58,86,114]),new X(28,new k(10,114),new k(2,115)),new X(28,new k(19,46),new k(4,47)),new X(28,new k(28,22),new k(6,23)),new X(30,new k(33,16),new k(4,17))),new Ne(27,Int32Array.from([6,34,62,90,118]),new X(30,new k(8,122),new k(4,123)),new X(28,new k(22,45),new k(3,46)),new X(30,new k(8,23),new k(26,24)),new X(30,new k(12,15),new k(28,16))),new Ne(28,Int32Array.from([6,26,50,74,98,122]),new X(30,new k(3,117),new k(10,118)),new X(28,new k(3,45),new k(23,46)),new X(30,new k(4,24),new k(31,25)),new X(30,new k(11,15),new k(31,16))),new Ne(29,Int32Array.from([6,30,54,78,102,126]),new X(30,new k(7,116),new k(7,117)),new X(28,new k(21,45),new k(7,46)),new X(30,new k(1,23),new k(37,24)),new X(30,new k(19,15),new k(26,16))),new Ne(30,Int32Array.from([6,26,52,78,104,130]),new X(30,new k(5,115),new k(10,116)),new X(28,new k(19,47),new k(10,48)),new X(30,new k(15,24),new k(25,25)),new X(30,new k(23,15),new k(25,16))),new Ne(31,Int32Array.from([6,30,56,82,108,134]),new X(30,new k(13,115),new k(3,116)),new X(28,new k(2,46),new k(29,47)),new X(30,new k(42,24),new k(1,25)),new X(30,new k(23,15),new k(28,16))),new Ne(32,Int32Array.from([6,34,60,86,112,138]),new X(30,new k(17,115)),new X(28,new k(10,46),new k(23,47)),new X(30,new k(10,24),new k(35,25)),new X(30,new k(19,15),new k(35,16))),new Ne(33,Int32Array.from([6,30,58,86,114,142]),new X(30,new k(17,115),new k(1,116)),new X(28,new k(14,46),new k(21,47)),new X(30,new k(29,24),new k(19,25)),new X(30,new k(11,15),new k(46,16))),new Ne(34,Int32Array.from([6,34,62,90,118,146]),new X(30,new k(13,115),new k(6,116)),new X(28,new k(14,46),new k(23,47)),new X(30,new k(44,24),new k(7,25)),new X(30,new k(59,16),new k(1,17))),new Ne(35,Int32Array.from([6,30,54,78,102,126,150]),new X(30,new k(12,121),new k(7,122)),new X(28,new k(12,47),new k(26,48)),new X(30,new k(39,24),new k(14,25)),new X(30,new k(22,15),new k(41,16))),new Ne(36,Int32Array.from([6,24,50,76,102,128,154]),new X(30,new k(6,121),new k(14,122)),new X(28,new k(6,47),new k(34,48)),new X(30,new k(46,24),new k(10,25)),new X(30,new k(2,15),new k(64,16))),new Ne(37,Int32Array.from([6,28,54,80,106,132,158]),new X(30,new k(17,122),new k(4,123)),new X(28,new k(29,46),new k(14,47)),new X(30,new k(49,24),new k(10,25)),new X(30,new k(24,15),new k(46,16))),new Ne(38,Int32Array.from([6,32,58,84,110,136,162]),new X(30,new k(4,122),new k(18,123)),new X(28,new k(13,46),new k(32,47)),new X(30,new k(48,24),new k(14,25)),new X(30,new k(42,15),new k(32,16))),new Ne(39,Int32Array.from([6,26,54,82,110,138,166]),new X(30,new k(20,117),new k(4,118)),new X(28,new k(40,47),new k(7,48)),new X(30,new k(43,24),new k(22,25)),new X(30,new k(10,15),new k(67,16))),new Ne(40,Int32Array.from([6,30,58,86,114,142,170]),new X(30,new k(19,118),new k(6,119)),new X(28,new k(18,47),new k(31,48)),new X(30,new k(34,24),new k(34,25)),new X(30,new k(20,15),new k(61,16)))];var Ut;(function(C){C[C.DATA_MASK_000=0]="DATA_MASK_000",C[C.DATA_MASK_001=1]="DATA_MASK_001",C[C.DATA_MASK_010=2]="DATA_MASK_010",C[C.DATA_MASK_011=3]="DATA_MASK_011",C[C.DATA_MASK_100=4]="DATA_MASK_100",C[C.DATA_MASK_101=5]="DATA_MASK_101",C[C.DATA_MASK_110=6]="DATA_MASK_110",C[C.DATA_MASK_111=7]="DATA_MASK_111"})(Ut||(Ut={}));class pn{constructor(e,n){this.value=e,this.isMasked=n}unmaskBitMatrix(e,n){for(let o=0;o<n;o++)for(let s=0;s<n;s++)this.isMasked(o,s)&&e.flip(s,o)}}pn.values=new Map([[Ut.DATA_MASK_000,new pn(Ut.DATA_MASK_000,(C,e)=>(C+e&1)===0)],[Ut.DATA_MASK_001,new pn(Ut.DATA_MASK_001,(C,e)=>(C&1)===0)],[Ut.DATA_MASK_010,new pn(Ut.DATA_MASK_010,(C,e)=>e%3===0)],[Ut.DATA_MASK_011,new pn(Ut.DATA_MASK_011,(C,e)=>(C+e)%3===0)],[Ut.DATA_MASK_100,new pn(Ut.DATA_MASK_100,(C,e)=>(Math.floor(C/2)+Math.floor(e/3)&1)===0)],[Ut.DATA_MASK_101,new pn(Ut.DATA_MASK_101,(C,e)=>C*e%6===0)],[Ut.DATA_MASK_110,new pn(Ut.DATA_MASK_110,(C,e)=>C*e%6<3)],[Ut.DATA_MASK_111,new pn(Ut.DATA_MASK_111,(C,e)=>(C+e+C*e%3&1)===0)]]);class nd{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new L;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 o=0;const s=n-7;for(let a=n-1;a>=s;a--)o=this.copyBit(8,a,o);for(let a=n-8;a<n;a++)o=this.copyBit(a,8,o);if(this.parsedFormatInfo=Gt.decodeFormatInformation(e,o),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new L}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 Ne.getVersionForNumber(n);let o=0;const s=e-11;for(let l=5;l>=0;l--)for(let u=e-9;u>=s;u--)o=this.copyBit(u,l,o);let a=Ne.decodeVersionInformation(o);if(a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;o=0;for(let l=5;l>=0;l--)for(let u=e-9;u>=s;u--)o=this.copyBit(l,u,o);if(a=Ne.decodeVersionInformation(o),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new L}copyBit(e,n,o){return(this.isMirror?this.bitMatrix.get(n,e):this.bitMatrix.get(e,n))?o<<1|1:o<<1}readCodewords(){const e=this.readFormatInformation(),n=this.readVersion(),o=pn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();o.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const u=new Uint8Array(n.getTotalCodewords());let h=0,p=0,y=0;for(let b=s-1;b>0;b-=2){b===6&&b--;for(let I=0;I<s;I++){const R=l?s-1-I:I;for(let U=0;U<2;U++)a.get(b-U,R)||(y++,p<<=1,this.bitMatrix.get(b-U,R)&&(p|=1),y===8&&(u[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new L;return u}remask(){if(this.parsedFormatInfo===null)return;const e=pn.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,o=e.getWidth();n<o;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 Yo{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,o){if(e.length!==n.getTotalCodewords())throw new A;const s=n.getECBlocksForLevel(o);let a=0;const l=s.getECBlocks();for(const U of l)a+=U.getCount();const u=new Array(a);let h=0;for(const U of l)for(let V=0;V<U.getCount();V++){const H=U.getDataCodewords(),Q=s.getECCodewordsPerBlock()+H;u[h++]=new Yo(H,new Uint8Array(Q))}const p=u[0].codewords.length;let y=u.length-1;for(;y>=0&&u[y].codewords.length!==p;)y--;y++;const b=p-s.getECCodewordsPerBlock();let I=0;for(let U=0;U<b;U++)for(let V=0;V<h;V++)u[V].codewords[U]=e[I++];for(let U=y;U<h;U++)u[U].codewords[b]=e[I++];const R=u[0].codewords.length;for(let U=b;U<R;U++)for(let V=0;V<h;V++){const H=V<y?U:U+1;u[V].codewords[H]=e[I++]}return u}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var mn;(function(C){C[C.TERMINATOR=0]="TERMINATOR",C[C.NUMERIC=1]="NUMERIC",C[C.ALPHANUMERIC=2]="ALPHANUMERIC",C[C.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",C[C.BYTE=4]="BYTE",C[C.ECI=5]="ECI",C[C.KANJI=6]="KANJI",C[C.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",C[C.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",C[C.HANZI=9]="HANZI"})(mn||(mn={}));class Re{constructor(e,n,o,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=o,this.bits=s,Re.FOR_BITS.set(s,this),Re.FOR_VALUE.set(e,this)}static forBits(e){const n=Re.FOR_BITS.get(e);if(n===void 0)throw new A;return n}getCharacterCountBits(e){const n=e.getVersionNumber();let o;return n<=9?o=0:n<=26?o=1:o=2,this.characterCountBitsForVersions[o]}getValue(){return this.value}getBits(){return this.bits}equals(e){if(!(e instanceof Re))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Re.FOR_BITS=new Map,Re.FOR_VALUE=new Map,Re.TERMINATOR=new Re(mn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Re.NUMERIC=new Re(mn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Re.ALPHANUMERIC=new Re(mn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Re.STRUCTURED_APPEND=new Re(mn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Re.BYTE=new Re(mn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Re.ECI=new Re(mn.ECI,"ECI",Int32Array.from([0,0,0]),7),Re.KANJI=new Re(mn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Re.FNC1_FIRST_POSITION=new Re(mn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Re.FNC1_SECOND_POSITION=new Re(mn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Re.HANZI=new Re(mn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class Et{static decode(e,n,o,s){const a=new Xo(e);let l=new fe;const u=new Array;let h=-1,p=-1;try{let y=null,b=!1,I;do{if(a.available()<4)I=Re.TERMINATOR;else{const R=a.readBits(4);I=Re.forBits(R)}switch(I){case Re.TERMINATOR:break;case Re.FNC1_FIRST_POSITION:case Re.FNC1_SECOND_POSITION:b=!0;break;case Re.STRUCTURED_APPEND:if(a.available()<16)throw new L;h=a.readBits(8),p=a.readBits(8);break;case Re.ECI:const R=Et.parseECIValue(a);if(y=z.getCharacterSetECIByValue(R),y===null)throw new L;break;case Re.HANZI:const U=a.readBits(4),V=a.readBits(I.getCharacterCountBits(n));U===Et.GB2312_SUBSET&&Et.decodeHanziSegment(a,l,V);break;default:const H=a.readBits(I.getCharacterCountBits(n));switch(I){case Re.NUMERIC:Et.decodeNumericSegment(a,l,H);break;case Re.ALPHANUMERIC:Et.decodeAlphanumericSegment(a,l,H,b);break;case Re.BYTE:Et.decodeByteSegment(a,l,H,y,u,s);break;case Re.KANJI:Et.decodeKanjiSegment(a,l,H);break;default:throw new L}break}}while(I!==Re.TERMINATOR)}catch{throw new L}return new Pe(e,l.toString(),u.length===0?null:u,o===null?null:o.toString(),h,p)}static decodeHanziSegment(e,n,o){if(o*13>e.available())throw new L;const s=new Uint8Array(2*o);let a=0;for(;o>0;){const l=e.readBits(13);let u=l/96<<8&4294967295|l%96;u<959?u+=41377:u+=42657,s[a]=u>>8&255,s[a+1]=u&255,a+=2,o--}try{n.append(G.decode(s,me.GB2312))}catch(l){throw new L(l)}}static decodeKanjiSegment(e,n,o){if(o*13>e.available())throw new L;const s=new Uint8Array(2*o);let a=0;for(;o>0;){const l=e.readBits(13);let u=l/192<<8&4294967295|l%192;u<7936?u+=33088:u+=49472,s[a]=u>>8,s[a+1]=u,a+=2,o--}try{n.append(G.decode(s,me.SHIFT_JIS))}catch(l){throw new L(l)}}static decodeByteSegment(e,n,o,s,a,l){if(8*o>e.available())throw new L;const u=new Uint8Array(o);for(let p=0;p<o;p++)u[p]=e.readBits(8);let h;s===null?h=me.guessEncoding(u,l):h=s.getName();try{n.append(G.decode(u,h))}catch(p){throw new L(p)}a.push(u)}static toAlphaNumericChar(e){if(e>=Et.ALPHANUMERIC_CHARS.length)throw new L;return Et.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,o,s){const a=n.length();for(;o>1;){if(e.available()<11)throw new L;const l=e.readBits(11);n.append(Et.toAlphaNumericChar(Math.floor(l/45))),n.append(Et.toAlphaNumericChar(l%45)),o-=2}if(o===1){if(e.available()<6)throw new L;n.append(Et.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,o){for(;o>=3;){if(e.available()<10)throw new L;const s=e.readBits(10);if(s>=1e3)throw new L;n.append(Et.toAlphaNumericChar(Math.floor(s/100))),n.append(Et.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(Et.toAlphaNumericChar(s%10)),o-=3}if(o===2){if(e.available()<7)throw new L;const s=e.readBits(7);if(s>=100)throw new L;n.append(Et.toAlphaNumericChar(Math.floor(s/10))),n.append(Et.toAlphaNumericChar(s%10))}else if(o===1){if(e.available()<4)throw new L;const s=e.readBits(4);if(s>=10)throw new L;n.append(Et.toAlphaNumericChar(s))}}static parseECIValue(e){const n=e.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){const o=e.readBits(8);return(n&63)<<8&4294967295|o}if((n&224)===192){const o=e.readBits(16);return(n&31)<<16&4294967295|o}throw new L}}Et.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",Et.GB2312_SUBSET=1;class us{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 rd{constructor(){this.rsDecoder=new vt(Se.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(te.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const o=new nd(e);let s=null;try{return this.decodeBitMatrixParser(o,n)}catch(a){s=a}try{o.remask(),o.setMirror(!0),o.readVersion(),o.readFormatInformation(),o.mirror();const a=this.decodeBitMatrixParser(o,n);return a.setOther(new us(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const o=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=Yo.getDataBlocks(a,o,s);let u=0;for(const y of l)u+=y.getNumDataCodewords();const h=new Uint8Array(u);let p=0;for(const y of l){const b=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(b,I);for(let R=0;R<I;R++)h[p++]=b[R]}return Et.decode(h,o,s,n)}correctErrors(e,n){const o=new Int32Array(e);try{this.rsDecoder.decode(o,e.length-n)}catch{throw new T}for(let s=0;s<n;s++)e[s]=o[s]}}class Ko extends be{constructor(e,n,o){super(e,n),this.estimatedModuleSize=o}aboutEquals(e,n,o){if(Math.abs(n-this.getY())<=e&&Math.abs(o-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,o){const s=(this.getX()+n)/2,a=(this.getY()+e)/2,l=(this.estimatedModuleSize+o)/2;return new Ko(s,a,l)}}class ho{constructor(e,n,o,s,a,l,u){this.image=e,this.startX=n,this.startY=o,this.width=s,this.height=a,this.moduleSize=l,this.resultPointCallback=u,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}find(){const e=this.startX,n=this.height,o=this.width,s=e+o,a=this.startY+n/2,l=new Int32Array(3),u=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&&!u.get(y,p);)y++;let b=0;for(;y<s;){if(u.get(y,p))if(b===1)l[1]++;else if(b===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,b=1}else l[++b]++;else b===1&&b++,l[b]++;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 q}static centerFromEnd(e,n){return n-e[2]-e[1]/2}foundPatternCross(e){const n=this.moduleSize,o=n/2;for(let s=0;s<3;s++)if(Math.abs(n-e[s])>=o)return!1;return!0}crossCheckVertical(e,n,o,s){const a=this.image,l=a.getHeight(),u=this.crossCheckStateCount;u[0]=0,u[1]=0,u[2]=0;let h=e;for(;h>=0&&a.get(n,h)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&!a.get(n,h)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(n,h)&&u[1]<=o;)u[1]++,h++;if(h===l||u[1]>o)return NaN;for(;h<l&&!a.get(n,h)&&u[2]<=o;)u[2]++,h++;if(u[2]>o)return NaN;const p=u[0]+u[1]+u[2];return 5*Math.abs(p-s)>=2*s?NaN:this.foundPatternCross(u)?ho.centerFromEnd(u,h):NaN}handlePossibleCenter(e,n,o){const s=e[0]+e[1]+e[2],a=ho.centerFromEnd(e,o),l=this.crossCheckVertical(n,a,2*e[1],s);if(!isNaN(l)){const u=(e[0]+e[1]+e[2])/3;for(const p of this.possibleCenters)if(p.aboutEquals(u,l,a))return p.combineEstimate(l,a,u);const h=new Ko(a,l,u);this.possibleCenters.push(h),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(h)}return null}}class Jo extends be{constructor(e,n,o,s){super(e,n),this.estimatedModuleSize=o,this.count=s,s===void 0&&(this.count=1)}getEstimatedModuleSize(){return this.estimatedModuleSize}getCount(){return this.count}aboutEquals(e,n,o){if(Math.abs(n-this.getY())<=e&&Math.abs(o-this.getX())<=e){const s=Math.abs(e-this.estimatedModuleSize);return s<=1||s<=this.estimatedModuleSize}return!1}combineEstimate(e,n,o){const s=this.count+1,a=(this.count*this.getX()+n)/s,l=(this.count*this.getY()+e)/s,u=(this.count*this.estimatedModuleSize+o)/s;return new Jo(a,l,u,s)}}class od{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 zt{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(B.TRY_HARDER)!==void 0,o=e!=null&&e.get(B.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let u=Math.floor(3*a/(4*zt.MAX_MODULES));(u<zt.MIN_SKIP||n)&&(u=zt.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let b=u-1;b<a&&!h;b+=u){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,b))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(zt.foundPatternCross(p)){if(this.handlePossibleCenter(p,b,R,o)===!0)if(u=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const V=this.findRowSkip();V>p[2]&&(b+=V-p[2]-u,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]++;zt.foundPatternCross(p)&&this.handlePossibleCenter(p,b,l,o)===!0&&(u=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return be.orderBestPatterns(y),new od(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 o=n/7,s=o/2;return Math.abs(o-e[0])<s&&Math.abs(o-e[1])<s&&Math.abs(3*o-e[2])<3*s&&Math.abs(o-e[3])<s&&Math.abs(o-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,o,s){const a=this.getCrossCheckStateCount();let l=0;const u=this.image;for(;e>=l&&n>=l&&u.get(n-l,e-l);)a[2]++,l++;if(e<l||n<l)return!1;for(;e>=l&&n>=l&&!u.get(n-l,e-l)&&a[1]<=o;)a[1]++,l++;if(e<l||n<l||a[1]>o)return!1;for(;e>=l&&n>=l&&u.get(n-l,e-l)&&a[0]<=o;)a[0]++,l++;if(a[0]>o)return!1;const h=u.getHeight(),p=u.getWidth();for(l=1;e+l<h&&n+l<p&&u.get(n+l,e+l);)a[2]++,l++;if(e+l>=h||n+l>=p)return!1;for(;e+l<h&&n+l<p&&!u.get(n+l,e+l)&&a[3]<o;)a[3]++,l++;if(e+l>=h||n+l>=p||a[3]>=o)return!1;for(;e+l<h&&n+l<p&&u.get(n+l,e+l)&&a[4]<o;)a[4]++,l++;if(a[4]>=o)return!1;const y=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(y-s)<2*s&&zt.foundPatternCross(a)}crossCheckVertical(e,n,o,s){const a=this.image,l=a.getHeight(),u=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)u[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&a.get(n,h)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(n,h);)u[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&u[3]<o;)u[3]++,h++;if(h===l||u[3]>=o)return NaN;for(;h<l&&a.get(n,h)&&u[4]<o;)u[4]++,h++;if(u[4]>=o)return NaN;const p=u[0]+u[1]+u[2]+u[3]+u[4];return 5*Math.abs(p-s)>=2*s?NaN:zt.foundPatternCross(u)?zt.centerFromEnd(u,h):NaN}crossCheckHorizontal(e,n,o,s){const a=this.image,l=a.getWidth(),u=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)u[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&u[1]<=o;)u[1]++,h--;if(h<0||u[1]>o)return NaN;for(;h>=0&&a.get(h,n)&&u[0]<=o;)u[0]++,h--;if(u[0]>o)return NaN;for(h=e+1;h<l&&a.get(h,n);)u[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&u[3]<o;)u[3]++,h++;if(h===l||u[3]>=o)return NaN;for(;h<l&&a.get(h,n)&&u[4]<o;)u[4]++,h++;if(u[4]>=o)return NaN;const p=u[0]+u[1]+u[2]+u[3]+u[4];return 5*Math.abs(p-s)>=s?NaN:zt.foundPatternCross(u)?zt.centerFromEnd(u,h):NaN}handlePossibleCenter(e,n,o,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=zt.centerFromEnd(e,o),u=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(u)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(u),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(u),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const y=this.possibleCenters;for(let b=0,I=y.length;b<I;b++){const R=y[b];if(R.aboutEquals(h,u,l)){y[b]=R.combineEstimate(u,l,h),p=!0;break}}if(!p){const b=new Jo(l,u,h);y.push(b),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(b)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const o of this.possibleCenters)if(o.getCount()>=zt.CENTER_QUORUM)if(n==null)n=o;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-o.getX())-Math.abs(n.getY()-o.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const o=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=zt.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/o;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 q;const n=this.possibleCenters;let o;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const p=h.getEstimatedModuleSize();s+=p,a+=p*p}o=s/e;let l=Math.sqrt(a/e-o*o);n.sort((h,p)=>{const y=Math.abs(p.getEstimatedModuleSize()-o),b=Math.abs(h.getEstimatedModuleSize()-o);return y<b?-1:y>b?1:0});const u=Math.max(.2*o,l);for(let h=0;h<n.length&&n.length>3;h++){const p=n[h];Math.abs(p.getEstimatedModuleSize()-o)>u&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();o=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const u=Math.abs(l.getEstimatedModuleSize()-o),h=Math.abs(a.getEstimatedModuleSize()-o);return u<h?1:u>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}zt.CENTER_QUORUM=2,zt.MIN_SKIP=3,zt.MAX_MODULES=57;class Dr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(B.NEED_RESULT_POINT_CALLBACK);const o=new zt(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(o)}processFinderPatternInfo(e){const n=e.getTopLeft(),o=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,o,s);if(a<1)throw new q("No pattern found in proccess finder.");const l=Dr.computeDimension(n,o,s,a),u=Ne.getProvisionalVersionForDimension(l),h=u.getDimensionForVersion()-7;let p=null;if(u.getAlignmentPatternCenters().length>0){const R=o.getX()-n.getX()+s.getX(),U=o.getY()-n.getY()+s.getY(),V=1-3/h,H=Math.floor(n.getX()+V*(R-n.getX())),Q=Math.floor(n.getY()+V*(U-n.getY()));for(let he=4;he<=16;he<<=1)try{p=this.findAlignmentInRegion(a,H,Q,he);break}catch(pe){if(!(pe instanceof q))throw pe}}const y=Dr.createTransform(n,o,s,p,l),b=Dr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,o]:I=[s,n,o,p],new Bn(b,I)}static createTransform(e,n,o,s,a){const l=a-3.5;let u,h,p,y;return s!==null?(u=s.getX(),h=s.getY(),p=l-3,y=p):(u=n.getX()-e.getX()+o.getX(),h=n.getY()-e.getY()+o.getY(),p=l,y=l),Ft.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,p,y,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),u,h,o.getX(),o.getY())}static sampleGrid(e,n,o){return sn.getInstance().sampleGridWithTransform(e,o,o,n)}static computeDimension(e,n,o,s){const a=Xe.round(be.distance(e,n)/s),l=Xe.round(be.distance(e,o)/s);let u=Math.floor((a+l)/2)+7;switch(u&3){case 0:u++;break;case 2:u--;break;case 3:throw new q("Dimensions could be not found.")}return u}calculateModuleSize(e,n,o){return(this.calculateModuleSizeOneWay(e,n)+this.calculateModuleSizeOneWay(e,o))/2}calculateModuleSizeOneWay(e,n){const o=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(o)?s/7:isNaN(s)?o/7:(o+s)/14}sizeOfBlackWhiteBlackRunBothWays(e,n,o,s){let a=this.sizeOfBlackWhiteBlackRun(e,n,o,s),l=1,u=e-(o-e);u<0?(l=e/(e-u),u=0):u>=this.image.getWidth()&&(l=(this.image.getWidth()-1-e)/(u-e),u=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),u=Math.floor(e+(u-e)*l),a+=this.sizeOfBlackWhiteBlackRun(e,n,u,h),a-1}sizeOfBlackWhiteBlackRun(e,n,o,s){const a=Math.abs(s-n)>Math.abs(o-e);if(a){let R=e;e=n,n=R,R=o,o=s,s=R}const l=Math.abs(o-e),u=Math.abs(s-n);let h=-l/2;const p=e<o?1:-1,y=n<s?1:-1;let b=0;const I=o+p;for(let R=e,U=n;R!==I;R+=p){const V=a?U:R,H=a?R:U;if(b===1===this.image.get(V,H)){if(b===2)return Xe.distance(R,U,e,n);b++}if(h+=u,h>0){if(U===s)break;U+=y,h-=l}}return b===2?Xe.distance(o+p,s,e,n):NaN}findAlignmentInRegion(e,n,o,s){const a=Math.floor(s*e),l=Math.max(0,n-a),u=Math.min(this.image.getWidth()-1,n+a);if(u-l<e*3)throw new q("Alignment top exceeds estimated module size.");const h=Math.max(0,o-a),p=Math.min(this.image.getHeight()-1,o+a);if(p-h<e*3)throw new q("Alignment bottom exceeds estimated module size.");return new ho(this.image,l,h,u-l,p-h,e,this.resultPointCallback).find()}}class qn{constructor(){this.decoder=new rd}getDecoder(){return this.decoder}decode(e,n){let o,s;if(n!=null&&n.get(B.PURE_BARCODE)!==void 0){const h=qn.extractPureBits(e.getBlackMatrix());o=this.decoder.decodeBitMatrix(h,n),s=qn.NO_POINTS}else{const h=new Dr(e.getBlackMatrix()).detect(n);o=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}o.getOther()instanceof us&&o.getOther().applyMirroredCorrection(s);const a=new qe(o.getText(),o.getRawBytes(),void 0,s,ie.QR_CODE,void 0),l=o.getByteSegments();l!==null&&a.putMetadata(_e.BYTE_SEGMENTS,l);const u=o.getECLevel();return u!==null&&a.putMetadata(_e.ERROR_CORRECTION_LEVEL,u),o.hasStructuredAppend()&&(a.putMetadata(_e.STRUCTURED_APPEND_SEQUENCE,o.getStructuredAppendSequenceNumber()),a.putMetadata(_e.STRUCTURED_APPEND_PARITY,o.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),o=e.getBottomRightOnBit();if(n===null||o===null)throw new q;const s=this.moduleSize(n,e);let a=n[1],l=o[1],u=n[0],h=o[0];if(u>=h||a>=l)throw new q;if(l-a!==h-u&&(h=u+(l-a),h>=e.getWidth()))throw new q;const p=Math.round((h-u+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new q;if(y!==p)throw new q;const b=Math.floor(s/2);a+=b,u+=b;const I=u+Math.floor((p-1)*s)-h;if(I>0){if(I>b)throw new q;u-=I}const R=a+Math.floor((y-1)*s)-l;if(R>0){if(R>b)throw new q;a-=R}const U=new te(p,y);for(let V=0;V<y;V++){const H=a+Math.floor(V*s);for(let Q=0;Q<p;Q++)e.get(u+Math.floor(Q*s),H)&&U.set(Q,V)}return U}static moduleSize(e,n){const o=n.getHeight(),s=n.getWidth();let a=e[0],l=e[1],u=!0,h=0;for(;a<s&&l<o;){if(u!==n.get(a,l)){if(++h===5)break;u=!u}a++,l++}if(a===s||l===o)throw new q;return(a-e[0])/7}}qn.NO_POINTS=new Array;class Be{PDF417Common(){}static getBitCountSum(e){return Xe.sum(e)}static toIntArray(e){if(e==null||!e.length)return Be.EMPTY_INT_ARRAY;const n=new Int32Array(e.length);let o=0;for(const s of e)n[o++]=s;return n}static getCodeword(e){const n=$.binarySearch(Be.SYMBOL_TABLE,e&262143);return n<0?-1:(Be.CODEWORD_TABLE[n]-1)%Be.NUMBER_OF_CODEWORDS}}Be.NUMBER_OF_CODEWORDS=929,Be.MAX_CODEWORDS_IN_BARCODE=Be.NUMBER_OF_CODEWORDS-1,Be.MIN_ROWS_IN_BARCODE=3,Be.MAX_ROWS_IN_BARCODE=90,Be.MODULES_IN_CODEWORD=17,Be.MODULES_IN_STOP_PATTERN=18,Be.BARS_IN_MODULE=8,Be.EMPTY_INT_ARRAY=new Int32Array([]),Be.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]),Be.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 id{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class We{static detectMultiple(e,n,o){let s=e.getBlackMatrix(),a=We.detect(o,s);return a.length||(s=s.clone(),s.rotate180(),a=We.detect(o,s)),new id(s,a)}static detect(e,n){const o=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const u=We.findVertices(n,s,a);if(u[0]==null&&u[3]==null){if(!l)break;l=!1,a=0;for(const h of o)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+=We.ROW_STEP;continue}if(l=!0,o.push(u),!e)break;u[2]!=null?(a=Math.trunc(u[2].getX()),s=Math.trunc(u[2].getY())):(a=Math.trunc(u[4].getX()),s=Math.trunc(u[4].getY()))}return o}static findVertices(e,n,o){const s=e.getHeight(),a=e.getWidth(),l=new Array(8);return We.copyToResult(l,We.findRowsWithPattern(e,s,a,n,o,We.START_PATTERN),We.INDEXES_START_PATTERN),l[4]!=null&&(o=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),We.copyToResult(l,We.findRowsWithPattern(e,s,a,n,o,We.STOP_PATTERN),We.INDEXES_STOP_PATTERN),l}static copyToResult(e,n,o){for(let s=0;s<o.length;s++)e[o[s]]=n[s]}static findRowsWithPattern(e,n,o,s,a,l){const u=new Array(4);let h=!1;const p=new Int32Array(l.length);for(;s<n;s+=We.ROW_STEP){let b=We.findGuardPattern(e,a,s,o,!1,l,p);if(b!=null){for(;s>0;){const I=We.findGuardPattern(e,a,--s,o,!1,l,p);if(I!=null)b=I;else{s++;break}}u[0]=new be(b[0],s),u[1]=new be(b[1],s),h=!0;break}}let y=s+1;if(h){let b=0,I=Int32Array.from([Math.trunc(u[0].getX()),Math.trunc(u[1].getX())]);for(;y<n;y++){const R=We.findGuardPattern(e,I[0],y,o,!1,l,p);if(R!=null&&Math.abs(I[0]-R[0])<We.MAX_PATTERN_DRIFT&&Math.abs(I[1]-R[1])<We.MAX_PATTERN_DRIFT)I=R,b=0;else{if(b>We.SKIPPED_ROW_COUNT_MAX)break;b++}}y-=b+1,u[2]=new be(I[0],y),u[3]=new be(I[1],y)}return y-s<We.BARCODE_MIN_HEIGHT&&$.fill(u,null),u}static findGuardPattern(e,n,o,s,a,l,u){$.fillWithin(u,0,u.length,0);let h=n,p=0;for(;e.get(h,o)&&h>0&&p++<We.MAX_PIXEL_DRIFT;)h--;let y=h,b=0,I=l.length;for(let R=a;y<s;y++)if(e.get(y,o)!==R)u[b]++;else{if(b===I-1){if(We.patternMatchVariance(u,l,We.MAX_INDIVIDUAL_VARIANCE)<We.MAX_AVG_VARIANCE)return new Int32Array([h,y]);h+=u[0]+u[1],P.arraycopy(u,2,u,0,b-1),u[b-1]=0,u[b]=0,b--}else b++;u[b]=1,R=!R}return b===I-1&&We.patternMatchVariance(u,l,We.MAX_INDIVIDUAL_VARIANCE)<We.MAX_AVG_VARIANCE?new Int32Array([h,y-1]):null}static patternMatchVariance(e,n,o){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 u=a/l;o*=u;let h=0;for(let p=0;p<s;p++){let y=e[p],b=n[p]*u,I=y>b?y-b:b-y;if(I>o)return 1/0;h+=I}return h/a}}We.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),We.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),We.MAX_AVG_VARIANCE=.42,We.MAX_INDIVIDUAL_VARIANCE=.8,We.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),We.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),We.MAX_PIXEL_DRIFT=3,We.MAX_PATTERN_DRIFT=5,We.SKIPPED_ROW_COUNT_MAX=25,We.ROW_STEP=5,We.BARCODE_MIN_HEIGHT=10;class $t{constructor(e,n){if(n.length===0)throw new A;this.field=e;let o=n.length;if(o>1&&n[0]===0){let s=1;for(;s<o&&n[s]===0;)s++;s===o?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(o-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],o=this.coefficients.length;for(let s=1;s<o;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,o=e.coefficients;if(n.length>o.length){let l=n;n=o,o=l}let s=new Int32Array(o.length),a=o.length-n.length;P.arraycopy(o,0,s,0,a);for(let l=a;l<o.length;l++)s[l]=this.field.add(n[l-a],o[l]);return new $t(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 $t?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 $t(this.field,new Int32Array([0]));let n=this.coefficients,o=n.length,s=e.coefficients,a=s.length,l=new Int32Array(o+a-1);for(let u=0;u<o;u++){let h=n[u];for(let p=0;p<a;p++)l[u+p]=this.field.add(l[u+p],this.field.multiply(h,s[p]))}return new $t(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let o=0;o<e;o++)n[o]=this.field.subtract(0,this.coefficients[o]);return new $t(this.field,n)}multiplyScalar(e){if(e===0)return new $t(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,o=new Int32Array(n);for(let s=0;s<n;s++)o[s]=this.field.multiply(this.coefficients[s],e);return new $t(this.field,o)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new $t(this.field,new Int32Array([0]));let o=this.coefficients.length,s=new Int32Array(o+e);for(let a=0;a<o;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new $t(this.field,s)}toString(){let e=new fe;for(let n=this.getDegree();n>=0;n--){let o=this.getCoefficient(n);o!==0&&(o<0?(e.append(" - "),o=-o):e.length()>0&&e.append(" + "),(n===0||o!==1)&&e.append(o),n!==0&&(n===1?e.append("x"):(e.append("x^"),e.append(n))))}return e.toString()}}class sd{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 ye;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 Qo extends sd{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let o=1;for(let s=0;s<e;s++)this.expTable[s]=o,o=o*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new $t(this,new Int32Array([0])),this.one=new $t(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 o=new Int32Array(e+1);return o[0]=n,new $t(this,o)}}Qo.PDF417_GF=new Qo(Be.NUMBER_OF_CODEWORDS,3);class ds{constructor(){this.field=Qo.PDF417_GF}decode(e,n,o){let s=new $t(this.field,e),a=new Int32Array(n),l=!1;for(let U=n;U>0;U--){let V=s.evaluateAt(this.field.exp(U));a[n-U]=V,V!==0&&(l=!0)}if(!l)return 0;let u=this.field.getOne();if(o!=null)for(const U of o){let V=this.field.exp(e.length-1-U),H=new $t(this.field,new Int32Array([this.field.subtract(0,V),1]));u=u.multiply(H)}let h=new $t(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],b=p[1],I=this.findErrorLocations(y),R=this.findErrorMagnitudes(b,y,I);for(let U=0;U<I.length;U++){let V=e.length-1-this.field.log(I[U]);if(V<0)throw T.getChecksumInstance();e[V]=this.field.subtract(e[V],R[U])}return I.length}runEuclideanAlgorithm(e,n,o){if(e.getDegree()<n.getDegree()){let I=e;e=n,n=I}let s=e,a=n,l=this.field.getZero(),u=this.field.getOne();for(;a.getDegree()>=Math.round(o/2);){let I=s,R=l;if(s=a,l=u,s.isZero())throw T.getChecksumInstance();a=I;let U=this.field.getZero(),V=s.getCoefficient(s.getDegree()),H=this.field.inverse(V);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Q=a.getDegree()-s.getDegree(),he=this.field.multiply(a.getCoefficient(a.getDegree()),H);U=U.add(this.field.buildMonomial(Q,he)),a=a.subtract(s.multiplyByMonomial(Q,he))}u=U.multiply(l).subtract(R).negative()}let h=u.getCoefficient(0);if(h===0)throw T.getChecksumInstance();let p=this.field.inverse(h),y=u.multiply(p),b=a.multiply(p);return[y,b]}findErrorLocations(e){let n=e.getDegree(),o=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(o[s]=this.field.inverse(a),s++);if(s!==n)throw T.getChecksumInstance();return o}findErrorMagnitudes(e,n,o){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 $t(this.field,a),u=o.length,h=new Int32Array(u);for(let p=0;p<u;p++){let y=this.field.inverse(o[p]),b=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(b,I)}return h}}class ar{constructor(e,n,o,s,a){e instanceof ar?this.constructor_2(e):this.constructor_1(e,n,o,s,a)}constructor_1(e,n,o,s,a){const l=n==null||o==null,u=s==null||a==null;if(l&&u)throw new q;l?(n=new be(0,s.getY()),o=new be(0,a.getY())):u&&(s=new be(e.getWidth()-1,n.getY()),a=new be(e.getWidth()-1,o.getY())),this.image=e,this.topLeft=n,this.bottomLeft=o,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),o.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(o.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 ar(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,o){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,u=this.bottomRight;if(e>0){let h=o?this.topLeft:this.topRight,p=Math.trunc(h.getY()-e);p<0&&(p=0);let y=new be(h.getX(),p);o?s=y:l=y}if(n>0){let h=o?this.bottomLeft:this.bottomRight,p=Math.trunc(h.getY()+n);p>=this.image.getHeight()&&(p=this.image.getHeight()-1);let y=new be(h.getX(),p);o?a=y:u=y}return new ar(this.image,s,a,l,u)}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 ad{constructor(e,n,o,s){this.columnCount=e,this.errorCorrectionLevel=s,this.rowCountUpperPart=n,this.rowCountLowerPart=o,this.rowCount=n+o}getColumnCount(){return this.columnCount}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getRowCount(){return this.rowCount}getRowCountUpperPart(){return this.rowCountUpperPart}getRowCountLowerPart(){return this.rowCountLowerPart}}class Pr{constructor(){this.buffer=""}static form(e,n){let o=-1;function s(l,u,h,p,y,b){if(l==="%%")return"%";if(n[++o]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,R;switch(b){case"s":R=n[o];break;case"c":R=n[o][0];break;case"f":R=parseFloat(n[o]).toFixed(l);break;case"p":R=parseFloat(n[o]).toPrecision(l);break;case"e":R=parseFloat(n[o]).toExponential(l);break;case"x":R=parseInt(n[o]).toString(I||16);break;case"d":R=parseFloat(parseInt(n[o],I||10).toPrecision(l)).toFixed(0);break}R=typeof R=="object"?JSON.stringify(R):(+R).toString(I);let U=parseInt(h),V=h&&h[0]+""=="0"?"0":" ";for(;R.length<U;)R=u!==void 0?R+V:V+R;return R}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Pr.form(e,n)}toString(){return this.buffer}}class Br{constructor(e){this.boundingBox=new ar(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let o=1;o<Br.MAX_NEARBY_DISTANCE;o++){let s=this.imageRowToCodewordIndex(e)-o;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+o,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 Pr;let n=0;for(const o of this.codewords){if(o==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,o.getRowNumber(),o.getValue())}return e.toString()}}Br.MAX_NEARBY_DISTANCE=5;class Lr{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[o,s]of this.values.entries()){const a={getKey:()=>o,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return Be.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class fs extends Br{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 o=this.getBoundingBox(),s=this._isLeft?o.getTopLeft():o.getTopRight(),a=this._isLeft?o.getBottomLeft():o.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),u=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,p=1,y=0;for(let b=l;b<u;b++){if(n[b]==null)continue;let I=n[b],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>b)n[b]=null;else{let U;p>2?U=(p-2)*R:U=R;let V=U>=b;for(let H=1;H<=U&&!V;H++)V=n[b-H]!=null;V?n[b]=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 o of this.getCodewords())if(o!=null){let s=o.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),o=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(o.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),u=this.getCodewords(),h=-1;for(let p=a;p<l;p++){if(u[p]==null)continue;let y=u[p];y.setRowNumberAsRowIndicatorColumn();let b=y.getRowNumber()-h;b===0||(b===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?u[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Lr,o=new Lr,s=new Lr,a=new Lr;for(let u of e){if(u==null)continue;u.setRowNumberAsRowIndicatorColumn();let h=u.getValue()%30,p=u.getRowNumber();switch(this._isLeft||(p+=2),p%3){case 0:o.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||o.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||o.getValue()[0]+s.getValue()[0]<Be.MIN_ROWS_IN_BARCODE||o.getValue()[0]+s.getValue()[0]>Be.MAX_ROWS_IN_BARCODE)return null;let l=new ad(n.getValue()[0],o.getValue()[0],s.getValue()[0],a.getValue()[0]);return this.removeIncorrectCodewords(e,l),l}removeIncorrectCodewords(e,n){for(let o=0;o<e.length;o++){let s=e[o];if(e[o]==null)continue;let a=s.getValue()%30,l=s.getRowNumber();if(l>n.getRowCount()){e[o]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:a*3+1!==n.getRowCountUpperPart()&&(e[o]=null);break;case 1:(Math.trunc(a/3)!==n.getErrorCorrectionLevel()||a%3!==n.getRowCountLowerPart())&&(e[o]=null);break;case 2:a+1!==n.getColumnCount()&&(e[o]=null);break}}}isLeft(){return this._isLeft}toString(){return"IsLeft: "+this._isLeft+`
68
+ `+super.toString()}}class Fr{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=Be.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 o=this.detectionResultColumns[n].getCodewords();for(let s=0;s<o.length;s++)o[s]!=null&&(o[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,o))}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 o=0;o<e.length;o++)if(e[o]!=null&&n[o]!=null&&e[o].getRowNumber()===n[o].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[o];a!=null&&(a.setRowNumber(e[o].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[o]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let o=0;o<n.length;o++){if(n[o]==null)continue;let s=n[o].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let u=this.detectionResultColumns[l].getCodewords()[o];u!=null&&(a=Fr.adjustRowNumberIfValid(s,a,u),u.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let o=0;o<n.length;o++){if(n[o]==null)continue;let s=n[o].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let u=this.detectionResultColumns[l].getCodewords()[o];u!=null&&(a=Fr.adjustRowNumberIfValid(s,a,u),u.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,o){return o==null||o.hasValidRowNumber()||(o.isValidRowNumber(e)?(o.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,o){if(!this.detectionResultColumns[e-1])return;let s=o[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let u=new Array(14);u[2]=a[n],u[3]=l[n],n>0&&(u[0]=o[n-1],u[4]=a[n-1],u[5]=l[n-1]),n>1&&(u[8]=o[n-2],u[10]=a[n-2],u[11]=l[n-2]),n<o.length-1&&(u[1]=o[n+1],u[6]=a[n+1],u[7]=l[n+1]),n<o.length-2&&(u[9]=o[n+2],u[12]=a[n+2],u[13]=l[n+2]);for(let h of u)if(Fr.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 Pr;for(let o=0;o<e.getCodewords().length;o++){n.format("CW %3d:",o);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[o];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Ur{constructor(e,n,o,s){this.rowNumber=Ur.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(o),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Ur.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}}Ur.BARCODE_ROW_UNKNOWN=-1;class en{static initialize(){for(let e=0;e<Be.SYMBOL_TABLE.length;e++){let n=Be.SYMBOL_TABLE[e],o=n&1;for(let s=0;s<Be.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===o;)a+=1,n>>=1;o=n&1,en.RATIOS_TABLE[e]||(en.RATIOS_TABLE[e]=new Array(Be.BARS_IN_MODULE)),en.RATIOS_TABLE[e][Be.BARS_IN_MODULE-s-1]=Math.fround(a/Be.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=en.getDecodedCodewordValue(en.sampleBitCounts(e));return n!==-1?n:en.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=Xe.sum(e),o=new Int32Array(Be.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Be.MODULES_IN_CODEWORD;l++){let u=n/(2*Be.MODULES_IN_CODEWORD)+l*n/Be.MODULES_IN_CODEWORD;a+e[s]<=u&&(a+=e[s],s++),o[s]++}return o}static getDecodedCodewordValue(e){let n=en.getBitValue(e);return Be.getCodeword(n)===-1?-1:n}static getBitValue(e){let n=0;for(let o=0;o<e.length;o++)for(let s=0;s<e[o];s++)n=n<<1|(o%2===0?1:0);return Math.trunc(n)}static getClosestDecodedValue(e){let n=Xe.sum(e),o=new Array(Be.BARS_IN_MODULE);if(n>1)for(let l=0;l<o.length;l++)o[l]=Math.fround(e[l]/n);let s=In.MAX_VALUE,a=-1;this.bSymbolTableReady||en.initialize();for(let l=0;l<en.RATIOS_TABLE.length;l++){let u=0,h=en.RATIOS_TABLE[l];for(let p=0;p<Be.BARS_IN_MODULE;p++){let y=Math.fround(h[p]-o[p]);if(u+=Math.fround(y*y),u>=s)break}u<s&&(s=u,a=Be.SYMBOL_TABLE[l])}return a}}en.bSymbolTableReady=!1,en.RATIOS_TABLE=new Array(Be.SYMBOL_TABLE.length).map(C=>new Array(Be.BARS_IN_MODULE));class hs{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 ps{static parseLong(e,n=void 0){return parseInt(e,n)}}class ms extends g{}ms.kind="NullPointerException";class ld{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,o){if(e==null)throw new ms;if(n<0||n>e.length||o<0||n+o>e.length||n+o<0)throw new M;if(o===0)return;for(let s=0;s<o;s++)this.write(e[n+s])}flush(){}close(){}}class cd extends g{}class ud extends ld{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 o=this.buf.length<<1;if(o-e<0&&(o=e),o<0){if(e<0)throw new cd;o=F.MAX_VALUE}this.buf=$.copyOfUint8Array(this.buf,o)}write(e){this.ensureCapacity(this.count+1),this.buf[this.count]=e,this.count+=1}writeBytesOffset(e,n,o){if(n<0||n>e.length||o<0||n+o-e.length>0)throw new M;this.ensureCapacity(this.count+o),P.arraycopy(e,n,this.buf,this.count,o),this.count+=o}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return $.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 ut;(function(C){C[C.ALPHA=0]="ALPHA",C[C.LOWER=1]="LOWER",C[C.MIXED=2]="MIXED",C[C.PUNCT=3]="PUNCT",C[C.ALPHA_SHIFT=4]="ALPHA_SHIFT",C[C.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(ut||(ut={}));function gs(){if(typeof window<"u")return window.BigInt||null;if(typeof To<"u")return To.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let po;function Xn(C){if(typeof po>"u"&&(po=gs()),po===null)throw new Error("BigInt is not supported!");return po(C)}function dd(){let C=[];C[0]=Xn(1);let e=Xn(900);C[1]=e;for(let n=2;n<16;n++)C[n]=C[n-1]*e;return C}class K{static decode(e,n){let o=new fe(""),s=z.ISO8859_1;o.enableDecoding(s);let a=1,l=e[a++],u=new hs;for(;a<e[0];){switch(l){case K.TEXT_COMPACTION_MODE_LATCH:a=K.textCompaction(e,a,o);break;case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:a=K.byteCompaction(l,e,s,a,o);break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:o.append(e[a++]);break;case K.NUMERIC_COMPACTION_MODE_LATCH:a=K.numericCompaction(e,a,o);break;case K.ECI_CHARSET:z.getCharacterSetECIByValue(e[a++]);break;case K.ECI_GENERAL_PURPOSE:a+=2;break;case K.ECI_USER_DEFINED:a++;break;case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=K.decodeMacroBlock(e,a,u);break;case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:throw new L;default:a--,a=K.textCompaction(e,a,o);break}if(a<e.length)l=e[a++];else throw L.getFormatInstance()}if(o.length()===0)throw L.getFormatInstance();let h=new Pe(null,o.toString(),null,n);return h.setOther(u),h}static decodeMacroBlock(e,n,o){if(n+K.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw L.getFormatInstance();let s=new Int32Array(K.NUMBER_OF_SEQUENCE_CODEWORDS);for(let u=0;u<K.NUMBER_OF_SEQUENCE_CODEWORDS;u++,n++)s[u]=e[n];o.setSegmentIndex(F.parseInt(K.decodeBase900toBase10(s,K.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new fe;n=K.textCompaction(e,n,a),o.setFileId(a.toString());let l=-1;for(e[n]===K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case K.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let u=new fe;n=K.textCompaction(e,n+1,u),o.setFileName(u.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new fe;n=K.textCompaction(e,n+1,h),o.setSender(h.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new fe;n=K.textCompaction(e,n+1,p),o.setAddressee(p.toString());break;case K.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new fe;n=K.numericCompaction(e,n+1,y),o.setSegmentCount(F.parseInt(y.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let b=new fe;n=K.numericCompaction(e,n+1,b),o.setTimestamp(ps.parseLong(b.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new fe;n=K.numericCompaction(e,n+1,I),o.setChecksum(F.parseInt(I.toString()));break;case K.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let R=new fe;n=K.numericCompaction(e,n+1,R),o.setFileSize(ps.parseLong(R.toString()));break;default:throw L.getFormatInstance()}break;case K.MACRO_PDF417_TERMINATOR:n++,o.setLastSegment(!0);break;default:throw L.getFormatInstance()}if(l!==-1){let u=n-l;o.isLastSegment()&&u--,o.setOptionalData($.copyOfRange(e,l,l+u))}return n}static textCompaction(e,n,o){let s=new Int32Array((e[0]-n)*2),a=new Int32Array((e[0]-n)*2),l=0,u=!1;for(;n<e[0]&&!u;){let h=e[n++];if(h<K.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case K.TEXT_COMPACTION_MODE_LATCH:s[l++]=K.TEXT_COMPACTION_MODE_LATCH;break;case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:n--,u=!0;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return K.decodeTextCompaction(s,a,l,o),n}static decodeTextCompaction(e,n,o,s){let a=ut.ALPHA,l=ut.ALPHA,u=0;for(;u<o;){let h=e[u],p="";switch(a){case ut.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case K.LL:a=ut.LOWER;break;case K.ML:a=ut.MIXED;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case K.AS:l=a,a=ut.ALPHA_SHIFT;break;case K.ML:a=ut.MIXED;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.MIXED:if(h<K.PL)p=K.MIXED_CHARS[h];else switch(h){case K.PL:a=ut.PUNCT;break;case 26:p=" ";break;case K.LL:a=ut.LOWER;break;case K.AL:a=ut.ALPHA;break;case K.PS:l=a,a=ut.PUNCT_SHIFT;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.PUNCT:if(h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=ut.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break;case ut.PUNCT_SHIFT:if(a=l,h<K.PAL)p=K.PUNCT_CHARS[h];else switch(h){case K.PAL:a=ut.ALPHA;break;case K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[u]);break;case K.TEXT_COMPACTION_MODE_LATCH:a=ut.ALPHA;break}break}p!==""&&s.append(p),u++}}static byteCompaction(e,n,o,s,a){let l=new ud,u=0,h=0,p=!1;switch(e){case K.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),b=n[s++];for(;s<n[0]&&!p;)switch(y[u++]=b,h=900*h+b,b=n[s++],b){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(u%5===0&&u>0){for(let I=0;I<6;++I)l.write(Number(Xn(h)>>Xn(8*(5-I))));h=0,u=0}break}s===n[0]&&b<K.TEXT_COMPACTION_MODE_LATCH&&(y[u++]=b);for(let I=0;I<u;I++)l.write(y[I]);break;case K.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<K.TEXT_COMPACTION_MODE_LATCH)u++,h=900*h+I;else switch(I){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.NUMERIC_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(u%5===0&&u>0){for(let R=0;R<6;++R)l.write(Number(Xn(h)>>Xn(8*(5-R))));h=0,u=0}}break}return a.append(G.decode(l.toByteArray(),o)),s}static numericCompaction(e,n,o){let s=0,a=!1,l=new Int32Array(K.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let u=e[n++];if(n===e[0]&&(a=!0),u<K.TEXT_COMPACTION_MODE_LATCH)l[s]=u,s++;else switch(u){case K.TEXT_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH:case K.BYTE_COMPACTION_MODE_LATCH_6:case K.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case K.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%K.MAX_NUMERIC_CODEWORDS===0||u===K.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(o.append(K.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let o=Xn(0);for(let a=0;a<n;a++)o+=K.EXP900[n-a-1]*Xn(e[a]);let s=o.toString();if(s.charAt(0)!=="1")throw new L;return s.substring(1)}}K.TEXT_COMPACTION_MODE_LATCH=900,K.BYTE_COMPACTION_MODE_LATCH=901,K.NUMERIC_COMPACTION_MODE_LATCH=902,K.BYTE_COMPACTION_MODE_LATCH_6=924,K.ECI_USER_DEFINED=925,K.ECI_GENERAL_PURPOSE=926,K.ECI_CHARSET=927,K.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,K.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,K.MACRO_PDF417_TERMINATOR=922,K.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,K.MAX_NUMERIC_CODEWORDS=15,K.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,K.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,K.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,K.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,K.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,K.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,K.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,K.PL=25,K.LL=27,K.AS=27,K.ML=28,K.AL=28,K.PS=29,K.PAL=29,K.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
69
+ -.$/"|*()?{}'`,K.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",K.EXP900=gs()?dd():[],K.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ge{constructor(){}static decode(e,n,o,s,a,l,u){let h=new ar(e,n,o,s,a),p=null,y=null,b;for(let U=!0;;U=!1){if(n!=null&&(p=Ge.getRowIndicatorColumn(e,h,n,!0,l,u)),s!=null&&(y=Ge.getRowIndicatorColumn(e,h,s,!1,l,u)),b=Ge.merge(p,y),b==null)throw q.getNotFoundInstance();let V=b.getBoundingBox();if(U&&V!=null&&(V.getMinY()<h.getMinY()||V.getMaxY()>h.getMaxY()))h=V;else break}b.setBoundingBox(h);let I=b.getBarcodeColumnCount()+1;b.setDetectionResultColumn(0,p),b.setDetectionResultColumn(I,y);let R=p!=null;for(let U=1;U<=I;U++){let V=R?U:I-U;if(b.getDetectionResultColumn(V)!==void 0)continue;let H;V===0||V===I?H=new fs(h,V===0):H=new Br(h),b.setDetectionResultColumn(V,H);let Q=-1,he=Q;for(let pe=h.getMinY();pe<=h.getMaxY();pe++){if(Q=Ge.getStartColumn(b,V,pe,R),Q<0||Q>h.getMaxX()){if(he===-1)continue;Q=he}let ce=Ge.detectCodeword(e,h.getMinX(),h.getMaxX(),R,Q,pe,l,u);ce!=null&&(H.setCodeword(pe,ce),he=Q,l=Math.min(l,ce.getWidth()),u=Math.max(u,ce.getWidth()))}}return Ge.createDecoderResult(b)}static merge(e,n){if(e==null&&n==null)return null;let o=Ge.getBarcodeMetadata(e,n);if(o==null)return null;let s=ar.merge(Ge.adjustBoundingBox(e),Ge.adjustBoundingBox(n));return new Fr(o,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let o=Ge.getMax(n),s=0;for(let u of n)if(s+=o-u,u>0)break;let a=e.getCodewords();for(let u=0;s>0&&a[u]==null;u++)s--;let l=0;for(let u=n.length-1;u>=0&&(l+=o-n[u],!(n[u]>0));u--);for(let u=a.length-1;l>0&&a[u]==null;u--)l--;return e.getBoundingBox().addMissingRows(s,l,e.isLeft())}static getMax(e){let n=-1;for(let o of e)n=Math.max(n,o);return n}static getBarcodeMetadata(e,n){let o;if(e==null||(o=e.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();let s;return n==null||(s=n.getBarcodeMetadata())==null?o:o.getColumnCount()!==s.getColumnCount()&&o.getErrorCorrectionLevel()!==s.getErrorCorrectionLevel()&&o.getRowCount()!==s.getRowCount()?null:o}static getRowIndicatorColumn(e,n,o,s,a,l){let u=new fs(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(o.getX()));for(let b=Math.trunc(Math.trunc(o.getY()));b<=n.getMaxY()&&b>=n.getMinY();b+=p){let I=Ge.detectCodeword(e,0,e.getWidth(),s,y,b,a,l);I!=null&&(u.setCodeword(b,I),s?y=I.getStartX():y=I.getEndX())}}return u}static adjustCodewordCount(e,n){let o=n[0][1],s=o.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ge.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Be.MAX_CODEWORDS_IN_BARCODE)throw q.getNotFoundInstance();o.setValue(a)}else s[0]!==a&&o.setValue(a)}static createDecoderResult(e){let n=Ge.createBarcodeMatrix(e);Ge.adjustCodewordCount(e,n);let o=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(),b=h*e.getBarcodeColumnCount()+p;y.length===0?o.push(b):y.length===1?s[b]=y[0]:(l.push(b),a.push(y))}let u=new Array(a.length);for(let h=0;h<u.length;h++)u[h]=a[h];return Ge.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Be.toIntArray(o),Be.toIntArray(l),u)}static createDecoderResultFromAmbiguousValues(e,n,o,s,a){let l=new Int32Array(s.length),u=100;for(;u-- >0;){for(let h=0;h<l.length;h++)n[s[h]]=a[h][l[h]];try{return Ge.decodeCodewords(n,e,o)}catch(h){if(!(h instanceof T))throw h}if(l.length===0)throw T.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 T.getChecksumInstance()}throw T.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 Lr;let o=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][o].setValue(a.getValue())}}}o++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,o,s){let a=s?1:-1,l=null;if(Ge.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodeword(o)),l!=null)return s?l.getEndX():l.getStartX();if(l=e.getDetectionResultColumn(n).getCodewordNearby(o),l!=null)return s?l.getStartX():l.getEndX();if(Ge.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(o)),l!=null)return s?l.getEndX():l.getStartX();let u=0;for(;Ge.isValidBarcodeColumn(e,n-a);){n-=a;for(let h of e.getDetectionResultColumn(n).getCodewords())if(h!=null)return(s?h.getEndX():h.getStartX())+a*u*(h.getEndX()-h.getStartX());u++}return s?e.getBoundingBox().getMinX():e.getBoundingBox().getMaxX()}static detectCodeword(e,n,o,s,a,l,u,h){a=Ge.adjustCodewordStartColumn(e,n,o,s,a,l);let p=Ge.getModuleBitCount(e,n,o,s,a,l);if(p==null)return null;let y,b=Xe.sum(p);if(s)y=a+b;else{for(let U=0;U<p.length/2;U++){let V=p[U];p[U]=p[p.length-1-U],p[p.length-1-U]=V}y=a,a=y-b}if(!Ge.checkCodewordSkew(b,u,h))return null;let I=en.getDecodedValue(p),R=Be.getCodeword(I);return R===-1?null:new Ur(a,y,Ge.getCodewordBucketNumber(I),R)}static getModuleBitCount(e,n,o,s,a,l){let u=a,h=new Int32Array(8),p=0,y=s?1:-1,b=s;for(;(s?u<o:u>=n)&&p<h.length;)e.get(u,l)===b?(h[p]++,u+=y):(p++,b=!b);return p===h.length||u===(s?o:n)&&p===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,o,s,a,l){let u=a,h=s?-1:1;for(let p=0;p<2;p++){for(;(s?u>=n:u<o)&&s===e.get(u,l);){if(Math.abs(a-u)>Ge.CODEWORD_SKEW_SIZE)return a;u+=h}h=-h,s=!s}return u}static checkCodewordSkew(e,n,o){return n-Ge.CODEWORD_SKEW_SIZE<=e&&e<=o+Ge.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,o){if(e.length===0)throw L.getFormatInstance();let s=1<<n+1,a=Ge.correctErrors(e,o,s);Ge.verifyCodewordCount(e,s);let l=K.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(o.length),l}static correctErrors(e,n,o){if(n!=null&&n.length>o/2+Ge.MAX_ERRORS||o<0||o>Ge.MAX_EC_CODEWORDS)throw T.getChecksumInstance();return Ge.errorCorrection.decode(e,o,n)}static verifyCodewordCount(e,n){if(e.length<4)throw L.getFormatInstance();let o=e[0];if(o>e.length)throw L.getFormatInstance();if(o===0)if(n<e.length)e[0]=e.length-n;else throw L.getFormatInstance()}static getBitCountForCodeword(e){let n=new Int32Array(8),o=0,s=n.length-1;for(;!((e&1)!==o&&(o=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 Ge.getCodewordBucketNumber(Ge.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Pr;for(let o=0;o<e.length;o++){n.format("Row %2d: ",o);for(let s=0;s<e[o].length;s++){let a=e[o][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()}}Ge.CODEWORD_SKEW_SIZE=2,Ge.MAX_ERRORS=3,Ge.MAX_EC_CODEWORDS=512,Ge.errorCorrection=new ds;class jt{decode(e,n=null){let o=jt.decode(e,n,!1);if(o==null||o.length===0||o[0]==null)throw q.getNotFoundInstance();return o[0]}decodeMultiple(e,n=null){try{return jt.decode(e,n,!0)}catch(o){throw o instanceof L||o instanceof T?q.getNotFoundInstance():o}}static decode(e,n,o){const s=new Array,a=We.detectMultiple(e,n,o);for(const l of a.getPoints()){const u=Ge.decode(a.getBits(),l[4],l[5],l[6],l[7],jt.getMinCodewordWidth(l),jt.getMaxCodewordWidth(l)),h=new qe(u.getText(),u.getRawBytes(),void 0,l,ie.PDF_417);h.putMetadata(_e.ERROR_CORRECTION_LEVEL,u.getECLevel());const p=u.getOther();p!=null&&h.putMetadata(_e.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?F.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(jt.getMaxWidth(e[0],e[4]),jt.getMaxWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.max(jt.getMaxWidth(e[1],e[5]),jt.getMaxWidth(e[7],e[3])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(jt.getMinWidth(e[0],e[4]),jt.getMinWidth(e[6],e[2])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN),Math.min(jt.getMinWidth(e[1],e[5]),jt.getMinWidth(e[7],e[3])*Be.MODULES_IN_CODEWORD/Be.MODULES_IN_STOP_PATTERN)))}reset(){}}class mo extends g{}mo.kind="ReaderException";class xs{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(B.TRY_HARDER)===!0,o=c(e)?null:e.get(B.POSSIBLE_FORMATS),s=new Array;if(!c(o)){const a=o.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 br(e,this.verbose)),o.includes(ie.QR_CODE)&&s.push(new qn),o.includes(ie.DATA_MATRIX)&&s.push(new Gn),o.includes(ie.AZTEC)&&s.push(new Ln),o.includes(ie.PDF_417)&&s.push(new jt),a&&n&&s.push(new br(e,this.verbose))}s.length===0&&(n||s.push(new br(e,this.verbose)),s.push(new qn),s.push(new Gn),s.push(new Ln),s.push(new jt),n&&s.push(new br(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 mo("No readers where selected, nothing can be read.");for(const n of this.readers)try{return n.decode(e,this.hints)}catch(o){if(o instanceof mo)continue}throw new q("No MultiFormat Readers were able to detect the code.")}}class fd extends Ze{constructor(e=null,n=500){const o=new xs;o.setHints(e),super(o,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class hd extends Ze{constructor(e=500){super(new jt,e)}}class pd extends Ze{constructor(e=500){super(new qn,e)}}var ei;(function(C){C[C.ERROR_CORRECTION=0]="ERROR_CORRECTION",C[C.CHARACTER_SET=1]="CHARACTER_SET",C[C.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",C[C.MIN_SIZE=3]="MIN_SIZE",C[C.MAX_SIZE=4]="MAX_SIZE",C[C.MARGIN=5]="MARGIN",C[C.PDF417_COMPACT=6]="PDF417_COMPACT",C[C.PDF417_COMPACTION=7]="PDF417_COMPACTION",C[C.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",C[C.AZTEC_LAYERS=9]="AZTEC_LAYERS",C[C.QR_VERSION=10]="QR_VERSION"})(ei||(ei={}));var Bt=ei;class ti{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new J(e,Int32Array.from([1])))}buildGenerator(e){const n=this.cachedGenerators;if(e>=n.length){let o=n[n.length-1];const s=this.field;for(let a=n.length;a<=e;a++){const l=o.multiply(new J(s,Int32Array.from([1,s.exp(a-1+s.getGeneratorBase())])));n.push(l),o=l}}return n[e]}encode(e,n){if(n===0)throw new A("No error correction bytes");const o=e.length-n;if(o<=0)throw new A("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(o);P.arraycopy(e,0,a,0,o);let l=new J(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[o+y]=0;P.arraycopy(h,0,e,o+p,h.length)}}class Nt{constructor(){}static applyMaskPenaltyRule1(e){return Nt.applyMaskPenaltyRule1Internal(e,!0)+Nt.applyMaskPenaltyRule1Internal(e,!1)}static applyMaskPenaltyRule2(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a-1;l++){const u=o[l];for(let h=0;h<s-1;h++){const p=u[h];p===u[h+1]&&p===o[l+1][h]&&p===o[l+1][h+1]&&n++}}return Nt.N2*n}static applyMaskPenaltyRule3(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let l=0;l<a;l++)for(let u=0;u<s;u++){const h=o[l];u+6<s&&h[u]===1&&h[u+1]===0&&h[u+2]===1&&h[u+3]===1&&h[u+4]===1&&h[u+5]===0&&h[u+6]===1&&(Nt.isWhiteHorizontal(h,u-4,u)||Nt.isWhiteHorizontal(h,u+7,u+11))&&n++,l+6<a&&o[l][u]===1&&o[l+1][u]===0&&o[l+2][u]===1&&o[l+3][u]===1&&o[l+4][u]===1&&o[l+5][u]===0&&o[l+6][u]===1&&(Nt.isWhiteVertical(o,u,l-4,l)||Nt.isWhiteVertical(o,u,l+7,l+11))&&n++}return n*Nt.N3}static isWhiteHorizontal(e,n,o){n=Math.max(n,0),o=Math.min(o,e.length);for(let s=n;s<o;s++)if(e[s]===1)return!1;return!0}static isWhiteVertical(e,n,o,s){o=Math.max(o,0),s=Math.min(s,e.length);for(let a=o;a<s;a++)if(e[a][n]===1)return!1;return!0}static applyMaskPenaltyRule4(e){let n=0;const o=e.getArray(),s=e.getWidth(),a=e.getHeight();for(let h=0;h<a;h++){const p=o[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)*Nt.N4}static getDataMaskBit(e,n,o){let s,a;switch(e){case 0:s=o+n&1;break;case 1:s=o&1;break;case 2:s=n%3;break;case 3:s=(o+n)%3;break;case 4:s=Math.floor(o/2)+Math.floor(n/3)&1;break;case 5:a=o*n,s=(a&1)+a%3;break;case 6:a=o*n,s=(a&1)+a%3&1;break;case 7:a=o*n,s=a%3+(o+n&1)&1;break;default:throw new A("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let o=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let u=0;u<s;u++){let h=0,p=-1;for(let y=0;y<a;y++){const b=n?l[u][y]:l[y][u];b===p?h++:(h>=5&&(o+=Nt.N1+(h-5)),h=1,p=b)}h>=5&&(o+=Nt.N1+(h-5))}return o}}Nt.N1=3,Nt.N2=3,Nt.N3=40,Nt.N4=10;class go{constructor(e,n){this.width=e,this.height=n;const o=new Array(n);for(let s=0;s!==n;s++)o[s]=new Uint8Array(e);this.bytes=o}getHeight(){return this.height}getWidth(){return this.width}get(e,n){return this.bytes[n][e]}getArray(){return this.bytes}setNumber(e,n,o){this.bytes[n][e]=o}setBoolean(e,n,o){this.bytes[n][e]=o?1:0}clear(e){for(const n of this.bytes)$.fill(n,e)}equals(e){if(!(e instanceof go))return!1;const n=e;if(this.width!==n.width||this.height!==n.height)return!1;for(let o=0,s=this.height;o<s;++o){const a=this.bytes[o],l=n.bytes[o];for(let u=0,h=this.width;u<h;++u)if(a[u]!==l[u])return!1}return!0}toString(){const e=new fe;for(let n=0,o=this.height;n<o;++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(`
70
+ `)}return e.toString()}}class lr{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 fe;return e.append(`<<
71
71
  `),e.append(" mode: "),e.append(this.mode?this.mode.toString():"null"),e.append(`
72
72
  ecLevel: `),e.append(this.ecLevel?this.ecLevel.toString():"null"),e.append(`
73
73
  version: `),e.append(this.version?this.version.toString():"null"),e.append(`
@@ -76,9 +76,9 @@ ${this.tempPrompt}
76
76
  `),e.append(this.matrix.toString())):e.append(`
77
77
  matrix: null
78
78
  `),e.append(`>>
79
- `),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<lr.NUM_MASK_PATTERNS}}lr.NUM_MASK_PATTERNS=8;class ut extends x{}ut.kind="WriterException";class Be{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Be.clearMatrix(a),Be.embedBasicPatterns(i,a),Be.embedTypeInfo(n,s,a),Be.maybeEmbedVersionInfo(i,a),Be.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Be.embedPositionDetectionPatternsAndSeparators(n),Be.embedDarkDotAtLeftBottomCorner(n),Be.maybeEmbedPositionAdjustmentPatterns(e,n),Be.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new re;Be.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Be.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(i.setBoolean(p,y,d),a<8){const b=i.getWidth()-a-1;i.setBoolean(b,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 re;Be.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(!Be.isEmpty(i.get(p,d)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&Tt.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 ut("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-Z.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const i=Be.findMSBSet(n);for(e<<=i-1;Be.findMSBSet(e)>=i;)e^=n<<Be.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!lr.isValidMaskPattern(n))throw new ut("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Be.calculateBCHCode(s,Be.TYPE_INFO_POLY);i.appendBits(a,10);const l=new re;if(l.appendBits(Be.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new ut("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Be.calculateBCHCode(e.getVersionNumber(),Be.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new ut("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;Be.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Be.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new ut;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Be.isEmpty(i.get(e+s,n)))throw new ut;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Be.isEmpty(i.get(e,n+s)))throw new ut;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Be.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=Be.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Be.POSITION_DETECTION_PATTERN[0].length;Be.embedPositionDetectionPattern(0,0,e),Be.embedPositionDetectionPattern(e.getWidth()-n,0,e),Be.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Be.embedHorizontalSeparationPattern(0,i-1,e),Be.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Be.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Be.embedVerticalSeparationPattern(s,0,e),Be.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Be.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Be.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&&Be.isEmpty(n.get(p,d))&&Be.embedPositionAdjustmentPattern(p-2,d-2,n)}}}}Be.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])]),Be.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])]),Be.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])]),Be.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])]),Be.VERSION_INFO_POLY=7973,Be.TYPE_INFO_POLY=1335,Be.TYPE_INFO_MASK_PATTERN=21522;class cd{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class gt{constructor(){}static calculateMaskPenalty(e){return Tt.applyMaskPenaltyRule1(e)+Tt.applyMaskPenaltyRule2(e)+Tt.applyMaskPenaltyRule3(e)+Tt.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=gt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Ft.CHARACTER_SET)!==void 0;a&&(s=i.get(Ft.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new re;if(l===De.BYTE&&(a||gt.DEFAULT_BYTE_MODE_ENCODING!==s)){const de=U.getCharacterSetECIByName(s);de!==void 0&&this.appendECI(de,d)}this.appendModeInfo(l,d);const h=new re;this.appendBytes(e,l,h,s);let p;if(i!==null&&i.get(Ft.QR_VERSION)!==void 0){const de=Number.parseInt(i.get(Ft.QR_VERSION).toString(),10);p=Re.getVersionForNumber(de);const ae=this.calculateBitsNeeded(l,d,h,p);if(!this.willFit(ae,p,n))throw new ut("Data too big for requested version")}else p=this.recommendVersion(n,l,d,h);const y=new re;y.appendBitArray(d);const b=l===De.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(b,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()),V=new lr;V.setECLevel(n),V.setMode(l),V.setVersion(p);const W=p.getDimensionForVersion(),Q=new fi(W,W),ce=this.chooseMaskPattern(F,n,p,Q);return V.setMaskPattern(ce),Be.buildMatrix(F,n,p,ce,Q),V.setMatrix(Q),V}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,Re.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<gt.ALPHANUMERIC_TABLE.length?gt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(U.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return De.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(gt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return De.BYTE}return s?De.ALPHANUMERIC:i?De.NUMERIC:De.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=Y.encode(e,U.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<lr.NUM_MASK_PATTERNS;d++){Be.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=Re.getVersionForNumber(i);if(gt.willFit(e,s,n))return s}throw new ut("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 ut("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 ut("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new ut("Block ID too large");const d=e%i,h=i-d,p=Math.floor(e/i),y=p+1,b=Math.floor(n/i),I=b+1,R=p-b,F=y-I;if(R!==F)throw new ut("EC bytes mismatch");if(i!==h+d)throw new ut("RS blocks mismatch");if(e!==(b+R)*h+(I+F)*d)throw new ut("Total bytes mismatch");s<h?(a[0]=b,l[0]=R):(a[0]=I,l[0]=F)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new ut("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 b=new Int32Array(1),I=new Int32Array(1);gt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,y,b,I);const R=b[0],F=new Uint8Array(R);e.toBytes(8*a,F,0,R);const V=gt.generateECBytes(F,I[0]);h.push(new cd(F,V)),l=Math.max(l,R),d=Math.max(d,V.length),a+=b[0]}if(i!==a)throw new ut("Data bytes does not match offset");const p=new re;for(let y=0;y<l;++y)for(const b of h){const I=b.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<d;++y)for(const b of h){const I=b.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new ut("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 Ki(we.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 ut(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case De.NUMERIC:gt.appendNumericBytes(e,i);break;case De.ALPHANUMERIC:gt.appendAlphanumericBytes(e,i);break;case De.BYTE:gt.append8BitBytes(e,i,s);break;case De.KANJI:gt.appendKanjiBytes(e,i);break;default:throw new ut("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=gt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=gt.getDigit(e.charAt(s));if(s+2<i){const l=gt.getDigit(e.charAt(s+1)),d=gt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=gt.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=gt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new ut;if(s+1<i){const l=gt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new ut;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=Y.encode(e,i)}catch(a){throw new ut(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=Y.encode(e,U.SJIS)}catch(a){throw new ut(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 ut("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(De.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}gt.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]),gt.DEFAULT_BYTE_MODE_ENCODING=U.UTF8.getName();class cr{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=ht.L,l=cr.QUIET_ZONE_SIZE;s!==null&&(s.get(Ft.ERROR_CORRECTION)!==void 0&&(a=ht.fromString(s.get(Ft.ERROR_CORRECTION).toString())),s.get(Ft.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Ft.MARGIN).toString(),10)));const d=gt.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 Bt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),b=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),F=Math.floor((b-d*I)/2),V=this.createSVGElement(y,b);for(let W=0,Q=F;W<d;W++,Q+=I)for(let ce=0,de=R;ce<l;ce++,de+=I)if(a.get(ce,W)===1){const ae=this.createSvgRectElement(de,Q,I,I);V.appendChild(ae)}return V}createSVGElement(e,n){const i=document.createElementNS(cr.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(cr.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}}cr.QUIET_ZONE_SIZE=4,cr.SVG_NS="http://www.w3.org/2000/svg";class Ar{encode(e,n,i,s,a){if(e.length===0)throw new A("Found empty contents");if(n!==te.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=ht.L,d=Ar.QUIET_ZONE_SIZE;a!==null&&(a.get(Ft.ERROR_CORRECTION)!==void 0&&(l=ht.fromString(a.get(Ft.ERROR_CORRECTION).toString())),a.get(Ft.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Ft.MARGIN).toString(),10)));const h=gt.encode(e,l,a);return Ar.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Bt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),b=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),F=Math.floor((b-d*I)/2),V=new Te(y,b);for(let W=0,Q=F;W<d;W++,Q+=I)for(let ce=0,de=R;ce<l;ce++,de+=I)a.get(ce,W)===1&&V.setRegion(de,Q,I,I);return V}}Ar.QUIET_ZONE_SIZE=4;class ud{encode(e,n,i,s,a){let l;switch(n){case te.QR_CODE:l=new Ar;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class Mn extends Se{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 Mn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/Mn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/Mn.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*Mn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|p*65793}a+=this.dataWidth*Mn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/Mn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/Mn.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 We(this)}}Mn.THUMBNAIL_SCALE_FACTOR=2;class Ji extends Se{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 b=e[y],I=b>>16&255,R=b>>7&510,F=b&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 Ji(this.luminances,i,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new We(this)}}class ms extends U{static forName(e){return this.getCharacterSetECIByName(e)}}class Qi{}Qi.ISO_8859_1=U.ISO8859_1;class gs{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 xs{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class dd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Er extends dd{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 Er(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new Er(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+Z.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class eo extends Er{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 eo(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function fd(C,e,n){return new eo(C,e,n)}function Fr(C,e,n){return new Er(C,e,n)}const hd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Jn=0,hi=1,yn=2,ys=3,Dn=4,pd=new Er(null,0,0),to=[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 md(C){for(let e of C)z.fill(e,-1);return C[Jn][Dn]=0,C[hi][Dn]=0,C[hi][Jn]=28,C[ys][Dn]=0,C[yn][Dn]=0,C[yn][Jn]=15,C}const ws=md(z.createInt32Array(6,6));class Pn{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=to[this.mode][e];s=Fr(s,l&65535,l>>16),i+=l>>16}let a=e===yn?4:5;return s=Fr(s,n,a),new Pn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===yn?4:5;return i=Fr(i,ws[this.mode][e],s),i=Fr(i,n,5),new Pn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===Dn||this.mode===yn){let d=to[i][Jn];n=Fr(n,d&65535,d>>16),s+=d>>16,i=Jn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Pn(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=fd(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Pn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(to[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Pn.calculateBinaryShiftCost(e)-Pn.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 re;for(const s of n)s.appendTo(i,e);return i}toString(){return ue.format("%s bits=%d bytes=%d",hd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Pn.INITIAL_STATE=new Pn(pd,Jn,0,0);function gd(C){const e=ue.getCharCode(" "),n=ue.getCharCode("."),i=ue.getCharCode(",");C[Jn][e]=1;const s=ue.getCharCode("Z"),a=ue.getCharCode("A");for(let I=a;I<=s;I++)C[Jn][I]=I-a+2;C[hi][e]=1;const l=ue.getCharCode("z"),d=ue.getCharCode("a");for(let I=d;I<=l;I++)C[hi][I]=I-d+2;C[yn][e]=1;const h=ue.getCharCode("9"),p=ue.getCharCode("0");for(let I=p;I<=h;I++)C[yn][I]=I-p+2;C[yn][i]=12,C[yn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
80
- `,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)C[ys][ue.getCharCode(y[I])]=I;const b=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<b.length;I++)ue.getCharCode(b[I])>0&&(C[Dn][ue.getCharCode(b[I])]=I);return C}const no=gd(z.createInt32Array(5,256));class Ur{constructor(e){this.text=e}encode(){const e=ue.getCharCode(" "),n=ue.getCharCode(`
81
- `);let i=xs.singletonList(Pn.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 ue.getCharCode("\r"):l=d===n?2:0;break;case ue.getCharCode("."):l=d===e?3:0;break;case ue.getCharCode(","):l=d===e?4:0;break;case ue.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Ur.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return xs.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 Ur.simplifyStates(i)}updateStateForChar(e,n,i){let s=this.text[n]&255,a=no[e.getMode()][s]>0,l=null;for(let d=0;d<=Dn;d++){let h=no[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===yn){const p=l.latchAndAppend(d,h);i.push(p)}if(!a&&ws[e.getMode()][d]>=0){const p=l.shiftAndAppend(d,h);i.push(p)}}}if(e.getBinaryShiftByteCount()>0||no[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(Dn,i)),e.getMode()!==Dn&&s.push(a.shiftAndAppend(Dn,i)),i===3||i===4){let l=a.latchAndAppend(yn,16-i).latchAndAppend(yn,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 Ke{constructor(){}static encodeBytes(e){return Ke.encode(e,Ke.DEFAULT_EC_PERCENT,Ke.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Ur(e).encode(),a=Z.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,p,y,b;if(i!==Ke.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?Ke.MAX_NB_BITS_COMPACT:Ke.MAX_NB_BITS))throw new A(ue.format("Illegal value %s for layers",i));p=Ke.totalBitsInLayer(h,d),y=Ke.WORD_SIZE[h];let ae=p-p%y;if(b=Ke.stuffBits(s,y),b.getSize()+a>ae)throw new A("Data to large for user specified layer");if(d&&b.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,b=null;for(let ae=0;;ae++){if(ae>Ke.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(d=ae<=3,h=d?ae+1:ae,p=Ke.totalBitsInLayer(h,d),l>p)continue;(b==null||y!==Ke.WORD_SIZE[h])&&(y=Ke.WORD_SIZE[h],b=Ke.stuffBits(s,y));let Xe=p-p%y;if(!(d&&b.getSize()>y*64)&&b.getSize()+a<=Xe)break}}let I=Ke.generateCheckWords(b,p,y),R=b.getSize()/y,F=Ke.generateModeMessage(d,h,R),V=(d?11:14)+h*4,W=new Int32Array(V),Q;if(d){Q=V;for(let ae=0;ae<W.length;ae++)W[ae]=ae}else{Q=V+1+2*Z.truncDivision(Z.truncDivision(V,2)-1,15);let ae=Z.truncDivision(V,2),Xe=Z.truncDivision(Q,2);for(let Ve=0;Ve<ae;Ve++){let rn=Ve+Z.truncDivision(Ve,15);W[ae-Ve-1]=Xe-rn-1,W[ae+Ve]=Xe+rn+1}}let ce=new Te(Q);for(let ae=0,Xe=0;ae<h;ae++){let Ve=(h-ae)*4+(d?9:12);for(let rn=0;rn<Ve;rn++){let _n=rn*2;for(let on=0;on<2;on++)I.get(Xe+_n+on)&&ce.set(W[ae*2+on],W[ae*2+rn]),I.get(Xe+Ve*2+_n+on)&&ce.set(W[ae*2+rn],W[V-1-ae*2-on]),I.get(Xe+Ve*4+_n+on)&&ce.set(W[V-1-ae*2-on],W[V-1-ae*2-rn]),I.get(Xe+Ve*6+_n+on)&&ce.set(W[V-1-ae*2-rn],W[ae*2+on])}Xe+=Ve*8}if(Ke.drawModeMessage(ce,d,Q,F),d)Ke.drawBullsEye(ce,Z.truncDivision(Q,2),5);else{Ke.drawBullsEye(ce,Z.truncDivision(Q,2),7);for(let ae=0,Xe=0;ae<Z.truncDivision(V,2)-1;ae+=15,Xe+=16)for(let Ve=Z.truncDivision(Q,2)&1;Ve<Q;Ve+=2)ce.set(Z.truncDivision(Q,2)-Xe,Ve),ce.set(Z.truncDivision(Q,2)+Xe,Ve),ce.set(Ve,Z.truncDivision(Q,2)-Xe),ce.set(Ve,Z.truncDivision(Q,2)+Xe)}let de=new gs;return de.setCompact(d),de.setSize(Q),de.setLayers(h),de.setCodeWords(R),de.setMatrix(ce),de}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 re;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=Ke.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=Ke.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=Z.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+Z.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 Ki(Ke.getGF(i)),l=Z.truncDivision(n,i),d=Ke.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,p=new re;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 we.AZTEC_PARAM;case 6:return we.AZTEC_DATA_6;case 8:return we.AZTEC_DATA_8;case 10:return we.AZTEC_DATA_10;case 12:return we.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let i=new re,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}}Ke.DEFAULT_EC_PERCENT=33,Ke.DEFAULT_AZTEC_LAYERS=0,Ke.MAX_NB_BITS=32,Ke.MAX_NB_BITS_COMPACT=4,Ke.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 pi{encode(e,n,i,s){return this.encodeWithHints(e,n,i,s,null)}encodeWithHints(e,n,i,s,a){let l=Qi.ISO_8859_1,d=Ke.DEFAULT_EC_PERCENT,h=Ke.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Ft.CHARACTER_SET)&&(l=ms.forName(a.get(Ft.CHARACTER_SET).toString())),a.has(Ft.ERROR_CORRECTION)&&(d=Z.parseInt(a.get(Ft.ERROR_CORRECTION).toString())),a.has(Ft.AZTEC_LAYERS)&&(h=Z.parseInt(a.get(Ft.AZTEC_LAYERS).toString()))),pi.encodeLayers(e,n,i,s,l,d,h)}static encodeLayers(e,n,i,s,a,l,d){if(n!==te.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=Ke.encode(ue.getBytes(e,a),l,d);return pi.renderResult(h,i,s)}static renderResult(e,n,i){let s=e.getMatrix();if(s==null)throw new Bt;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,b=(h-l*p)/2,I=new Te(d,h);for(let R=0,F=b;R<l;R++,F+=p)for(let V=0,W=y;V<a;V++,W+=p)s.get(V,R)&&I.setRegion(W,F,p,p);return I}}o.AbstractExpandedDecoder=Vi,o.ArgumentException=E,o.ArithmeticException=et,o.AztecCode=gs,o.AztecCodeReader=Ye,o.AztecCodeWriter=pi,o.AztecDecoder=Qe,o.AztecDetector=se,o.AztecDetectorResult=Hn,o.AztecEncoder=Ke,o.AztecHighLevelEncoder=Ur,o.AztecPoint=k,o.BarcodeFormat=te,o.Binarizer=S,o.BinaryBitmap=M,o.BitArray=re,o.BitMatrix=Te,o.BitSource=Hi,o.BrowserAztecCodeReader=bt,o.BrowserBarcodeReader=Gu,o.BrowserCodeReader=Je,o.BrowserDatamatrixCodeReader=qu,o.BrowserMultiFormatReader=sd,o.BrowserPDF417Reader=ad,o.BrowserQRCodeReader=ld,o.BrowserQRCodeSvgWriter=cr,o.CharacterSetECI=U,o.ChecksumException=T,o.Code128Reader=pe,o.Code39Reader=Rt,o.DataMatrixDecodedBitStreamParser=Xn,o.DataMatrixReader=qn,o.DecodeHintType=P,o.DecoderResult=fe,o.DefaultGridSampler=ir,o.DetectorResult=Un,o.EAN13Reader=zn,o.EncodeHintType=Ft,o.Exception=x,o.FormatException=L,o.GenericGF=we,o.GenericGFPoly=xe,o.GlobalHistogramBinarizer=ye,o.GridSampler=Wn,o.GridSamplerInstance=ln,o.HTMLCanvasElementLuminanceSource=me,o.HybridBinarizer=he,o.ITFReader=at,o.IllegalArgumentException=A,o.IllegalStateException=Bt,o.InvertedLuminanceSource=We,o.LuminanceSource=Se,o.MathUtils=je,o.MultiFormatOneDReader=Cr,o.MultiFormatReader=ps,o.MultiFormatWriter=ud,o.NotFoundException=H,o.OneDReader=mt,o.PDF417DecodedBitStreamParser=J,o.PDF417DecoderErrorCorrection=ls,o.PDF417Reader=Wt,o.PDF417ResultMetadata=us,o.PerspectiveTransform=zt,o.PlanarYUVLuminanceSource=Mn,o.QRCodeByteMatrix=fi,o.QRCodeDataMask=gn,o.QRCodeDecodedBitStreamParser=At,o.QRCodeDecoderErrorCorrectionLevel=ht,o.QRCodeDecoderFormatInformation=qt,o.QRCodeEncoder=gt,o.QRCodeEncoderQRCode=lr,o.QRCodeMaskUtil=Tt,o.QRCodeMatrixUtil=Be,o.QRCodeMode=De,o.QRCodeReader=Yn,o.QRCodeVersion=Re,o.QRCodeWriter=Ar,o.RGBLuminanceSource=Ji,o.RSS14Reader=St,o.RSSExpandedReader=oe,o.ReaderException=di,o.ReedSolomonDecoder=Tn,o.ReedSolomonEncoder=Ki,o.ReedSolomonException=kt,o.Result=be,o.ResultMetadataType=Ae,o.ResultPoint=Ce,o.StringUtils=ue,o.UnsupportedOperationException=ee,o.VideoInputDevice=Oe,o.WhiteRectangleDetector=Yt,o.WriterException=ut,o.ZXingArrays=z,o.ZXingCharset=ms,o.ZXingInteger=Z,o.ZXingStandardCharsets=Qi,o.ZXingStringBuilder=ge,o.ZXingStringEncoding=Y,o.ZXingSystem=B,o.createAbstractExpandedDecoder=ss,Object.defineProperty(o,"__esModule",{value:!0})}))})(Hr,Hr.exports)),Hr.exports}var xt=qy();const Yy=Gy(xt),Ky=Cd({__proto__:null,default:Yy},[xt]);var ol=(function(){function t(r,o,c){if(this.formatMap=new Map([[ve.QR_CODE,xt.BarcodeFormat.QR_CODE],[ve.AZTEC,xt.BarcodeFormat.AZTEC],[ve.CODABAR,xt.BarcodeFormat.CODABAR],[ve.CODE_39,xt.BarcodeFormat.CODE_39],[ve.CODE_93,xt.BarcodeFormat.CODE_93],[ve.CODE_128,xt.BarcodeFormat.CODE_128],[ve.DATA_MATRIX,xt.BarcodeFormat.DATA_MATRIX],[ve.MAXICODE,xt.BarcodeFormat.MAXICODE],[ve.ITF,xt.BarcodeFormat.ITF],[ve.EAN_13,xt.BarcodeFormat.EAN_13],[ve.EAN_8,xt.BarcodeFormat.EAN_8],[ve.PDF_417,xt.BarcodeFormat.PDF_417],[ve.RSS_14,xt.BarcodeFormat.RSS_14],[ve.RSS_EXPANDED,xt.BarcodeFormat.RSS_EXPANDED],[ve.UPC_A,xt.BarcodeFormat.UPC_A],[ve.UPC_E,xt.BarcodeFormat.UPC_E],[ve.UPC_EAN_EXTENSION,xt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!Ky)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(xt.DecodeHintType.POSSIBLE_FORMATS,u),f.set(xt.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 xt.MultiFormatReader(this.verbose,this.hints),c=new xt.HTMLCanvasElementLuminanceSource(r),u=new xt.BinaryBitmap(new xt.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:Uu.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})(),Jy=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 g(E){try{x(c.next(E))}catch(A){m(A)}}function v(E){try{x(c.throw(E))}catch(A){m(A)}}function x(E){E.done?f(E.value):u(E.value).then(g,v)}x((c=c.apply(t,r||[])).next())})},Qy=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(E){x=[6,E],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},sl=(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 Jy(this,void 0,void 0,function(){var o,c;return Qy(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:Uu.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],g=m.boundingBox.width*m.boundingBox.height;g>c&&(c=g,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})(),al=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 g(E){try{x(c.next(E))}catch(A){m(A)}}function v(E){try{x(c.throw(E))}catch(A){m(A)}}function x(E){E.done?f(E.value):u(E.value).then(g,v)}x((c=c.apply(t,r||[])).next())})},ll=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(E){x=[6,E],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},ew=(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&&sl.isSupported()?(this.primaryDecoder=new sl(r,c,u),this.secondaryDecoder=new ol(r,c,u)):this.primaryDecoder=new ol(r,c,u)}return t.prototype.decodeAsync=function(r){return al(this,void 0,void 0,function(){var o;return ll(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 al(this,void 0,void 0,function(){var o,c;return ll(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})(),ts=(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)}})(),Ri=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 g(E){try{x(c.next(E))}catch(A){m(A)}}function v(E){try{x(c.throw(E))}catch(A){m(A)}}function x(E){E.done?f(E.value):u(E.value).then(g,v)}x((c=c.apply(t,r||[])).next())})},Mi=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(E){x=[6,E],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Vu=(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})(),tw=(function(t){ts(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})(Vu),nw=(function(t){ts(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(tw),rw=(function(t){ts(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(Vu),iw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new nw(this.track)},t.prototype.torchFeature=function(){return new rw(this.track)},t})(),ow=(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 Ri(this,void 0,void 0,function(){var f,m;return Mi(this,function(g){switch(g.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:g.sent(),g.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 Ri(this,void 0,void 0,function(){return Mi(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(g){r.mediaStream.removeTrack(g),g.stop(),++m,m>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),o())})})},t.prototype.getCapabilities=function(){return new iw(this.getFirstTrackOrFail())},t})(),sw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,o,c){return Ri(this,void 0,void 0,function(){return Mi(this,function(u){return[2,ow.create(r,this.mediaStream,o,c)]})})},t.create=function(r){return Ri(this,void 0,void 0,function(){var o,c;return Mi(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})(),cl=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 g(E){try{x(c.next(E))}catch(A){m(A)}}function v(E){try{x(c.throw(E))}catch(A){m(A)}}function x(E){E.done?f(E.value):u(E.value).then(g,v)}x((c=c.apply(t,r||[])).next())})},ul=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(E){x=[6,E],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},aw=(function(){function t(){}return t.failIfNotSupported=function(){return cl(this,void 0,void 0,function(){return ul(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return cl(this,void 0,void 0,function(){return ul(this,function(o){return[2,sw.create(r)]})})},t})(),lw=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 g(E){try{x(c.next(E))}catch(A){m(A)}}function v(E){try{x(c.throw(E))}catch(A){m(A)}}function x(E){E.done?f(E.value):u(E.value).then(g,v)}x((c=c.apply(t,r||[])).next())})},cw=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:g(0),throw:g(1),return:g(2)},typeof Symbol=="function"&&(m[Symbol.iterator]=function(){return this}),m;function g(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,x[0]&&(o=0)),o;)try{if(c=1,u&&(f=x[0]&2?u.return:x[0]?u.throw||((f=u.return)&&f.call(u),0):u.next)&&!(f=f.call(u,x[1])).done)return f;switch(u=0,f&&(x=[x[0]&2,f.value]),x[0]){case 0:case 1:f=x;break;case 4:return o.label++,{value:x[1],done:!1};case 5:o.label++,u=x[1],x=[0];continue;case 7:x=o.ops.pop(),o.trys.pop();continue;default:if(f=o.trys,!(f=f.length>0&&f[f.length-1])&&(x[0]===6||x[0]===2)){o=0;continue}if(x[0]===3&&(!f||x[1]>f[0]&&x[1]<f[3])){o.label=x[1];break}if(x[0]===6&&o.label<f[1]){o.label=f[1],f=x;break}if(f&&o.label<f[2]){o.label=f[2],o.ops.push(x);break}f[2]&&o.ops.pop(),o.trys.pop();continue}x=r.call(t,o)}catch(E){x=[6,E],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},uw=(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=Or.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Or.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 lw(this,void 0,void 0,function(){var r,o,c,u,f,m,g;return cw(this,function(v){switch(v.label){case 0:return r=function(x){for(var E=x.getVideoTracks(),A=0,M=E;A<M.length;A++){var T=M[A];T.enabled=!1,T.stop(),x.removeTrack(T)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return o=v.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=v.sent(),u=[],f=0,m=c;f<m.length;f++)g=m[f],g.kind==="videoinput"&&u.push({id:g.deviceId,label:g.label});return r(o),[2,u]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,o){var c=function(f){for(var m=[],g=0,v=f;g<v.length;g++){var x=v[g];x.kind==="video"&&m.push({id:x.id,label:x.label})}r(m)},u=MediaStreamTrack;u.getSources(c)})},t})(),Nt;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Nt||(Nt={}));var dw=(function(){function t(){this.state=Nt.NOT_STARTED,this.onGoingTransactionNewState=Nt.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===Nt.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Nt.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Nt.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Nt.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Nt.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Nt.UNKNOWN:throw"Transition from unknown is not allowed";case Nt.NOT_STARTED:this.failIfNewStateIs(r,[Nt.PAUSED]);break;case Nt.SCANNING:break;case Nt.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})(),fw=(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()===Nt.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Nt.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Nt.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Nt.PAUSED},t})(),hw=(function(){function t(){}return t.create=function(){return new fw(new dw)},t})(),pw=(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)}})(),un=(function(t){pw(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})(jy),mw=(function(){function t(r,o){this.logger=o,this.fps=un.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=un.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?zu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Vn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),dl=(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 Wy(this.verbose),this.qrcode=new ew(this.getSupportedFormats(o),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=hw.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 g=mw.create(o,this.logger);this.clearElement();var v=!1;g.videoConstraints&&(g.isMediaStreamConstraintsValid()?v=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var x=v,E=document.getElementById(this.elementId);E.clientWidth?E.clientWidth:un.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,M=this.stateManagerProxy.startTransition(Nt.SCANNING);return new Promise(function(T,S){var B=x?g.videoConstraints:A.createVideoConstraints(r);if(!B){M.cancel(),S("videoConstraints should be defined");return}var D={};(!x||g.aspectRatio)&&(D.aspectRatio=g.aspectRatio);var ne={onRenderSurfaceReady:function(z,Z){A.setupUi(z,Z,g),A.isScanning=!0,A.foreverScan(g,c,m)}};aw.failIfNotSupported().then(function(z){z.create(B).then(function(Z){return Z.render(f.element,D,ne).then(function(re){A.renderedCamera=re,M.execute(),T(null)}).catch(function(re){M.cancel(),S(re)})}).catch(function(Z){M.cancel(),S(Or.errorGettingUserMedia(Z))})}).catch(function(z){M.cancel(),S(Or.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Nt.PAUSED),this.showPausedState(),(Vn(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(Nt.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(Nt.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(un.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(Vn(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 g=m.width,v=m.height,x=document.getElementById(c.elementId),E=x.clientWidth?x.clientWidth:un.DEFAULT_WIDTH,A=Math.max(x.clientHeight?x.clientHeight:v,un.FILE_SCAN_MIN_HEIGHT),M=c.computeCanvasDrawConfig(g,v,E,A);if(o){var T=c.createCanvasElement(E,A,"qr-canvas-visible");T.style.display="inline-block",x.appendChild(T);var S=T.getContext("2d");if(!S)throw"Unable to get 2d context from canvas";S.canvas.width=E,S.canvas.height=A,S.drawImage(m,0,0,g,v,M.x,M.y,M.width,M.height)}var B=un.FILE_SCAN_HIDDEN_CANVAS_PADDING,D=Math.max(m.width,M.width),ne=Math.max(m.height,M.height),z=D+2*B,Z=ne+2*B,re=c.createCanvasElement(z,Z);x.appendChild(re);var $=re.getContext("2d");if(!$)throw"Unable to get 2d context from canvas";$.canvas.width=z,$.canvas.height=Z,$.drawImage(m,0,0,g,v,B,B,D,ne);try{c.qrcode.decodeRobustlyAsync(re).then(function(P){u(rl.createFromQrcodeResult(P))}).catch(f)}catch(P){f("QR code parse error, error = ".concat(P))}},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 uw.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(!zu.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];$y(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(Vn(r))return!0;if(!Vn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Vn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Vn(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),g=function(x){if(x<un.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(un.MIN_QR_BOX_SIZE,"px.")},v=function(x){return x>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."),x=r),x};g(m.width),g(m.height),m.width=v(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=Vn(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,g={x:0,y:0,width:r,height:o},v=m?this.getShadedRegionBounds(r,o,f):g,x=this.createCanvasElement(v.width,v.height),E={willReadFrequently:!0},A=x.getContext("2d",E);A.canvas.width=v.width,A.canvas.height=v.height,this.element.append(x),m&&this.possiblyInsertShadingElement(this.element,r,o,f),this.createScannerPausedUiElement(this.element),this.qrRegion=v,this.context=A,this.canvasElement=x},t.prototype.createScannerPausedUiElement=function(r){var o=document.createElement("div");o.innerText=Or.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,rl.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Or.codeParseError(u);return o(f,Hy.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,g=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var v=this.qrRegion.width*m,x=this.qrRegion.height*g,E=this.qrRegion.x*m,A=this.qrRegion.y*g;this.context.drawImage(f,E,A,v,x,0,0,this.qrRegion.width,this.qrRegion.height);var M=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(T){!T&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){M()})):M()}).catch(function(T){u.logger.logError("Error happend while scanning context",T),M()})}},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(S){if(S in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(S,"'")},g=Object.keys(r);if(g.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(g.length," keys");var v=Object.keys(r)[0];if(v!==o&&v!==c)throw"Only '".concat(o,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(v===o){var x=r.facingMode;if(typeof x=="string"){if(m(x))return{facingMode:x}}else if(typeof x=="object")if(f in x){if(m(x["".concat(f)]))return{facingMode:{exact:x["".concat(f)]}}}else throw"'facingMode' should be string or object with"+" ".concat(f," as key.");else{var E=typeof x;throw"Invalid type of 'facingMode' = ".concat(E)}}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 M=typeof A;throw"Invalid type of 'deviceId' = ".concat(M)}}}var T=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(T)},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 g=r,v=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(g,"X").concat(v)+" 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?un.BORDER_SHADER_MATCH_COLOR:un.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=Vn(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,g=(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(g,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(g,"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(un.SHADED_REGION_ELEMENT_ID),o-u.width<11||c-u.height<11)this.hasBorderShaders=!1;else{var v=5,x=40;this.insertShaderBorders(f,x,v,-v,null,0,!0),this.insertShaderBorders(f,x,v,-v,null,0,!1),this.insertShaderBorders(f,x,v,null,-v,0,!0),this.insertShaderBorders(f,x,v,null,-v,0,!1),this.insertShaderBorders(f,v,x+v,-v,null,-v,!0),this.insertShaderBorders(f,v,x+v,null,-v,-v,!0),this.insertShaderBorders(f,v,x+v,-v,null,-v,!1),this.insertShaderBorders(f,v,x+v,null,-v,-v,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,o,c,u,f,m,g){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=un.BORDER_SHADER_DEFAULT_COLOR,v.style.width="".concat(o,"px"),v.style.height="".concat(c,"px"),u!==null&&(v.style.top="".concat(u,"px")),f!==null&&(v.style.bottom="".concat(f,"px")),g?v.style.left="".concat(m,"px"):v.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(v),r.appendChild(v)},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})(),fl;(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"})(fl||(fl={}));const gw={class:"scan-code"},xw={class:"btn"},yw={class:"left-back"},ww=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=vd.IconScan(),u=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!u.html5QrCode){rt("摄像头无访问权限!");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 T=new URL(A).searchParams.get("sessionId");T?o("scanSuccess",T):rt("无效的二维码")}catch{rt("无效的二维码")}E()}).catch(A=>{console.log(A),rt({message:"二维码识别失败",duration:3e3})})},g=()=>{x().then(()=>{m()})},v=()=>{E()},x=()=>dl.getCameras().then(A=>{A&&A.length&&(u.html5QrCode=new dl("reader"))}).catch(()=>{rt({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{u.html5QrCode&&u.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),rt("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&E()}),(A,M)=>{const T=es;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref($t.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:M[0]||(M[0]=S=>g())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",gw,[M[1]||(M[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",xw,[_.createElementVNode("div",yw,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),_w=rr(ww,[["__scopeId","data-v-2d988579"]]);function ns(t,r,o){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const E=c.value;if(E.length===0)return"";if(r){const M=typeof r=="string"?r:r.value;if(M&&E.some(T=>T.id===M))return M}const A=E.find(M=>M.isDefault);return A?A.id:E[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=u());else{let E;r&&typeof r=="string"&&(E=r),f=_.ref(E&&c.value.some(A=>A.id===E)?E:u())}(!m||o)&&_.watch(f,E=>{o&&o(E)});const g=_.computed(()=>c.value.find(E=>E.id===f.value)),v=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:g,availableModels:v,setSelectedModel:E=>{c.value.find(M=>M.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const vw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Cw=Object.prototype.toString,bw=t=>Cw.call(t)==="[object Object]",Ei=()=>{};function go(t){return Array.isArray(t)?t:[t]}function Aw(t,r,o){return _.watch(t,r,{...o,immediate:!0})}const Zu=vw?window:void 0;function Wr(t){var r;const o=_.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function xo(...t){const r=(c,u,f,m)=>(c.addEventListener(u,f,m),()=>c.removeEventListener(u,f,m)),o=_.computed(()=>{const c=go(_.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return Aw(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>Wr(f)))!==null&&c!==void 0?c:[Zu].filter(f=>f!=null),go(_.toValue(o.value?t[1]:t[0])),go(_.unref(o.value?t[2]:t[1])),_.toValue(o.value?t[3]:t[2])]},([c,u,f,m],g,v)=>{if(!c?.length||!u?.length||!f?.length)return;const x=bw(m)?{...m}:m,E=c.flatMap(A=>u.flatMap(M=>f.map(T=>r(A,M,T,x))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Ew(t,r,o={}){const{window:c=Zu,ignore:u=[],capture:f=!0,detectIframe:m=!1,controls:g=!1}=o;if(!c)return g?{stop:Ei,cancel:Ei,trigger:Ei}:Ei;let v=!0;const x=D=>_.toValue(u).some(ne=>{if(typeof ne=="string")return Array.from(c.document.querySelectorAll(ne)).some(z=>z===D.target||D.composedPath().includes(z));{const z=Wr(ne);return z&&(D.target===z||D.composedPath().includes(z))}});function E(D){const ne=_.toValue(D);return ne&&ne.$.subTree.shapeFlag===16}function A(D,ne){const z=_.toValue(D),Z=z.$.subTree&&z.$.subTree.children;return Z==null||!Array.isArray(Z)?!1:Z.some(re=>re.el===ne.target||ne.composedPath().includes(re.el))}const M=D=>{const ne=Wr(t);if(D.target!=null&&!(!(ne instanceof Element)&&E(t)&&A(t,D))&&!(!ne||ne===D.target||D.composedPath().includes(ne))){if("detail"in D&&D.detail===0&&(v=!x(D)),!v){v=!0;return}r(D)}};let T=!1;const S=[xo(c,"click",D=>{T||(T=!0,setTimeout(()=>{T=!1},0),M(D))},{passive:!0,capture:f}),xo(c,"pointerdown",D=>{const ne=Wr(t);v=!x(D)&&!!(ne&&!D.composedPath().includes(ne))},{passive:!0}),m&&xo(c,"blur",D=>{setTimeout(()=>{const ne=Wr(t);let z=c.document.activeElement;for(;z?.shadowRoot;)z=z.shadowRoot.activeElement;z?.tagName==="IFRAME"&&!ne?.contains(c.document.activeElement)&&r(D)},0)},{passive:!0})].filter(Boolean),B=()=>S.forEach(D=>D());return g?{stop:B,cancel:()=>{v=!1},trigger:D=>{v=!0,M(D),v=!1}}:B}const Iw=["data-active","disabled"],Sw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,o)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,Iw))}}),rs=rr(Sw,[["__scopeId","data-v-6f582cce"]]),Tw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Nw(t,r){return _.openBlock(),_.createElementBlock("svg",Tw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.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 Ow={render:Nw},kw={class:"button-text"},Rw={class:"dropdown-menu__items"},Mw=["onClick"],Dw=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,o=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const T=r.modelConfigs;return T?Array.isArray(T)?T:T.value:[]}),{selectedModel:u,availableModels:f,setSelectedModel:m}=ns(c,o),g=_.ref(!1),v=T=>{m(T),E()},x=()=>{g.value=!g.value},E=()=>{g.value=!1},A=_.ref(null),M=_.ref(null);return Ew(M,()=>{E()},{ignore:[A]}),(T,S)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[_.createVNode(rs,{size:"small",class:"action-button",rounded:"",onClick:x},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(u)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",kw,_.toDisplayString(_.unref(u)?.label),1),_.createVNode(_.unref(Ow),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[g.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:M},[_.createElementVNode("div",Rw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),B=>(_.openBlock(),_.createElementBlock("div",{key:B.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":B.id===o.value}]),onClick:_.withModifiers(D=>v(B.id),["stop"])},[B.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(B.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(B.label),1)],10,Mw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),g.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),Pw=rr(Dw,[["__scopeId","data-v-475491fd"]]),Bw={key:0,class:"active-count"},Lw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,o=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,u)=>(_.openBlock(),_.createBlock(rs,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(kr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(_.openBlock(),_.createElementBlock("span",Bw,_.toDisplayString(o.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Fw=rr(Lw,[["__scopeId","data-v-c2a16c66"]]),Uw={"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 zw(t,r){return _.openBlock(),_.createElementBlock("svg",Uw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.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 Vw={render:zw},Zw=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),o=()=>{r.value=!r.value};return(c,u)=>(_.openBlock(),_.createBlock(rs,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:_.withCtx(()=>[_.createVNode(_.unref(Vw),{width:16,height:16}),u[0]||(u[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),$w=rr(Zw,[["__scopeId","data-v-7f3b0372"]]),jw={class:"bubble-image-wrapper"},Hw=["src"],Ww=["src"],Gw=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),o=_.ref(null),c=()=>{r.value=!0},u=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{o.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",jw,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,Hw),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:u,onKeydown:_.withKeys(u,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:o,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:u},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.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),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,Ww)])],32)):_.createCommentVNode("",!0)]))]))}}),Xw=rr(Gw,[["__scopeId","data-v-91c75579"]]),qw=`
79
+ `),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<lr.NUM_MASK_PATTERNS}}lr.NUM_MASK_PATTERNS=8;class dt extends g{}dt.kind="WriterException";class De{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,o,s,a){De.clearMatrix(a),De.embedBasicPatterns(o,a),De.embedTypeInfo(n,s,a),De.maybeEmbedVersionInfo(o,a),De.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){De.embedPositionDetectionPatternsAndSeparators(n),De.embedDarkDotAtLeftBottomCorner(n),De.maybeEmbedPositionAdjustmentPatterns(e,n),De.embedTimingPatterns(n)}static embedTypeInfo(e,n,o){const s=new re;De.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const u=s.get(s.getSize()-1-a),h=De.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(o.setBoolean(p,y,u),a<8){const b=o.getWidth()-a-1;o.setBoolean(b,8,u)}else{const I=o.getHeight()-7+(a-8);o.setBoolean(8,I,u)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const o=new re;De.makeVersionInfoBits(e,o);let s=17;for(let a=0;a<6;++a)for(let l=0;l<3;++l){const u=o.get(s);s--,n.setBoolean(a,n.getHeight()-11+l,u),n.setBoolean(n.getHeight()-11+l,a,u)}}static embedDataBits(e,n,o){let s=0,a=-1,l=o.getWidth()-1,u=o.getHeight()-1;for(;l>0;){for(l===6&&(l-=1);u>=0&&u<o.getHeight();){for(let h=0;h<2;++h){const p=l-h;if(!De.isEmpty(o.get(p,u)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&Nt.getDataMaskBit(n,p,u)&&(y=!y),o.setBoolean(p,u,y)}u+=a}a=-a,u+=a,l-=2}if(s!==e.getSize())throw new dt("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-F.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const o=De.findMSBSet(n);for(e<<=o-1;De.findMSBSet(e)>=o;)e^=n<<De.findMSBSet(e)-o;return e}static makeTypeInfoBits(e,n,o){if(!lr.isValidMaskPattern(n))throw new dt("Invalid mask pattern");const s=e.getBits()<<3|n;o.appendBits(s,5);const a=De.calculateBCHCode(s,De.TYPE_INFO_POLY);o.appendBits(a,10);const l=new re;if(l.appendBits(De.TYPE_INFO_MASK_PATTERN,15),o.xor(l),o.getSize()!==15)throw new dt("should not happen but we got: "+o.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const o=De.calculateBCHCode(e.getVersionNumber(),De.VERSION_INFO_POLY);if(n.appendBits(o,12),n.getSize()!==18)throw new dt("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 o=(n+1)%2;De.isEmpty(e.get(n,6))&&e.setNumber(n,6,o),De.isEmpty(e.get(6,n))&&e.setNumber(6,n,o)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new dt;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,o){for(let s=0;s<8;++s){if(!De.isEmpty(o.get(e+s,n)))throw new dt;o.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,o){for(let s=0;s<7;++s){if(!De.isEmpty(o.get(e,n+s)))throw new dt;o.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,o){for(let s=0;s<5;++s){const a=De.POSITION_ADJUSTMENT_PATTERN[s];for(let l=0;l<5;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPattern(e,n,o){for(let s=0;s<7;++s){const a=De.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)o.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=De.POSITION_DETECTION_PATTERN[0].length;De.embedPositionDetectionPattern(0,0,e),De.embedPositionDetectionPattern(e.getWidth()-n,0,e),De.embedPositionDetectionPattern(0,e.getWidth()-n,e);const o=8;De.embedHorizontalSeparationPattern(0,o-1,e),De.embedHorizontalSeparationPattern(e.getWidth()-o,o-1,e),De.embedHorizontalSeparationPattern(0,e.getWidth()-o,e);const s=7;De.embedVerticalSeparationPattern(s,0,e),De.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),De.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const o=e.getVersionNumber()-1,s=De.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[o];for(let a=0,l=s.length;a!==l;a++){const u=s[a];if(u>=0)for(let h=0;h!==l;h++){const p=s[h];p>=0&&De.isEmpty(n.get(p,u))&&De.embedPositionAdjustmentPattern(p-2,u-2,n)}}}}De.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])]),De.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])]),De.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])]),De.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])]),De.VERSION_INFO_POLY=7973,De.TYPE_INFO_POLY=1335,De.TYPE_INFO_MASK_PATTERN=21522;class md{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class xt{constructor(){}static calculateMaskPenalty(e){return Nt.applyMaskPenaltyRule1(e)+Nt.applyMaskPenaltyRule2(e)+Nt.applyMaskPenaltyRule3(e)+Nt.applyMaskPenaltyRule4(e)}static encode(e,n,o=null){let s=xt.DEFAULT_BYTE_MODE_ENCODING;const a=o!==null&&o.get(Bt.CHARACTER_SET)!==void 0;a&&(s=o.get(Bt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),u=new re;if(l===Re.BYTE&&(a||xt.DEFAULT_BYTE_MODE_ENCODING!==s)){const pe=z.getCharacterSetECIByName(s);pe!==void 0&&this.appendECI(pe,u)}this.appendModeInfo(l,u);const h=new re;this.appendBytes(e,l,h,s);let p;if(o!==null&&o.get(Bt.QR_VERSION)!==void 0){const pe=Number.parseInt(o.get(Bt.QR_VERSION).toString(),10);p=Ne.getVersionForNumber(pe);const ce=this.calculateBitsNeeded(l,u,h,p);if(!this.willFit(ce,p,n))throw new dt("Data too big for requested version")}else p=this.recommendVersion(n,l,u,h);const y=new re;y.appendBitArray(u);const b=l===Re.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(b,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),R=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(R,y);const U=this.interleaveWithECBytes(y,p.getTotalCodewords(),R,I.getNumBlocks()),V=new lr;V.setECLevel(n),V.setMode(l),V.setVersion(p);const H=p.getDimensionForVersion(),Q=new go(H,H),he=this.chooseMaskPattern(U,n,p,Q);return V.setMaskPattern(he),De.buildMatrix(U,n,p,he,Q),V.setMatrix(Q),V}static recommendVersion(e,n,o,s){const a=this.calculateBitsNeeded(n,o,s,Ne.getVersionForNumber(1)),l=this.chooseVersion(a,e),u=this.calculateBitsNeeded(n,o,s,l);return this.chooseVersion(u,e)}static calculateBitsNeeded(e,n,o,s){return n.getSize()+e.getCharacterCountBits(s)+o.getSize()}static getAlphanumericCode(e){return e<xt.ALPHANUMERIC_TABLE.length?xt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(z.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Re.KANJI;let o=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const u=e.charAt(a);if(xt.isDigit(u))o=!0;else if(this.getAlphanumericCode(u.charCodeAt(0))!==-1)s=!0;else return Re.BYTE}return s?Re.ALPHANUMERIC:o?Re.NUMERIC:Re.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=G.encode(e,z.SJIS)}catch{return!1}const o=n.length;if(o%2!==0)return!1;for(let s=0;s<o;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,o,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let u=0;u<lr.NUM_MASK_PATTERNS;u++){De.buildMatrix(e,n,o,u,s);let h=this.calculateMaskPenalty(s);h<a&&(a=h,l=u)}return l}static chooseVersion(e,n){for(let o=1;o<=40;o++){const s=Ne.getVersionForNumber(o);if(xt.willFit(e,s,n))return s}throw new dt("Data too big")}static willFit(e,n,o){const s=n.getTotalCodewords(),l=n.getECBlocksForLevel(o).getTotalECCodewords(),u=s-l,h=(e+7)/8;return u>=h}static terminateBits(e,n){const o=e*8;if(n.getSize()>o)throw new dt("data bits cannot fit in the QR Code"+n.getSize()+" > "+o);for(let l=0;l<4&&n.getSize()<o;++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()!==o)throw new dt("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,o,s,a,l){if(s>=o)throw new dt("Block ID too large");const u=e%o,h=o-u,p=Math.floor(e/o),y=p+1,b=Math.floor(n/o),I=b+1,R=p-b,U=y-I;if(R!==U)throw new dt("EC bytes mismatch");if(o!==h+u)throw new dt("RS blocks mismatch");if(e!==(b+R)*h+(I+U)*u)throw new dt("Total bytes mismatch");s<h?(a[0]=b,l[0]=R):(a[0]=I,l[0]=U)}static interleaveWithECBytes(e,n,o,s){if(e.getSizeInBytes()!==o)throw new dt("Number of bits and data bytes does not match");let a=0,l=0,u=0;const h=new Array;for(let y=0;y<s;++y){const b=new Int32Array(1),I=new Int32Array(1);xt.getNumDataBytesAndNumECBytesForBlockID(n,o,s,y,b,I);const R=b[0],U=new Uint8Array(R);e.toBytes(8*a,U,0,R);const V=xt.generateECBytes(U,I[0]);h.push(new md(U,V)),l=Math.max(l,R),u=Math.max(u,V.length),a+=b[0]}if(o!==a)throw new dt("Data bytes does not match offset");const p=new re;for(let y=0;y<l;++y)for(const b of h){const I=b.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<u;++y)for(const b of h){const I=b.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new dt("Interleaving error: "+n+" and "+p.getSizeInBytes()+" differ.");return p}static generateECBytes(e,n){const o=e.length,s=new Int32Array(o+n);for(let l=0;l<o;l++)s[l]=e[l]&255;new ti(Se.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[o+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,o,s){const a=o.getCharacterCountBits(n);if(e>=1<<a)throw new dt(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,o,s){switch(n){case Re.NUMERIC:xt.appendNumericBytes(e,o);break;case Re.ALPHANUMERIC:xt.appendAlphanumericBytes(e,o);break;case Re.BYTE:xt.append8BitBytes(e,o,s);break;case Re.KANJI:xt.appendKanjiBytes(e,o);break;default:throw new dt("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=xt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getDigit(e.charAt(s));if(s+2<o){const l=xt.getDigit(e.charAt(s+1)),u=xt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+u,10),s+=3}else if(s+1<o){const l=xt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const o=e.length;let s=0;for(;s<o;){const a=xt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new dt;if(s+1<o){const l=xt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new dt;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,o){let s;try{s=G.encode(e,o)}catch(a){throw new dt(a)}for(let a=0,l=s.length;a!==l;a++){const u=s[a];n.appendBits(u,8)}}static appendKanjiBytes(e,n){let o;try{o=G.encode(e,z.SJIS)}catch(a){throw new dt(a)}const s=o.length;for(let a=0;a<s;a+=2){const l=o[a]&255,u=o[a+1]&255,h=l<<8&4294967295|u;let p=-1;if(h>=33088&&h<=40956?p=h-33088:h>=57408&&h<=60351&&(p=h-49472),p===-1)throw new dt("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Re.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}xt.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]),xt.DEFAULT_BYTE_MODE_ENCODING=z.UTF8.getName();class cr{write(e,n,o,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||o<0)throw new A("Requested dimensions are too small: "+n+"x"+o);let a=pt.L,l=cr.QUIET_ZONE_SIZE;s!==null&&(s.get(Bt.ERROR_CORRECTION)!==void 0&&(a=pt.fromString(s.get(Bt.ERROR_CORRECTION).toString())),s.get(Bt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Bt.MARGIN).toString(),10)));const u=xt.encode(e,a,s);return this.renderResult(u,n,o,l)}writeToDom(e,n,o,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,o,s,a);e&&e.appendChild(l)}renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=this.createSVGElement(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)if(a.get(he,H)===1){const ce=this.createSvgRectElement(pe,Q,I,I);V.appendChild(ce)}return V}createSVGElement(e,n){const o=document.createElementNS(cr.SVG_NS,"svg");return o.setAttributeNS(null,"height",e.toString()),o.setAttributeNS(null,"width",n.toString()),o}createSvgRectElement(e,n,o,s){const a=document.createElementNS(cr.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",o.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}cr.QUIET_ZONE_SIZE=4,cr.SVG_NS="http://www.w3.org/2000/svg";class Er{encode(e,n,o,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(o<0||s<0)throw new A(`Requested dimensions are too small: ${o}x${s}`);let l=pt.L,u=Er.QUIET_ZONE_SIZE;a!==null&&(a.get(Bt.ERROR_CORRECTION)!==void 0&&(l=pt.fromString(a.get(Bt.ERROR_CORRECTION).toString())),a.get(Bt.MARGIN)!==void 0&&(u=Number.parseInt(a.get(Bt.MARGIN).toString(),10)));const h=xt.encode(e,l,a);return Er.renderResult(h,o,s,u)}static renderResult(e,n,o,s){const a=e.getMatrix();if(a===null)throw new St;const l=a.getWidth(),u=a.getHeight(),h=l+s*2,p=u+s*2,y=Math.max(n,h),b=Math.max(o,p),I=Math.min(Math.floor(y/h),Math.floor(b/p)),R=Math.floor((y-l*I)/2),U=Math.floor((b-u*I)/2),V=new te(y,b);for(let H=0,Q=U;H<u;H++,Q+=I)for(let he=0,pe=R;he<l;he++,pe+=I)a.get(he,H)===1&&V.setRegion(pe,Q,I,I);return V}}Er.QUIET_ZONE_SIZE=4;class gd{encode(e,n,o,s,a){let l;switch(n){case ie.QR_CODE:l=new Er;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,o,s,a)}}class On extends Te{constructor(e,n,o,s,a,l,u,h){if(super(l,u),this.yuvData=e,this.dataWidth=n,this.dataHeight=o,this.left=s,this.top=a,s+l>n||a+u>o)throw new A("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,u)}getRow(e,n){if(e<0||e>=this.getHeight())throw new A("Requested row is outside the image: "+e);const o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.yuvData,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.yuvData;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.yuvData,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.yuvData,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new On(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,o,s,!1)}renderThumbnail(){const e=this.getWidth()/On.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/On.THUMBNAIL_SCALE_FACTOR,o=new Int32Array(e*n),s=this.yuvData;let a=this.top*this.dataWidth+this.left;for(let l=0;l<n;l++){const u=l*e;for(let h=0;h<e;h++){const p=s[a+h*On.THUMBNAIL_SCALE_FACTOR]&255;o[u+h]=4278190080|p*65793}a+=this.dataWidth*On.THUMBNAIL_SCALE_FACTOR}return o}getThumbnailWidth(){return this.getWidth()/On.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/On.THUMBNAIL_SCALE_FACTOR}reverseHorizontal(e,n){const o=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 u=a,h=a+e-1;u<l;u++,h--){const p=o[u];o[u]=o[h],o[h]=p}}}invert(){return new Je(this)}}On.THUMBNAIL_SCALE_FACTOR=2;class ni extends Te{constructor(e,n,o,s,a,l,u){if(super(n,o),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=u,e.BYTES_PER_ELEMENT===4){const h=n*o,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const b=e[y],I=b>>16&255,R=b>>7&510,U=b&255;p[y]=(I+R+U)/4&255}this.luminances=p}else this.luminances=e;if(s===void 0&&(this.dataWidth=n),a===void 0&&(this.dataHeight=o),l===void 0&&(this.left=0),u===void 0&&(this.top=0),this.left+n>this.dataWidth||this.top+o>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 o=this.getWidth();(n==null||n.length<o)&&(n=new Uint8ClampedArray(o));const s=(e+this.top)*this.dataWidth+this.left;return P.arraycopy(this.luminances,s,n,0,o),n}getMatrix(){const e=this.getWidth(),n=this.getHeight();if(e===this.dataWidth&&n===this.dataHeight)return this.luminances;const o=e*n,s=new Uint8ClampedArray(o);let a=this.top*this.dataWidth+this.left;if(e===this.dataWidth)return P.arraycopy(this.luminances,a,s,0,o),s;for(let l=0;l<n;l++){const u=l*e;P.arraycopy(this.luminances,a,s,u,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,o,s){return new ni(this.luminances,o,s,this.dataWidth,this.dataHeight,this.left+e,this.top+n)}invert(){return new Je(this)}}class ys extends z{static forName(e){return this.getCharacterSetECIByName(e)}}class ri{}ri.ISO_8859_1=z.ISO8859_1;class ws{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 _s{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class xd{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Ir extends xd{constructor(e,n,o){super(e),this.value=n,this.bitCount=o}appendTo(e,n){e.appendBits(this.value,this.bitCount)}add(e,n){return new Ir(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new Ir(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+F.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class oi extends Ir{constructor(e,n,o){super(e,0,0),this.binaryShiftStart=n,this.binaryShiftByteCount=o}appendTo(e,n){for(let o=0;o<this.binaryShiftByteCount;o++)(o===0||o===31&&this.binaryShiftByteCount<=62)&&(e.appendBits(31,5),this.binaryShiftByteCount>62?e.appendBits(this.binaryShiftByteCount-31,16):o===0?e.appendBits(Math.min(this.binaryShiftByteCount,31),5):e.appendBits(this.binaryShiftByteCount-31,5)),e.appendBits(n[this.binaryShiftStart+o],8)}addBinaryShift(e,n){return new oi(this,e,n)}toString(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"}}function yd(C,e,n){return new oi(C,e,n)}function zr(C,e,n){return new Ir(C,e,n)}const wd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Yn=0,xo=1,gn=2,vs=3,kn=4,_d=new Ir(null,0,0),ii=[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 vd(C){for(let e of C)$.fill(e,-1);return C[Yn][kn]=0,C[xo][kn]=0,C[xo][Yn]=28,C[vs][kn]=0,C[gn][kn]=0,C[gn][Yn]=15,C}const Cs=vd($.createInt32Array(6,6));class Rn{constructor(e,n,o,s){this.token=e,this.mode=n,this.binaryShiftByteCount=o,this.bitCount=s}getMode(){return this.mode}getToken(){return this.token}getBinaryShiftByteCount(){return this.binaryShiftByteCount}getBitCount(){return this.bitCount}latchAndAppend(e,n){let o=this.bitCount,s=this.token;if(e!==this.mode){let l=ii[this.mode][e];s=zr(s,l&65535,l>>16),o+=l>>16}let a=e===gn?4:5;return s=zr(s,n,a),new Rn(s,e,0,o+a)}shiftAndAppend(e,n){let o=this.token,s=this.mode===gn?4:5;return o=zr(o,Cs[this.mode][e],s),o=zr(o,n,5),new Rn(o,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,o=this.mode,s=this.bitCount;if(this.mode===kn||this.mode===gn){let u=ii[o][Yn];n=zr(n,u&65535,u>>16),s+=u>>16,o=Yn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Rn(n,o,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=yd(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Rn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(ii[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 o=new re;for(const s of n)s.appendTo(o,e);return o}toString(){return me.format("%s bits=%d bytes=%d",wd[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(_d,Yn,0,0);function Cd(C){const e=me.getCharCode(" "),n=me.getCharCode("."),o=me.getCharCode(",");C[Yn][e]=1;const s=me.getCharCode("Z"),a=me.getCharCode("A");for(let I=a;I<=s;I++)C[Yn][I]=I-a+2;C[xo][e]=1;const l=me.getCharCode("z"),u=me.getCharCode("a");for(let I=u;I<=l;I++)C[xo][I]=I-u+2;C[gn][e]=1;const h=me.getCharCode("9"),p=me.getCharCode("0");for(let I=p;I<=h;I++)C[gn][I]=I-p+2;C[gn][o]=12,C[gn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
80
+ `,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)C[vs][me.getCharCode(y[I])]=I;const b=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<b.length;I++)me.getCharCode(b[I])>0&&(C[kn][me.getCharCode(b[I])]=I);return C}const si=Cd($.createInt32Array(5,256));class Vr{constructor(e){this.text=e}encode(){const e=me.getCharCode(" "),n=me.getCharCode(`
81
+ `);let o=_s.singletonList(Rn.INITIAL_STATE);for(let a=0;a<this.text.length;a++){let l,u=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case me.getCharCode("\r"):l=u===n?2:0;break;case me.getCharCode("."):l=u===e?3:0;break;case me.getCharCode(","):l=u===e?4:0;break;case me.getCharCode(":"):l=u===e?5:0;break;default:l=0}l>0?(o=Vr.updateStateListForPair(o,a,l),a++):o=this.updateStateListForChar(o,a)}return _s.min(o,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const o=[];for(let s of e)this.updateStateForChar(s,n,o);return Vr.simplifyStates(o)}updateStateForChar(e,n,o){let s=this.text[n]&255,a=si[e.getMode()][s]>0,l=null;for(let u=0;u<=kn;u++){let h=si[u][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||u===e.getMode()||u===gn){const p=l.latchAndAppend(u,h);o.push(p)}if(!a&&Cs[e.getMode()][u]>=0){const p=l.shiftAndAppend(u,h);o.push(p)}}}if(e.getBinaryShiftByteCount()>0||si[e.getMode()][s]===0){let u=e.addBinaryShiftChar(n);o.push(u)}}static updateStateListForPair(e,n,o){const s=[];for(let a of e)this.updateStateForPair(a,n,o,s);return this.simplifyStates(s)}static updateStateForPair(e,n,o,s){let a=e.endBinaryShift(n);if(s.push(a.latchAndAppend(kn,o)),e.getMode()!==kn&&s.push(a.shiftAndAppend(kn,o)),o===3||o===4){let l=a.latchAndAppend(gn,16-o).latchAndAppend(gn,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 o of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(o)){s=!1;break}o.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(o)}return n}}class tt{constructor(){}static encodeBytes(e){return tt.encode(e,tt.DEFAULT_EC_PERCENT,tt.DEFAULT_AZTEC_LAYERS)}static encode(e,n,o){let s=new Vr(e).encode(),a=F.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,u,h,p,y,b;if(o!==tt.DEFAULT_AZTEC_LAYERS){if(u=o<0,h=Math.abs(o),h>(u?tt.MAX_NB_BITS_COMPACT:tt.MAX_NB_BITS))throw new A(me.format("Illegal value %s for layers",o));p=tt.totalBitsInLayer(h,u),y=tt.WORD_SIZE[h];let ce=p-p%y;if(b=tt.stuffBits(s,y),b.getSize()+a>ce)throw new A("Data to large for user specified layer");if(u&&b.getSize()>y*64)throw new A("Data to large for user specified layer")}else{y=0,b=null;for(let ce=0;;ce++){if(ce>tt.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(u=ce<=3,h=u?ce+1:ce,p=tt.totalBitsInLayer(h,u),l>p)continue;(b==null||y!==tt.WORD_SIZE[h])&&(y=tt.WORD_SIZE[h],b=tt.stuffBits(s,y));let Ke=p-p%y;if(!(u&&b.getSize()>y*64)&&b.getSize()+a<=Ke)break}}let I=tt.generateCheckWords(b,p,y),R=b.getSize()/y,U=tt.generateModeMessage(u,h,R),V=(u?11:14)+h*4,H=new Int32Array(V),Q;if(u){Q=V;for(let ce=0;ce<H.length;ce++)H[ce]=ce}else{Q=V+1+2*F.truncDivision(F.truncDivision(V,2)-1,15);let ce=F.truncDivision(V,2),Ke=F.truncDivision(Q,2);for(let He=0;He<ce;He++){let tn=He+F.truncDivision(He,15);H[ce-He-1]=Ke-tn-1,H[ce+He]=Ke+tn+1}}let he=new te(Q);for(let ce=0,Ke=0;ce<h;ce++){let He=(h-ce)*4+(u?9:12);for(let tn=0;tn<He;tn++){let yn=tn*2;for(let nn=0;nn<2;nn++)I.get(Ke+yn+nn)&&he.set(H[ce*2+nn],H[ce*2+tn]),I.get(Ke+He*2+yn+nn)&&he.set(H[ce*2+tn],H[V-1-ce*2-nn]),I.get(Ke+He*4+yn+nn)&&he.set(H[V-1-ce*2-nn],H[V-1-ce*2-tn]),I.get(Ke+He*6+yn+nn)&&he.set(H[V-1-ce*2-tn],H[ce*2+nn])}Ke+=He*8}if(tt.drawModeMessage(he,u,Q,U),u)tt.drawBullsEye(he,F.truncDivision(Q,2),5);else{tt.drawBullsEye(he,F.truncDivision(Q,2),7);for(let ce=0,Ke=0;ce<F.truncDivision(V,2)-1;ce+=15,Ke+=16)for(let He=F.truncDivision(Q,2)&1;He<Q;He+=2)he.set(F.truncDivision(Q,2)-Ke,He),he.set(F.truncDivision(Q,2)+Ke,He),he.set(He,F.truncDivision(Q,2)-Ke),he.set(He,F.truncDivision(Q,2)+Ke)}let pe=new ws;return pe.setCompact(u),pe.setSize(Q),pe.setLayers(h),pe.setCodeWords(R),pe.setMatrix(he),pe}static drawBullsEye(e,n,o){for(let s=0;s<o;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-o,n-o),e.set(n-o+1,n-o),e.set(n-o,n-o+1),e.set(n+o,n-o),e.set(n+o,n-o+1),e.set(n+o,n+o-1)}static generateModeMessage(e,n,o){let s=new re;return e?(s.appendBits(n-1,2),s.appendBits(o-1,6),s=tt.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(o-1,11),s=tt.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,o,s){let a=F.truncDivision(o,2);if(n)for(let l=0;l<7;l++){let u=a-3+l;s.get(l)&&e.set(u,a-5),s.get(l+7)&&e.set(a+5,u),s.get(20-l)&&e.set(u,a+5),s.get(27-l)&&e.set(a-5,u)}else for(let l=0;l<10;l++){let u=a-5+l+F.truncDivision(l,5);s.get(l)&&e.set(u,a-7),s.get(l+10)&&e.set(a+7,u),s.get(29-l)&&e.set(u,a+7),s.get(39-l)&&e.set(a-7,u)}}static generateCheckWords(e,n,o){let s=e.getSize()/o,a=new ti(tt.getGF(o)),l=F.truncDivision(n,o),u=tt.bitsToWords(e,o,l);a.encode(u,l-s);let h=n%o,p=new re;p.appendBits(0,h);for(const y of Array.from(u))p.appendBits(y,o);return p}static bitsToWords(e,n,o){let s=new Int32Array(o),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let u=0;for(let h=0;h<n;h++)u|=e.get(a*n+h)?1<<n-h-1:0;s[a]=u}return s}static getGF(e){switch(e){case 4:return Se.AZTEC_PARAM;case 6:return Se.AZTEC_DATA_6;case 8:return Se.AZTEC_DATA_8;case 10:return Se.AZTEC_DATA_10;case 12:return Se.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let o=new re,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let u=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(u|=1<<n-1-h);(u&a)===a?(o.appendBits(u&a,n),l--):(u&a)===0?(o.appendBits(u|1,n),l--):o.appendBits(u,n)}return o}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}tt.DEFAULT_EC_PERCENT=33,tt.DEFAULT_AZTEC_LAYERS=0,tt.MAX_NB_BITS=32,tt.MAX_NB_BITS_COMPACT=4,tt.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 yo{encode(e,n,o,s){return this.encodeWithHints(e,n,o,s,null)}encodeWithHints(e,n,o,s,a){let l=ri.ISO_8859_1,u=tt.DEFAULT_EC_PERCENT,h=tt.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Bt.CHARACTER_SET)&&(l=ys.forName(a.get(Bt.CHARACTER_SET).toString())),a.has(Bt.ERROR_CORRECTION)&&(u=F.parseInt(a.get(Bt.ERROR_CORRECTION).toString())),a.has(Bt.AZTEC_LAYERS)&&(h=F.parseInt(a.get(Bt.AZTEC_LAYERS).toString()))),yo.encodeLayers(e,n,o,s,l,u,h)}static encodeLayers(e,n,o,s,a,l,u){if(n!==ie.AZTEC)throw new A("Can only encode AZTEC, but got "+n);let h=tt.encode(me.getBytes(e,a),l,u);return yo.renderResult(h,o,s)}static renderResult(e,n,o){let s=e.getMatrix();if(s==null)throw new St;let a=s.getWidth(),l=s.getHeight(),u=Math.max(n,a),h=Math.max(o,l),p=Math.min(u/a,h/l),y=(u-a*p)/2,b=(h-l*p)/2,I=new te(u,h);for(let R=0,U=b;R<l;R++,U+=p)for(let V=0,H=y;V<a;V++,H+=p)s.get(V,R)&&I.setRegion(H,U,p,p);return I}}i.AbstractExpandedDecoder=Ho,i.ArgumentException=E,i.ArithmeticException=ye,i.AztecCode=ws,i.AztecCodeReader=Ln,i.AztecCodeWriter=yo,i.AztecDecoder=nt,i.AztecDetector=or,i.AztecDetectorResult=$n,i.AztecEncoder=tt,i.AztecHighLevelEncoder=Vr,i.AztecPoint=At,i.BarcodeFormat=ie,i.Binarizer=S,i.BinaryBitmap=D,i.BitArray=re,i.BitMatrix=te,i.BitSource=Xo,i.BrowserAztecCodeReader=wr,i.BrowserBarcodeReader=Qu,i.BrowserCodeReader=Ze,i.BrowserDatamatrixCodeReader=td,i.BrowserMultiFormatReader=fd,i.BrowserPDF417Reader=hd,i.BrowserQRCodeReader=pd,i.BrowserQRCodeSvgWriter=cr,i.CharacterSetECI=z,i.ChecksumException=T,i.Code128Reader=ge,i.Code39Reader=O,i.DataMatrixDecodedBitStreamParser=Wn,i.DataMatrixReader=Gn,i.DecodeHintType=B,i.DecoderResult=Pe,i.DefaultGridSampler=rr,i.DetectorResult=Bn,i.EAN13Reader=Fn,i.EncodeHintType=Bt,i.Exception=g,i.FormatException=L,i.GenericGF=Se,i.GenericGFPoly=J,i.GlobalHistogramBinarizer=ke,i.GridSampler=jn,i.GridSamplerInstance=sn,i.HTMLCanvasElementLuminanceSource=xe,i.HybridBinarizer=le,i.ITFReader=ne,i.IllegalArgumentException=A,i.IllegalStateException=St,i.InvertedLuminanceSource=Je,i.LuminanceSource=Te,i.MathUtils=Xe,i.MultiFormatOneDReader=br,i.MultiFormatReader=xs,i.MultiFormatWriter=gd,i.NotFoundException=q,i.OneDReader=gt,i.PDF417DecodedBitStreamParser=K,i.PDF417DecoderErrorCorrection=ds,i.PDF417Reader=jt,i.PDF417ResultMetadata=hs,i.PerspectiveTransform=Ft,i.PlanarYUVLuminanceSource=On,i.QRCodeByteMatrix=go,i.QRCodeDataMask=pn,i.QRCodeDecodedBitStreamParser=Et,i.QRCodeDecoderErrorCorrectionLevel=pt,i.QRCodeDecoderFormatInformation=Gt,i.QRCodeEncoder=xt,i.QRCodeEncoderQRCode=lr,i.QRCodeMaskUtil=Nt,i.QRCodeMatrixUtil=De,i.QRCodeMode=Re,i.QRCodeReader=qn,i.QRCodeVersion=Ne,i.QRCodeWriter=Er,i.RGBLuminanceSource=ni,i.RSS14Reader=Tt,i.RSSExpandedReader=se,i.ReaderException=mo,i.ReedSolomonDecoder=vt,i.ReedSolomonEncoder=ti,i.ReedSolomonException=Ve,i.Result=qe,i.ResultMetadataType=_e,i.ResultPoint=be,i.StringUtils=me,i.UnsupportedOperationException=we,i.VideoInputDevice=$e,i.WhiteRectangleDetector=qt,i.WriterException=dt,i.ZXingArrays=$,i.ZXingCharset=ys,i.ZXingInteger=F,i.ZXingStandardCharsets=ri,i.ZXingStringBuilder=fe,i.ZXingStringEncoding=G,i.ZXingSystem=P,i.createAbstractExpandedDecoder=cs,Object.defineProperty(i,"__esModule",{value:!0})}))})(qr,qr.exports)),qr.exports}var yt=aw();const lw=iw(yt),cw=Td({__proto__:null,default:lw},[yt]);var dl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,yt.BarcodeFormat.QR_CODE],[Ce.AZTEC,yt.BarcodeFormat.AZTEC],[Ce.CODABAR,yt.BarcodeFormat.CODABAR],[Ce.CODE_39,yt.BarcodeFormat.CODE_39],[Ce.CODE_93,yt.BarcodeFormat.CODE_93],[Ce.CODE_128,yt.BarcodeFormat.CODE_128],[Ce.DATA_MATRIX,yt.BarcodeFormat.DATA_MATRIX],[Ce.MAXICODE,yt.BarcodeFormat.MAXICODE],[Ce.ITF,yt.BarcodeFormat.ITF],[Ce.EAN_13,yt.BarcodeFormat.EAN_13],[Ce.EAN_8,yt.BarcodeFormat.EAN_8],[Ce.PDF_417,yt.BarcodeFormat.PDF_417],[Ce.RSS_14,yt.BarcodeFormat.RSS_14],[Ce.RSS_EXPANDED,yt.BarcodeFormat.RSS_EXPANDED],[Ce.UPC_A,yt.BarcodeFormat.UPC_A],[Ce.UPC_E,yt.BarcodeFormat.UPC_E],[Ce.UPC_EAN_EXTENSION,yt.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!cw)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=i,this.logger=c;var d=this.createZXingFormats(r),f=new Map;f.set(yt.DecodeHintType.POSSIBLE_FORMATS,d),f.set(yt.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var i=this;return new Promise(function(c,d){try{c(i.decode(r))}catch(f){d(f)}})},t.prototype.decode=function(r){var i=new yt.MultiFormatReader(this.verbose,this.hints),c=new yt.HTMLCanvasElementLuminanceSource(r),d=new yt.BinaryBitmap(new yt.HybridBinarizer(c)),f=i.decode(d);return{text:f.text,format:Hu.create(this.toHtml5QrcodeSupportedFormats(f.format)),debugData:this.createDebugData()}},t.prototype.createReverseFormatMap=function(){var r=new Map;return this.formatMap.forEach(function(i,c,d){r.set(i,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 i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.logError("".concat(f," is not supported by")+"ZXingHtml5QrcodeShim")}return i},t.prototype.createDebugData=function(){return{decoderName:"zxing-js"}},t})(),uw=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},dw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,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(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fl=(function(){function t(r,i,c){if(this.formatMap=new Map([[Ce.QR_CODE,"qr_code"],[Ce.AZTEC,"aztec"],[Ce.CODABAR,"codabar"],[Ce.CODE_39,"code_39"],[Ce.CODE_93,"code_93"],[Ce.CODE_128,"code_128"],[Ce.DATA_MATRIX,"data_matrix"],[Ce.ITF,"itf"],[Ce.EAN_13,"ean_13"],[Ce.EAN_8,"ean_8"],[Ce.PDF_417,"pdf417"],[Ce.UPC_A,"upc_a"],[Ce.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=i,this.logger=c;var d=this.createBarcodeDetectorFormats(r);if(this.detector=new BarcodeDetector(d),!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 uw(this,void 0,void 0,function(){var i,c;return dw(this,function(d){switch(d.label){case 0:return[4,this.detector.detect(r)];case 1:if(i=d.sent(),!i||i.length===0)throw"No barcode or QR code detected.";return c=this.selectLargestBarcode(i),[2,{text:c.rawValue,format:Hu.create(this.toHtml5QrcodeSupportedFormats(c.format)),debugData:this.createDebugData()}]}})})},t.prototype.selectLargestBarcode=function(r){for(var i=null,c=0,d=0,f=r;d<f.length;d++){var m=f[d],x=m.boundingBox.width*m.boundingBox.height;x>c&&(c=x,i=m)}if(!i)throw"No largest barcode found";return i},t.prototype.createBarcodeDetectorFormats=function(r){for(var i=[],c=0,d=r;c<d.length;c++){var f=d[c];this.formatMap.has(f)?i.push(this.formatMap.get(f)):this.logger.warn("".concat(f," is not supported by")+"BarcodeDetectorDelegate")}return{formats:i}},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(i,c,d){r.set(i,c)}),r},t.prototype.createDebugData=function(){return{decoderName:"BarcodeDetector"}},t})(),hl=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},pl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,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(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},fw=(function(){function t(r,i,c,d){this.EXECUTIONS_TO_REPORT_PERFORMANCE=100,this.executions=0,this.executionResults=[],this.wasPrimaryDecoderUsedInLastDecode=!1,this.verbose=c,i&&fl.isSupported()?(this.primaryDecoder=new fl(r,c,d),this.secondaryDecoder=new dl(r,c,d)):this.primaryDecoder=new dl(r,c,d)}return t.prototype.decodeAsync=function(r){return hl(this,void 0,void 0,function(){var i;return pl(this,function(c){switch(c.label){case 0:i=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(i),[7];case 4:return[2]}})})},t.prototype.decodeRobustlyAsync=function(r){return hl(this,void 0,void 0,function(){var i,c;return pl(this,function(d){switch(d.label){case 0:i=performance.now(),d.label=1;case 1:return d.trys.push([1,3,4,5]),[4,this.primaryDecoder.decodeAsync(r)];case 2:return[2,d.sent()];case 3:if(c=d.sent(),this.secondaryDecoder)return[2,this.secondaryDecoder.decodeAsync(r)];throw c;case 4:return this.possiblyLogPerformance(i),[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 i=performance.now()-r;this.executionResults.push(i),this.executions++,this.possiblyFlushPerformanceReport()}},t.prototype.possiblyFlushPerformanceReport=function(){if(!(this.executions<this.EXECUTIONS_TO_REPORT_PERFORMANCE)){for(var r=0,i=0,c=this.executionResults;i<c.length;i++){var d=c[i];r+=d}var f=r/this.executionResults.length;console.log("".concat(f," ms for ").concat(this.executionResults.length," last runs.")),this.executions=0,this.executionResults=[]}},t})(),os=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),Bo=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},Lo=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,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(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Gu=(function(){function t(r,i){this.name=r,this.track=i}return t.prototype.isSupported=function(){return this.track.getCapabilities?this.name in this.track.getCapabilities():!1},t.prototype.apply=function(r){var i={};i[this.name]=r;var c={advanced:[i]};return this.track.applyConstraints(c)},t.prototype.value=function(){var r=this.track.getSettings();if(this.name in r){var i=r[this.name];return i}return null},t})(),hw=(function(t){os(r,t);function r(i,c){return t.call(this,i,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(i){var c={};c[this.name]=i;var d={advanced:[c]};return this.track.applyConstraints(d)},r.prototype.getCapabilities=function(){this.failIfNotSupported();var i=this.track.getCapabilities(),c=i[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})(Gu),pw=(function(t){os(r,t);function r(i){return t.call(this,"zoom",i)||this}return r})(hw),mw=(function(t){os(r,t);function r(i){return t.call(this,"torch",i)||this}return r})(Gu),gw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new pw(this.track)},t.prototype.torchFeature=function(){return new mw(this.track)},t})(),xw=(function(){function t(r,i,c){this.isClosed=!1,this.parentElement=r,this.mediaStream=i,this.callbacks=c,this.surface=this.createVideoElement(this.parentElement.clientWidth),r.append(this.surface)}return t.prototype.createVideoElement=function(r){var i=document.createElement("video");return i.style.width="".concat(r,"px"),i.style.display="block",i.muted=!0,i.setAttribute("muted","true"),i.playsInline=!0,i},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 i=function(){var c=r.surface.clientWidth,d=r.surface.clientHeight;r.callbacks.onRenderSurfaceReady(c,d),r.surface.removeEventListener("playing",i)};this.surface.addEventListener("playing",i),this.surface.srcObject=this.mediaStream,this.surface.play()},t.create=function(r,i,c,d){return Bo(this,void 0,void 0,function(){var f,m;return Lo(this,function(x){switch(x.label){case 0:return f=new t(r,i,d),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 i=this,c=function(){setTimeout(r,200),i.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 Bo(this,void 0,void 0,function(){return Lo(this,function(i){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(i,c){var d=r.mediaStream.getVideoTracks(),f=d.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),i())})})},t.prototype.getCapabilities=function(){return new gw(this.getFirstTrackOrFail())},t})(),yw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,i,c){return Bo(this,void 0,void 0,function(){return Lo(this,function(d){return[2,xw.create(r,this.mediaStream,i,c)]})})},t.create=function(r){return Bo(this,void 0,void 0,function(){var i,c;return Lo(this,function(d){switch(d.label){case 0:if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return i={audio:!1,video:r},[4,navigator.mediaDevices.getUserMedia(i)];case 1:return c=d.sent(),[2,new t(c)]}})})},t})(),ml=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},gl=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,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(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},ww=(function(){function t(){}return t.failIfNotSupported=function(){return ml(this,void 0,void 0,function(){return gl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return ml(this,void 0,void 0,function(){return gl(this,function(i){return[2,yw.create(r)]})})},t})(),_w=function(t,r,i,c){function d(f){return f instanceof i?f:new i(function(m){m(f)})}return new(i||(i=Promise))(function(f,m){function x(E){try{g(c.next(E))}catch(A){m(A)}}function v(E){try{g(c.throw(E))}catch(A){m(A)}}function g(E){E.done?f(E.value):d(E.value).then(x,v)}g((c=c.apply(t,r||[])).next())})},vw=function(t,r){var i={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,d,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(E){return v([g,E])}}function v(g){if(c)throw new TypeError("Generator is already executing.");for(;m&&(m=0,g[0]&&(i=0)),i;)try{if(c=1,d&&(f=g[0]&2?d.return:g[0]?d.throw||((f=d.return)&&f.call(d),0):d.next)&&!(f=f.call(d,g[1])).done)return f;switch(d=0,f&&(g=[g[0]&2,f.value]),g[0]){case 0:case 1:f=g;break;case 4:return i.label++,{value:g[1],done:!1};case 5:i.label++,d=g[1],g=[0];continue;case 7:g=i.ops.pop(),i.trys.pop();continue;default:if(f=i.trys,!(f=f.length>0&&f[f.length-1])&&(g[0]===6||g[0]===2)){i=0;continue}if(g[0]===3&&(!f||g[1]>f[0]&&g[1]<f[3])){i.label=g[1];break}if(g[0]===6&&i.label<f[1]){i.label=f[1],f=g;break}if(f&&i.label<f[2]){i.label=f[2],i.ops.push(g);break}f[2]&&i.ops.pop(),i.trys.pop();continue}g=r.call(t,i)}catch(E){g=[6,E],d=0}finally{c=f=0}if(g[0]&5)throw g[1];return{value:g[0]?g[1]:void 0,done:!0}}},Cw=(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=Rr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Rr.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 _w(this,void 0,void 0,function(){var r,i,c,d,f,m,x;return vw(this,function(v){switch(v.label){case 0:return r=function(g){for(var E=g.getVideoTracks(),A=0,D=E;A<D.length;A++){var T=D[A];T.enabled=!1,T.stop(),g.removeTrack(T)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return i=v.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=v.sent(),d=[],f=0,m=c;f<m.length;f++)x=m[f],x.kind==="videoinput"&&d.push({id:x.deviceId,label:x.label});return r(i),[2,d]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,i){var c=function(f){for(var m=[],x=0,v=f;x<v.length;x++){var g=v[x];g.kind==="video"&&m.push({id:g.id,label:g.label})}r(m)},d=MediaStreamTrack;d.getSources(c)})},t})(),Ot;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(Ot||(Ot={}));var bw=(function(){function t(){this.state=Ot.NOT_STARTED,this.onGoingTransactionNewState=Ot.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===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=Ot.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===Ot.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=Ot.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==Ot.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case Ot.UNKNOWN:throw"Transition from unknown is not allowed";case Ot.NOT_STARTED:this.failIfNewStateIs(r,[Ot.PAUSED]);break;case Ot.SCANNING:break;case Ot.PAUSED:break}},t.prototype.failIfNewStateIs=function(r,i){for(var c=0,d=i;c<d.length;c++){var f=d[c];if(r===f)throw"Cannot transition from ".concat(this.state," to ").concat(r)}},t})(),Aw=(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()===Ot.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==Ot.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===Ot.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===Ot.PAUSED},t})(),Ew=(function(){function t(){}return t.create=function(){return new Aw(new bw)},t})(),Iw=(function(){var t=function(r,i){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,d){c.__proto__=d}||function(c,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(c[f]=d[f])},t(r,i)};return function(r,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");t(r,i);function c(){this.constructor=r}r.prototype=i===null?Object.create(i):(c.prototype=i.prototype,new c)}})(),ln=(function(t){Iw(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})(nw),Sw=(function(){function t(r,i){this.logger=i,this.fps=ln.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=ln.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Wu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!zn(this.qrbox)},t.create=function(r,i){return new t(r,i)},t})(),xl=(function(){function t(r,i){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 i=="boolean"?this.verbose=i===!0:i&&(c=i,this.verbose=c.verbose===!0,c.experimentalFeatures),this.logger=new ow(this.verbose),this.qrcode=new fw(this.getSupportedFormats(i),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Ew.create()}return t.prototype.start=function(r,i,c,d){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;d?m=d:m=this.verbose?this.logger.log:function(){};var x=Sw.create(i,this.logger);this.clearElement();var v=!1;x.videoConstraints&&(x.isMediaStreamConstraintsValid()?v=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var g=v,E=document.getElementById(this.elementId);E.clientWidth?E.clientWidth:ln.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,D=this.stateManagerProxy.startTransition(Ot.SCANNING);return new Promise(function(T,S){var P=g?x.videoConstraints:A.createVideoConstraints(r);if(!P){D.cancel(),S("videoConstraints should be defined");return}var M={};(!g||x.aspectRatio)&&(M.aspectRatio=x.aspectRatio);var ee={onRenderSurfaceReady:function($,F){A.setupUi($,F,x),A.isScanning=!0,A.foreverScan(x,c,m)}};ww.failIfNotSupported().then(function($){$.create(P).then(function(F){return F.render(f.element,M,ee).then(function(re){A.renderedCamera=re,D.execute(),T(null)}).catch(function(re){D.cancel(),S(re)})}).catch(function(F){D.cancel(),S(Rr.errorGettingUserMedia(F))})}).catch(function($){D.cancel(),S(Rr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(Ot.PAUSED),this.showPausedState(),(zn(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,i=function(){r.stateManagerProxy.directTransition(Ot.SCANNING),r.hidePausedState()};if(!this.renderedCamera.isPaused()){i();return}this.renderedCamera.resume(function(){i()})},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 i=this.stateManagerProxy.startTransition(Ot.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(ln.SHADED_REGION_ELEMENT_ID);f&&r.element.removeChild(f)}},d=this;return this.renderedCamera.close().then(function(){return d.renderedCamera=null,d.element&&(d.element.removeChild(d.canvasElement),d.canvasElement=null),c(),d.qrRegion&&(d.qrRegion=null),d.context&&(d.context=null),i.execute(),d.hidePausedState(),d.isScanning=!1,Promise.resolve()})},t.prototype.scanFile=function(r,i){return this.scanFileV2(r,i).then(function(c){return c.decodedText})},t.prototype.scanFileV2=function(r,i){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(zn(i)&&(i=!0),!this.stateManagerProxy.canScanFile())throw"Cannot start file scan - ongoing camera scan";return new Promise(function(d,f){c.possiblyCloseLastScanImageFile(),c.clearElement(),c.lastScanImageFile=URL.createObjectURL(r);var m=new Image;m.onload=function(){var x=m.width,v=m.height,g=document.getElementById(c.elementId),E=g.clientWidth?g.clientWidth:ln.DEFAULT_WIDTH,A=Math.max(g.clientHeight?g.clientHeight:v,ln.FILE_SCAN_MIN_HEIGHT),D=c.computeCanvasDrawConfig(x,v,E,A);if(i){var T=c.createCanvasElement(E,A,"qr-canvas-visible");T.style.display="inline-block",g.appendChild(T);var S=T.getContext("2d");if(!S)throw"Unable to get 2d context from canvas";S.canvas.width=E,S.canvas.height=A,S.drawImage(m,0,0,x,v,D.x,D.y,D.width,D.height)}var P=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,M=Math.max(m.width,D.width),ee=Math.max(m.height,D.height),$=M+2*P,F=ee+2*P,re=c.createCanvasElement($,F);g.appendChild(re);var Z=re.getContext("2d");if(!Z)throw"Unable to get 2d context from canvas";Z.canvas.width=$,Z.canvas.height=F,Z.drawImage(m,0,0,x,v,P,P,M,ee);try{c.qrcode.decodeRobustlyAsync(re).then(function(B){d(cl.createFromQrcodeResult(B))}).catch(f)}catch(B){f("QR code parse error, error = ".concat(B))}},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 Cw.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(!Wu.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 i=[Ce.QR_CODE,Ce.AZTEC,Ce.CODABAR,Ce.CODE_39,Ce.CODE_93,Ce.CODE_128,Ce.DATA_MATRIX,Ce.MAXICODE,Ce.ITF,Ce.EAN_13,Ce.EAN_8,Ce.PDF_417,Ce.RSS_14,Ce.RSS_EXPANDED,Ce.UPC_A,Ce.UPC_E,Ce.UPC_EAN_EXTENSION];if(!r||typeof r=="boolean"||!r.formatsToSupport)return i;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=[],d=0,f=r.formatsToSupport;d<f.length;d++){var m=f[d];tw(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(zn(r))return!0;if(!zn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(zn(r.experimentalFeatures))return!0;var i=r.experimentalFeatures;return zn(i.useBarCodeDetectorIfSupported)?!0:i.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,i,c){var d=this,f=c.qrbox;this.validateQrboxConfig(f);var m=this.toQrdimensions(r,i,f),x=function(g){if(g<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},v=function(g){return g>r&&(d.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=v(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,i,c){if(typeof c=="number")return{width:c,height:c};if(typeof c=="function")try{return c(r,i)}catch(d){throw new Error("qrbox config was passed as a function but it failed with unknown error"+d)}return c},t.prototype.setupUi=function(r,i,c){c.isShadedBoxEnabled()&&this.validateQrboxSize(r,i,c);var d=zn(c.qrbox)?{width:r,height:i}:c.qrbox;this.validateQrboxConfig(d);var f=this.toQrdimensions(r,i,d);f.height>i&&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<=i,x={x:0,y:0,width:r,height:i},v=m?this.getShadedRegionBounds(r,i,f):x,g=this.createCanvasElement(v.width,v.height),E={willReadFrequently:!0},A=g.getContext("2d",E);A.canvas.width=v.width,A.canvas.height=v.height,this.element.append(g),m&&this.possiblyInsertShadingElement(this.element,r,i,f),this.createScannerPausedUiElement(this.element),this.qrRegion=v,this.context=A,this.canvasElement=g},t.prototype.createScannerPausedUiElement=function(r){var i=document.createElement("div");i.innerText=Rr.scannerPaused(),i.style.display="none",i.style.position="absolute",i.style.top="0px",i.style.zIndex="1",i.style.background="rgba(9, 9, 9, 0.46)",i.style.color="#FFECEC",i.style.textAlign="center",i.style.width="100%",r.appendChild(i),this.scannerPausedUiElement=i},t.prototype.scanContext=function(r,i){var c=this;return this.stateManagerProxy.isPaused()?Promise.resolve(!1):this.qrcode.decodeAsync(this.canvasElement).then(function(d){return r(d.text,cl.createFromQrcodeResult(d)),c.possiblyUpdateShaders(!0),!0}).catch(function(d){c.possiblyUpdateShaders(!1);var f=Rr.codeParseError(d);return i(f,rw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,i,c){var d=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 v=this.qrRegion.width*m,g=this.qrRegion.height*x,E=this.qrRegion.x*m,A=this.qrRegion.y*x;this.context.drawImage(f,E,A,v,g,0,0,this.qrRegion.width,this.qrRegion.height);var D=function(){d.foreverScanTimeout=setTimeout(function(){d.foreverScan(r,i,c)},d.getTimeoutFps(r.fps))};this.scanContext(i,c).then(function(T){!T&&r.disableFlip!==!0?(d.context.translate(d.context.canvas.width,0),d.context.scale(-1,1),d.scanContext(i,c).finally(function(){D()})):D()}).catch(function(T){d.logger.logError("Error happend while scanning context",T),D()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var i="facingMode",c="deviceId",d={user:!0,environment:!0},f="exact",m=function(S){if(S in d)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(S,"'")},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 v=Object.keys(r)[0];if(v!==i&&v!==c)throw"Only '".concat(i,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(v===i){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 E=typeof g;throw"Invalid type of 'facingMode' = ".concat(E)}}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 D=typeof A;throw"Invalid type of 'deviceId' = ".concat(D)}}}var T=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(T)},t.prototype.computeCanvasDrawConfig=function(r,i,c,d){if(r<=c&&i<=d){var f=(c-r)/2,m=(d-i)/2;return{x:f,y:m,width:r,height:i}}else{var x=r,v=i;return r>c&&(i=c/r*i,r=c),i>d&&(r=d/i*r,i=d),this.logger.log("Image downsampled from "+"".concat(x,"X").concat(v)+" to ".concat(r,"X").concat(i,".")),this.computeCanvasDrawConfig(r,i,c,d)}},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(i){i.style.backgroundColor=r?ln.BORDER_SHADER_MATCH_COLOR:ln.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,i,c){var d=r,f=i,m=document.createElement("canvas");return m.style.width="".concat(d,"px"),m.style.height="".concat(f,"px"),m.style.display="none",m.id=zn(c)?"qr-canvas":c,m},t.prototype.getShadedRegionBounds=function(r,i,c){if(c.width>r||c.height>i)throw"'config.qrbox' dimensions should not be greater than the dimensions of the root HTML element.";return{x:(r-c.width)/2,y:(i-c.height)/2,width:c.width,height:c.height}},t.prototype.possiblyInsertShadingElement=function(r,i,c,d){if(!(i-d.width<1||c-d.height<1)){var f=document.createElement("div");f.style.position="absolute";var m=(i-d.width)/2,x=(c-d.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(ln.SHADED_REGION_ELEMENT_ID),i-d.width<11||c-d.height<11)this.hasBorderShaders=!1;else{var v=5,g=40;this.insertShaderBorders(f,g,v,-v,null,0,!0),this.insertShaderBorders(f,g,v,-v,null,0,!1),this.insertShaderBorders(f,g,v,null,-v,0,!0),this.insertShaderBorders(f,g,v,null,-v,0,!1),this.insertShaderBorders(f,v,g+v,-v,null,-v,!0),this.insertShaderBorders(f,v,g+v,null,-v,-v,!0),this.insertShaderBorders(f,v,g+v,-v,null,-v,!1),this.insertShaderBorders(f,v,g+v,null,-v,-v,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,i,c,d,f,m,x){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,v.style.width="".concat(i,"px"),v.style.height="".concat(c,"px"),d!==null&&(v.style.top="".concat(d,"px")),f!==null&&(v.style.bottom="".concat(f,"px")),x?v.style.left="".concat(m,"px"):v.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(v),r.appendChild(v)},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})(),yl;(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"})(yl||(yl={}));const Tw={class:"scan-code"},Nw={class:"btn"},Ow={class:"left-back"},kw=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const i=r,c=Sd.IconScan(),d=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!d.html5QrCode){it("摄像头无访问权限!");return}f.value=!0,d.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[oo.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const T=new URL(A).searchParams.get("sessionId");T?i("scanSuccess",T):it("无效的二维码")}catch{it("无效的二维码")}E()}).catch(A=>{console.log(A),it({message:"二维码识别失败",duration:3e3})})},x=()=>{g().then(()=>{m()})},v=()=>{E()},g=()=>xl.getCameras().then(A=>{A&&A.length&&(d.html5QrCode=new xl("reader"))}).catch(()=>{it({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{d.html5QrCode&&d.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),it("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{d.html5QrCode&&d.html5QrCode.isScanning&&E()}),(A,D)=>{const T=rs;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:D[0]||(D[0]=S=>x())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Tw,[D[1]||(D[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Nw,[_.createElementVNode("div",Ow,[_.createVNode(T,{name:"arrow-left",onClick:v})])])],512),[[_.vShow,f.value]])]))])}}}),Rw=nr(kw,[["__scopeId","data-v-2d988579"]]);function is(t,r,i){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),d=()=>{const E=c.value;if(E.length===0)return"";if(r){const D=typeof r=="string"?r:r.value;if(D&&E.some(T=>T.id===D))return D}const A=E.find(D=>D.isDefault);return A?A.id:E[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=d());else{let E;r&&typeof r=="string"&&(E=r),f=_.ref(E&&c.value.some(A=>A.id===E)?E:d())}(!m||i)&&_.watch(f,E=>{i&&i(E)});const x=_.computed(()=>c.value.find(E=>E.id===f.value)),v=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:x,availableModels:v,setSelectedModel:E=>{c.value.find(D=>D.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Mw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const Dw=Object.prototype.toString,Pw=t=>Dw.call(t)==="[object Object]",No=()=>{};function wi(t){return Array.isArray(t)?t:[t]}function Bw(t,r,i){return _.watch(t,r,{...i,immediate:!0})}const qu=Mw?window:void 0;function Xr(t){var r;const i=_.toValue(t);return(r=i?.$el)!==null&&r!==void 0?r:i}function _i(...t){const r=(c,d,f,m)=>(c.addEventListener(d,f,m),()=>c.removeEventListener(d,f,m)),i=_.computed(()=>{const c=wi(_.toValue(t[0])).filter(d=>d!=null);return c.every(d=>typeof d!="string")?c:void 0});return Bw(()=>{var c,d;return[(c=(d=i.value)===null||d===void 0?void 0:d.map(f=>Xr(f)))!==null&&c!==void 0?c:[qu].filter(f=>f!=null),wi(_.toValue(i.value?t[1]:t[0])),wi(_.unref(i.value?t[2]:t[1])),_.toValue(i.value?t[3]:t[2])]},([c,d,f,m],x,v)=>{if(!c?.length||!d?.length||!f?.length)return;const g=Pw(m)?{...m}:m,E=c.flatMap(A=>d.flatMap(D=>f.map(T=>r(A,D,T,g))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function Lw(t,r,i={}){const{window:c=qu,ignore:d=[],capture:f=!0,detectIframe:m=!1,controls:x=!1}=i;if(!c)return x?{stop:No,cancel:No,trigger:No}:No;let v=!0;const g=M=>_.toValue(d).some(ee=>{if(typeof ee=="string")return Array.from(c.document.querySelectorAll(ee)).some($=>$===M.target||M.composedPath().includes($));{const $=Xr(ee);return $&&(M.target===$||M.composedPath().includes($))}});function E(M){const ee=_.toValue(M);return ee&&ee.$.subTree.shapeFlag===16}function A(M,ee){const $=_.toValue(M),F=$.$.subTree&&$.$.subTree.children;return F==null||!Array.isArray(F)?!1:F.some(re=>re.el===ee.target||ee.composedPath().includes(re.el))}const D=M=>{const ee=Xr(t);if(M.target!=null&&!(!(ee instanceof Element)&&E(t)&&A(t,M))&&!(!ee||ee===M.target||M.composedPath().includes(ee))){if("detail"in M&&M.detail===0&&(v=!g(M)),!v){v=!0;return}r(M)}};let T=!1;const S=[_i(c,"click",M=>{T||(T=!0,setTimeout(()=>{T=!1},0),D(M))},{passive:!0,capture:f}),_i(c,"pointerdown",M=>{const ee=Xr(t);v=!g(M)&&!!(ee&&!M.composedPath().includes(ee))},{passive:!0}),m&&_i(c,"blur",M=>{setTimeout(()=>{const ee=Xr(t);let $=c.document.activeElement;for(;$?.shadowRoot;)$=$.shadowRoot.activeElement;$?.tagName==="IFRAME"&&!ee?.contains(c.document.activeElement)&&r(M)},0)},{passive:!0})].filter(Boolean),P=()=>S.forEach(M=>M());return x?{stop:P,cancel:()=>{v=!1},trigger:M=>{v=!0,D(M),v=!1}}:P}const Fw=["data-active","disabled"],Uw=_.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,i)=>(_.openBlock(),_.createElementBlock("button",{class:_.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[_.renderSlot(r.$slots,"default",{},void 0,!0)],10,Fw))}}),ss=nr(Uw,[["__scopeId","data-v-6f582cce"]]),zw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function Vw(t,r){return _.openBlock(),_.createElementBlock("svg",zw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),_.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 Zw={render:Vw},$w={class:"button-text"},jw={class:"dropdown-menu__items"},Hw=["onClick"],Ww=_.defineComponent({__name:"ModelSwitch",props:_.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,i=_.useModel(t,"selectedModelId"),c=_.computed(()=>{const T=r.modelConfigs;return T?Array.isArray(T)?T:T.value:[]}),{selectedModel:d,availableModels:f,setSelectedModel:m}=is(c,i),x=_.ref(!1),v=T=>{m(T),E()},g=()=>{x.value=!x.value},E=()=>{x.value=!1},A=_.ref(null),D=_.ref(null);return Lw(D,()=>{E()},{ignore:[A]}),(T,S)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[_.createVNode(ss,{size:"small",class:"action-button",rounded:"",onClick:g},{default:_.withCtx(()=>[(_.openBlock(),_.createBlock(_.resolveDynamicComponent(_.unref(d)?.icon),{width:16,height:16,class:"selected-model__icon"})),_.createElementVNode("span",$w,_.toDisplayString(_.unref(d)?.label),1),_.createVNode(_.unref(Zw),{width:16,height:16})]),_:1}),_.createVNode(_.Transition,{name:"dropdown"},{default:_.withCtx(()=>[x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:D},[_.createElementVNode("div",jw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),P=>(_.openBlock(),_.createElementBlock("div",{key:P.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":P.id===i.value}]),onClick:_.withModifiers(M=>v(P.id),["stop"])},[P.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(P.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(P.label),1)],10,Hw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),x.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):_.createCommentVNode("",!0)],512))}}),Gw=nr(Ww,[["__scopeId","data-v-475491fd"]]),qw={key:0,class:"active-count"},Xw=_.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,i=_.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,d)=>(_.openBlock(),_.createBlock(ss,{size:"small",class:"action-button",active:i.value>0,rounded:"",onClick:d[0]||(d[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Mr.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),d[1]||(d[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),i.value>0?(_.openBlock(),_.createElementBlock("span",qw,_.toDisplayString(i.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),Yw=nr(Xw,[["__scopeId","data-v-c2a16c66"]]),Kw={"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 Jw(t,r){return _.openBlock(),_.createElementBlock("svg",Kw,[...r[0]||(r[0]=[_.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),_.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 Qw={render:Jw},e_=_.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=_.useModel(t,"genuiEnabled"),i=()=>{r.value=!r.value};return(c,d)=>(_.openBlock(),_.createBlock(ss,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:i},{default:_.withCtx(()=>[_.createVNode(_.unref(Qw),{width:16,height:16}),d[0]||(d[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),t_=nr(e_,[["__scopeId","data-v-7f3b0372"]]),n_={class:"bubble-image-wrapper"},r_=["src"],o_=["src"],i_=_.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=_.ref(!1),i=_.ref(null),c=()=>{r.value=!0},d=()=>{r.value=!1};return _.watch(r,f=>{f&&_.nextTick(()=>{i.value?.focus()})}),(f,m)=>(_.openBlock(),_.createElementBlock("div",n_,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,r_),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[r.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:d,onKeydown:_.withKeys(d,["esc"])},[_.createElementVNode("button",{ref_key:"closeButtonRef",ref:i,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:d},[...m[1]||(m[1]=[_.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[_.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),_.createElementVNode("div",{class:"preview-content",onClick:m[0]||(m[0]=_.withModifiers(()=>{},["stop"]))},[_.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,o_)])],32)):_.createCommentVNode("",!0)]))]))}}),s_=nr(i_,[["__scopeId","data-v-91c75579"]]),a_=`
82
82
  <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">
83
83
  <defs>
84
84
  <clipPath id="clip657_188316">
@@ -91,4 +91,4 @@ ${this.tempPrompt}
91
91
  <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>
92
92
  </g>
93
93
  </svg>
94
- `,Yw=btoa(qw),hl=`data:image/svg+xml;base64,${Yw}`,yo=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},Kw=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(yo)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(yo)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(yo)}],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:_.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:_.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:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:o,promptItems:c}},pl={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},Jw=t=>{console.log("message",t);const r=Object.keys(pl),o=r.findIndex(u=>t.includes(u));return(o!==-1?pl[r[o]]:t)||t},Qw={class:"tr-container__title"},e3={style:{flex:"1"}},t3={class:"chat-input"},n3={class:"chat-input-pills"},r3={class:"attachments-container"},i3={class:"action-buttons"},o3=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.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:_.h(kr.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(Fu,{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},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{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:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:o}){const c=t,u=o,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),g=_.useModel(t,"selectedModelId"),v=_.useModel(t,"genUiAble"),x=_.useModel(t,"enabledTools"),E=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=ns(E,g),M=_.computed(()=>{const He=E?.value?.length?A.value:c.llmConfig;return He?!!(He.baseURL&&He.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:B,checkCanSendAttachments:D,processAttachments:ne,cleanupAttachments:z}=Zy({selectedModel:A,selectedModelId:g}),{agent:Z,customAgentProvider:re,conversationState:$,messages:P,messageState:L,inputMessage:G,abortRequest:U,senderRef:ee,sendMessage:Y,handleSendMessage:ue,addMessage:ge,send:Te,createConversation:H,switchConversation:ye,deleteConversation:he,getCurrentConversation:Se}=sx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:u});_.watch(()=>c.systemPrompt,He=>{re.promptManager.setStatic(He)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const We=_.toRef(c,"skills"),{processSkillMentions:me}=Ty({skillsRef:We,customAgentProvider:re}),Oe=async(He,Pe)=>ue(He,Pe,me),{welcomeIcon:Me,roles:Je}=Dy({props:c,messages:P,messageState:L,inputMessage:G,handleSendMessage:Oe}),{showHistory:be,handleCreateConversation:ke,handleHistorySelect:te,handleHistoryUpdateTitle:Ie,handleHistoryDelete:Ae}=Py({createConversation:H,switchConversation:ye,deleteConversation:he,getCurrentConversation:Se,abortRequest:U,conversationState:$,customAgentProvider:re}),fe=()=>{if(A.value){const He=A.value;re.updateLLMConfig({model:He.model||"",baseURL:He.baseURL||"",genuiUrl:He.genuiUrl||"",apiKey:He.apiKey||"",providerType:He.providerType,useReActMode:He.useReActMode,llm:He.llm,providerOptions:He.providerOptions,headers:He.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,fe,{immediate:!0}),_.watch(v,fe,{immediate:!0});const K={markdown:new $t.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":He=>_.h(wd.GenuiRenderer,{...He,customActions:{continueChat:{execute:(Pe,tt)=>{const Ge=typeof Pe=="string"?Pe:Pe.message,zn=`${Ge},相关参数为:${JSON.stringify(tt?.state||{})}`;ge({role:"user",content:zn,uiContent:[{type:"markdown",content:Ge}]}),Te()}}},generating:Qn.GeneratingStatus.includes(L.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:Xw};function xe(He,Pe){K[He]=Pe}const{installedPlugins:et,marketPlugins:we,pluginVisible:kt,loadMcpServerToPlugin:Bt,togglePlugin:Tn,toggleTool:It,deletePlugin:Qe,addPluginCore:je,addPluginFromMarket:Nn,addPluginFromScan:Ce,handleClientDisconnected:Un,searchPlugin:Hn,syncInstalledPluginTools:Yt}=Iy(Z,x,hl);Sy({onToolCatalogChanged:async()=>{await Z.refreshTools(),Yt()}}),we.value=[...c.customMarketMcpServers];const Wn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),zt=Kw(c),ir=_.computed(()=>c.pillItems??zt.pillItems),ln=_.computed(()=>c.promptItems??zt.promptItems),k=zt.lang,{handleScanSuccess:se,handleSessionIdInput:Ye,initialize:bt}=By({sessionId:_.toRef(c,"sessionId"),agentRoot:_.toRef(c,"agentRoot"),mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:Ce,inputMessage:G}),mt=async He=>{if(await Ye(G.value)||!D())return;const tt=await ne();try{await Oe(He,tt),z()}catch(Ge){console.error("发送消息失败:",Ge)}},pe=_.computed(()=>Qn.GeneratingStatus.includes(L.status)?k[c.locale].thinking:k[c.locale].placeholder),Rt=_.computed(()=>Qn.GeneratingStatus.includes(L.status)),at=He=>{G.value=He.inputMessage};bt(),_.onMounted(async()=>{setTimeout(()=>{ke()},100),Z.onError=Pe=>{Pe&&rt(Jw(Pe))};const He=we.value.filter(Pe=>Pe.addState==="added"&&Pe.enabled);for(const Pe of He)await Nn(Pe);if(c.mcpServers)for(const[Pe,tt]of Object.entries(c.mcpServers))await Bt(Pe,tt)});const{handleCustomAdd:_t}=Ey(Z,et,hl);return r({agent:Z,welcomeIcon:Me,messages:P,messageState:L,roles:Je,inputMessage:G,senderRef:ee,abortRequest:U,sendMessage:Y,loadMcpServerToPlugin:Bt,handleClientDisconnected:Un,addMessage:ge,installedPlugins:et,addPluginCore:je,deletePlugin:Qe,registerContentRenderer:xe,async refreshPluginTools(){await Z.refreshTools(),Yt()}}),(He,Pe)=>(_.openBlock(),_.createBlock(_.unref($t.TrContainer),{show:m.value,"onUpdate:show":Pe[11]||(Pe[11]=tt=>m.value=tt),fullscreen:f.value,"onUpdate:fullscreen":Pe[12]||(Pe[12]=tt=>f.value=tt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",Qw,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(He.$slots,"operations",{},()=>[_.createVNode(_.unref($t.TrIconButton),{icon:_.unref(kr.IconNewSession),size:"28",svgSize:"20",onClick:Pe[0]||(Pe[0]=tt=>_.unref(ke)())},null,8,["icon"]),_.createVNode(_.unref($t.TrIconButton),{icon:_.unref(kr.IconHistory),size:"28",svgSize:"20",onClick:Pe[1]||(Pe[1]=tt=>be.value=!_.unref(be))},null,8,["icon"]),_.createVNode(_w,{onScanSuccess:_.unref(se)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(be)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Pe[4]||(Pe[4]=tt=>be.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:Pe[3]||(Pe[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[Pe[13]||(Pe[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref($t.TrHistory),{class:"tr-history-demo",selected:_.unref($).currentId,data:_.unref($).conversations,showRenameControls:!0,onClose:Pe[2]||(Pe[2]=tt=>be.value=!1),onItemClick:_.unref(te),onItemTitleChange:_.unref(Ie),onItemAction:_.unref(Ae)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",t3,[_.renderSlot(He.$slots,"suggestions",{},()=>[_.createElementVNode("div",n3,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(ir.value,tt=>(_.openBlock(),_.createBlock(_.unref($t.TrDropdownMenu),{key:tt.id,items:tt.menus,onItemClick:at,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref($t.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(tt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref($t.TrSender),{ref_key:"senderRef",ref:ee,mode:"multiple",modelValue:_.unref(G),"onUpdate:modelValue":Pe[9]||(Pe[9]=tt=>_.isRef(G)?G.value=tt:null),placeholder:pe.value,clearable:!!_.unref(G),loading:Rt.value,showWordLimit:!0,maxLength:2e4,onSubmit:mt,onCancel:_.unref(U)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",i3,[_.createVNode(Fw,{"installed-plugins":_.unref(et),onClick:Pe[6]||(Pe[6]=tt=>kt.value=!_.unref(kt))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(Pw,{key:0,"model-configs":_.unref(E),"selected-model-id":g.value,"onUpdate:selectedModelId":Pe[7]||(Pe[7]=tt=>g.value=tt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),M.value?(_.openBlock(),_.createBlock($w,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Pe[8]||(Pe[8]=tt=>v.value=tt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref($t.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(B)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",r3,[_.createVNode(_.unref($t.TrAttachments),{items:_.unref(S),"onUpdate:items":Pe[5]||(Pe[5]=tt=>_.isRef(S)?S.value=tt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref($t.TrMcpServerPicker),{visible:_.unref(kt),"onUpdate:visible":Pe[10]||(Pe[10]=tt=>_.isRef(kt)?kt.value=tt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(et),marketPlugins:_.unref(we),"market-category-options":Wn.value,"installed-search-fn":_.unref(Hn),"market-search-fn":_.unref(Hn),onPluginToggle:_.unref(Tn),onPluginAdd:_.unref(Nn),onPluginDelete:_.unref(Qe),onToolToggle:_.unref(It),onPluginCreate:_.unref(_t)},{"header-actions":_.withCtx(()=>[_.renderSlot(He.$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:_.withCtx(()=>[_.createVNode(_.unref($t.TrBubbleProvider),{"content-renderers":K},{default:_.withCtx(()=>[_.unref(P).length===0?_.renderSlot(He.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",e3,[_.createVNode(_.unref($t.TrWelcome),{title:_.unref(k)[t.locale].title,description:_.unref(k)[t.locale].description,icon:_.unref(Me)},null,8,["title","description","icon"]),_.createVNode(_.unref($t.TrPrompts),{items:ln.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref($t.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(P),roles:_.unref(Je),"auto-scroll":"",loading:_.unref(L).status===_.unref(Qn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Po=rr(o3,[["__scopeId","data-v-1ca1e787"]]);function s3(t){const r=t.sessionId?ml(t.sessionId,t.agentRoot):[],o=new $n.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=_.ref("ready"),u=_.ref([]),f=_.ref("");let m=null;async function g(){const A=f.value;if(!A)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(A)){E(A.slice(1));return}c.value="submitted",m=new AbortController;const M=await o.chatStream({message:A,model:t.model,system:t.systemPrompt||"",abortSignal:m.signal,maxSteps:t.maxSteps||30,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(M.fullStream,u,A);return}t.ui==="matechat"?a3(M.fullStream,u,A):t.ui==="antx"?l3(M.fullStream,u,A):t.ui==="elplusx"?c3(M.fullStream,u,A):t.ui==="tdchat"?u3(M.fullStream,u,A):console.warn("暂时未实现")}function v(){m&&m.abort()}function x(){u.value=[],o.responseMessages=[]}async function E(A){const T=(await fetch(`${t.agentRoot}client?sessionId=${A}`).then(S=>S.json()))?.data?.sessionId||"";if(T){const S=ml(T,t.agentRoot);Object.assign(o.mcpServers,S)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:g,stopChat:v,newConversation:x,addSessionId:E}}function ml(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 a3(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 l3(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 c3(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 u3(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)}Po.install=function(t){t.component("tiny-remoter",Po)};exports.TinyRemoter=Po;exports.useModel=ns;exports.useNextAgent=s3;
94
+ `,l_=btoa(a_),wl=`data:image/svg+xml;base64,${l_}`,vi=(t,r)=>{const[i,c]=t.split("#");return{id:r,text:i,inputMessage:c}},c_=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..."}},i=[{id:"office",text:t.locale==="zh-CN"?"办公助手":"Office Assistant",menus:["接收邮件#请同步邮箱的新邮件。","编写邮件#请新建一个邮件,收件人为 opentiny-next@meeting.com, 内容为举办一个临时会议。","安排会议#创建一个临时的在线会议,主题为讨论问题,时长为1小时。","整理文档#请分析附件中的销售情况,把销售额绘制成折线图。"].map(vi)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(vi)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(vi)}],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:_.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:_.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:_.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:i,promptItems:c}},_l={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},u_=t=>{console.log("message",t);const r=Object.keys(_l),i=r.findIndex(d=>t.includes(d));return(i!==-1?_l[r[i]]:t)||t},d_={class:"tr-container__title"},f_={style:{flex:"1"}},h_={class:"chat-input"},p_={class:"chat-input-pills"},m_={class:"attachments-container"},g_={class:"action-buttons"},x_=_.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:_.mergeModels({agentRoot:{type:String,default:"https://agent.opentiny.design/api/v1/webmcp-trial/"},sessionId:{type:String,default:void 0},menuItems:{type:Array},remoteUrl:{type:String},qrCodeUrl:{type:String},systemPrompt:{type:String,default:"你是一个智能助手,擅长通过工具调用帮助用户解决问题和满足用户需求"},title:{type:String,default:"OpenTiny NEXT"},locale:{type:String,default:"zh-CN"},AILogoUrl:{type:String},roleAvatar:{type:Object,default:()=>({user:_.h(Mr.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(ju,{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},promptItems:{type:Array,default:void 0},pillItems:{type:Array,default:void 0}},{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:_.mergeModels(["before-ai-render","chat-stream-finish"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:i}){const c=t,d=i,f=_.useModel(t,"fullscreen"),m=_.useModel(t,"show"),x=_.useModel(t,"selectedModelId"),v=_.useModel(t,"genUiAble"),g=_.useModel(t,"enabledTools"),E=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=is(E,x),D=_.computed(()=>{const Ee=E?.value?.length?A.value:c.llmConfig;return Ee?!!(Ee.baseURL&&Ee.genuiUrl):!1}),{hasMultimodalSupport:T,attachments:S,onFilesSelected:P,checkCanSendAttachments:M,processAttachments:ee,cleanupAttachments:$}=ew({selectedModel:A,selectedModelId:x}),{agent:F,customAgentProvider:re,conversationState:Z,messages:B,messageState:L,inputMessage:W,abortRequest:z,senderRef:we,sendMessage:G,handleSendMessage:me,addMessage:fe,send:te,createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te}=yx({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:d});_.watch(()=>c.systemPrompt,Ee=>{re.promptManager.setStatic(Ee)}),re.isGenuiEnabled=v,re.debugStream=c.debugStream;const Je=_.toRef(c,"skills"),{processSkillMentions:xe}=zy({skillsRef:Je,customAgentProvider:re}),$e=async(Ee,Oe)=>me(Ee,Oe,xe),{welcomeIcon:Ue,roles:Ze}=Wy({props:c,messages:B,messageState:L,inputMessage:W,handleSendMessage:$e}),{showHistory:qe,handleCreateConversation:ze,handleHistorySelect:ie,handleHistoryUpdateTitle:de,handleHistoryDelete:_e}=Gy({createConversation:q,switchConversation:ke,deleteConversation:le,getCurrentConversation:Te,abortRequest:z,conversationState:Z,customAgentProvider:re}),Pe=()=>{if(A.value){const Ee=A.value;re.updateLLMConfig({model:Ee.model||"",baseURL:Ee.baseURL||"",genuiUrl:Ee.genuiUrl||"",apiKey:Ee.apiKey||"",providerType:Ee.providerType,useReActMode:Ee.useReActMode,llm:Ee.llm,providerOptions:Ee.providerOptions,headers:Ee.headers})}else re.updateLLMConfig(re.llmConfig)};c.llmConfigs&&_.watch(A,Pe,{immediate:!0}),_.watch(v,Pe,{immediate:!0});const ae={markdown:new Vt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":Ee=>_.h(Ed.GenuiRenderer,{...Ee,customActions:{continueChat:{execute:(Oe,rt)=>{const Ye=typeof Oe=="string"?Oe:Oe.message,Fn=`${Ye},相关参数为:${JSON.stringify(rt?.state||{})}`;fe({role:"user",content:Fn,uiContent:[{type:"markdown",content:Ye}]}),te()}}},generating:Kn.GeneratingStatus.includes(L.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:s_};function J(Ee,Oe){ae[Ee]=Oe}const{installedPlugins:ye,marketPlugins:Se,pluginVisible:Ve,loadMcpServerToPlugin:St,togglePlugin:vt,toggleTool:et,deletePlugin:nt,addPluginCore:Xe,addPluginFromMarket:In,addPluginFromScan:be,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:qt}=Fy(F,g,wl);Uy({onToolCatalogChanged:async()=>{await F.refreshTools(),qt()}}),Se.value=[...c.customMarketMcpServers];const jn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Ft=c_(c),rr=_.computed(()=>c.pillItems??Ft.pillItems),sn=_.computed(()=>c.promptItems??Ft.promptItems),At=Ft.lang,{handleScanSuccess:or,handleSessionIdInput:Ln,initialize:wr}=qy({sessionId:_.toRef(c,"sessionId"),agentRoot:_.toRef(c,"agentRoot"),mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:be,inputMessage:W}),gt=async Ee=>{if(await Ln(W.value)||!M())return;const rt=await ee();try{await $e(Ee,rt),$()}catch(Ye){console.error("发送消息失败:",Ye)}},ge=_.computed(()=>Kn.GeneratingStatus.includes(L.status)?At[c.locale].thinking:At[c.locale].placeholder),O=_.computed(()=>Kn.GeneratingStatus.includes(L.status)),ne=Ee=>{W.value=Ee.inputMessage};wr(),_.onMounted(async()=>{setTimeout(()=>{ze()},100),F.onError=Oe=>{Oe&&it(u_(Oe))};const Ee=Se.value.filter(Oe=>Oe.addState==="added"&&Oe.enabled);for(const Oe of Ee)await In(Oe);if(c.mcpServers)for(const[Oe,rt]of Object.entries(c.mcpServers))await St(Oe,rt)});const{handleCustomAdd:Me}=Ly(F,ye,wl);return r({agent:F,welcomeIcon:Ue,messages:B,messageState:L,roles:Ze,inputMessage:W,senderRef:we,abortRequest:z,sendMessage:G,loadMcpServerToPlugin:St,handleClientDisconnected:Bn,addMessage:fe,installedPlugins:ye,addPluginCore:Xe,deletePlugin:nt,registerContentRenderer:J,async refreshPluginTools(){await F.refreshTools(),qt()}}),(Ee,Oe)=>(_.openBlock(),_.createBlock(_.unref(Vt.TrContainer),{show:m.value,"onUpdate:show":Oe[11]||(Oe[11]=rt=>m.value=rt),fullscreen:f.value,"onUpdate:fullscreen":Oe[12]||(Oe[12]=rt=>f.value=rt),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",d_,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot(Ee.$slots,"operations",{},()=>[_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconNewSession),size:"28",svgSize:"20",onClick:Oe[0]||(Oe[0]=rt=>_.unref(ze)())},null,8,["icon"]),_.createVNode(_.unref(Vt.TrIconButton),{icon:_.unref(Mr.IconHistory),size:"28",svgSize:"20",onClick:Oe[1]||(Oe[1]=rt=>qe.value=!_.unref(qe))},null,8,["icon"]),_.createVNode(Rw,{onScanSuccess:_.unref(or)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(qe)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:Oe[4]||(Oe[4]=rt=>qe.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:Oe[3]||(Oe[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[Oe[13]||(Oe[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Vt.TrHistory),{class:"tr-history-demo",selected:_.unref(Z).currentId,data:_.unref(Z).conversations,showRenameControls:!0,onClose:Oe[2]||(Oe[2]=rt=>qe.value=!1),onItemClick:_.unref(ie),onItemTitleChange:_.unref(de),onItemAction:_.unref(_e)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",h_,[_.renderSlot(Ee.$slots,"suggestions",{},()=>[_.createElementVNode("div",p_,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,rt=>(_.openBlock(),_.createBlock(_.unref(Vt.TrDropdownMenu),{key:rt.id,items:rt.menus,onItemClick:ne,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(rt.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Vt.TrSender),{ref_key:"senderRef",ref:we,mode:"multiple",modelValue:_.unref(W),"onUpdate:modelValue":Oe[9]||(Oe[9]=rt=>_.isRef(W)?W.value=rt:null),placeholder:ge.value,clearable:!!_.unref(W),loading:O.value,showWordLimit:!0,maxLength:2e4,onSubmit:gt,onCancel:_.unref(z)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",g_,[_.createVNode(Yw,{"installed-plugins":_.unref(ye),onClick:Oe[6]||(Oe[6]=rt=>Ve.value=!_.unref(Ve))},null,8,["installed-plugins"]),_.unref(E)&&_.unref(E).length>0?(_.openBlock(),_.createBlock(Gw,{key:0,"model-configs":_.unref(E),"selected-model-id":x.value,"onUpdate:selectedModelId":Oe[7]||(Oe[7]=rt=>x.value=rt)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),D.value?(_.openBlock(),_.createBlock(t_,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":Oe[8]||(Oe[8]=rt=>v.value=rt)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(T)?(_.openBlock(),_.createBlock(_.unref(Vt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(P)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(S).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",m_,[_.createVNode(_.unref(Vt.TrAttachments),{items:_.unref(S),"onUpdate:items":Oe[5]||(Oe[5]=rt=>_.isRef(S)?S.value=rt:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Vt.TrMcpServerPicker),{visible:_.unref(Ve),"onUpdate:visible":Oe[10]||(Oe[10]=rt=>_.isRef(Ve)?Ve.value=rt:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(ye),marketPlugins:_.unref(Se),"market-category-options":jn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(vt),onPluginAdd:_.unref(In),onPluginDelete:_.unref(nt),onToolToggle:_.unref(et),onPluginCreate:_.unref(Me)},{"header-actions":_.withCtx(()=>[_.renderSlot(Ee.$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:_.withCtx(()=>[_.createVNode(_.unref(Vt.TrBubbleProvider),{"content-renderers":ae},{default:_.withCtx(()=>[_.unref(B).length===0?_.renderSlot(Ee.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",f_,[_.createVNode(_.unref(Vt.TrWelcome),{title:_.unref(At)[t.locale].title,description:_.unref(At)[t.locale].description,icon:_.unref(Ue)},null,8,["title","description","icon"]),_.createVNode(_.unref(Vt.TrPrompts),{items:sn.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref(Vt.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(B),roles:_.unref(Ze),"auto-scroll":"",loading:_.unref(L).status===_.unref(Kn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Fi=nr(x_,[["__scopeId","data-v-635a2faf"]]);Fi.install=function(t){t.component("tiny-remoter",Fi)};exports.TinyRemoter=Fi;exports.useModel=is;