@opentiny/next-remoter 0.2.10 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/TinyRobotChat.vue.d.ts +0 -19
- package/dist/composable/CustomAgentModelProvider.d.ts +0 -7
- package/dist/composable/useBuiltinMcpServer.d.ts +28 -0
- package/dist/composable/usePlugin.d.ts +1 -0
- package/dist/composable/useRouteBasedTools.d.ts +3 -35
- package/dist/next-remoter-runtime.es.js +72487 -71908
- package/dist/next-remoter.cjs.js +44 -43
- package/dist/next-remoter.css +1 -1
- package/dist/next-remoter.es.js +7960 -7700
- package/dist/style.css +1 -1
- package/package.json +2 -2
package/dist/next-remoter.cjs.js
CHANGED
|
@@ -1,67 +1,68 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
Error message: ${
|
|
3
|
-
Error message: ${
|
|
4
|
-
`;break;case"id":
|
|
5
|
-
`)?
|
|
6
|
-
`,c);let
|
|
7
|
-
`&&c++}}return[r,o]}class Zl extends TransformStream{constructor({onError:r,onRetry:o,onComment:c}={}){let u;super({start(f){u=Td({onEvent:g=>{f.enqueue(g)},onError(g){r==="terminate"?f.error(g):typeof r=="function"&&r(g)},onRetry:o,onComment:c})},transform(f){u.feed(f)}})}}function ne(t,r,o){function c(m,v){var x;Object.defineProperty(m,"_zod",{value:m._zod??{},enumerable:!1}),(x=m._zod).traits??(x.traits=new Set),m._zod.traits.add(t),r(m,v);for(const E in g.prototype)E in m||Object.defineProperty(m,E,{value:g.prototype[E].bind(m)});m._zod.constr=g,m._zod.def=v}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function g(m){var v;const x=o?.Parent?new f:this;c(x,m),(v=x._zod).deferred??(v.deferred=[]);for(const E of x._zod.deferred)E();return x}return Object.defineProperty(g,"init",{value:c}),Object.defineProperty(g,Symbol.hasInstance,{value:m=>o?.Parent&&m instanceof o.Parent?!0:m?._zod?.traits?.has(t)}),Object.defineProperty(g,"name",{value:t}),g}class Gr extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const $l={};function Xn(t){return $l}function Wl(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 Od(t,r){return typeof r=="bigint"?r.toString():r}function Mo(t){return{get value(){{const r=t();return Object.defineProperty(this,"value",{value:r}),r}}}}function Do(t){return t==null}function Po(t){const r=t.startsWith("^")?1:0,o=t.endsWith("$")?t.length-1:t.length;return t.slice(r,o)}function kd(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(".","")),g=Number.parseInt(r.toFixed(u).replace(".",""));return f%g/10**u}function Qe(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 Bo(t,r,o){Object.defineProperty(t,r,{value:o,writable:!0,enumerable:!0,configurable:!0})}function Pr(t){return JSON.stringify(t)}const Hl=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ii(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Rd=Mo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function Si(t){if(Ii(t)===!1)return!1;const r=t.constructor;if(r===void 0)return!0;const o=r.prototype;return!(Ii(o)===!1||Object.prototype.hasOwnProperty.call(o,"isPrototypeOf")===!1)}const Md=new Set(["string","number","symbol"]);function Qr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ur(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function ye(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 Dd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Pd={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 Bd(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 ur(t,{...t._zod.def,shape:o,checks:[]})}function Ld(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 ur(t,{...t._zod.def,shape:o,checks:[]})}function Fd(t,r){if(!Si(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 Bo(this,"shape",c),c},checks:[]};return ur(t,o)}function Ud(t,r){return ur(t,{...t._zod.def,get shape(){const o={...t._zod.def.shape,...r._zod.def.shape};return Bo(this,"shape",o),o},catchall:r._zod.def.catchall,checks:[]})}function zd(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 ur(r,{...r._zod.def,shape:u,checks:[]})}function Vd(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 ur(r,{...r._zod.def,shape:u,checks:[]})}function Wr(t,r=0){for(let o=r;o<t.issues.length;o++)if(t.issues[o]?.continue!==!0)return!0;return!1}function ar(t,r){return r.map(o=>{var c;return(c=o).path??(c.path=[]),o.path.unshift(t),o})}function gi(t){return typeof t=="string"?t:t?.message}function qn(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 Lo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Xr(...t){const[r,o,c]=t;return typeof r=="string"?{message:r,code:"custom",input:o,inst:c}:{...r}}const jl=(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,Od,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gl=ne("$ZodError",jl),Xl=ne("$ZodError",jl,{Parent:Error});function Zd(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 $d(t,r){const o=r||function(f){return f.message},c={_errors:[]},u=f=>{for(const g of f.issues)if(g.code==="invalid_union"&&g.errors.length)g.errors.map(m=>u({issues:m}));else if(g.code==="invalid_key")u({issues:g.issues});else if(g.code==="invalid_element")u({issues:g.issues});else if(g.path.length===0)c._errors.push(o(g));else{let m=c,v=0;for(;v<g.path.length;){const x=g.path[v];v===g.path.length-1?(m[x]=m[x]||{_errors:[]},m[x]._errors.push(o(g))):m[x]=m[x]||{_errors:[]},m=m[x],v++}}};return u(t),c}const Wd=t=>(r,o,c,u)=>{const f=c?Object.assign(c,{async:!1}):{async:!1},g=r._zod.run({value:o,issues:[]},f);if(g instanceof Promise)throw new Gr;if(g.issues.length){const m=new(u?.Err??t)(g.issues.map(v=>qn(v,f,Xn())));throw Hl(m,u?.callee),m}return g.value},Hd=t=>async(r,o,c,u)=>{const f=c?Object.assign(c,{async:!0}):{async:!0};let g=r._zod.run({value:o,issues:[]},f);if(g instanceof Promise&&(g=await g),g.issues.length){const m=new(u?.Err??t)(g.issues.map(v=>qn(v,f,Xn())));throw Hl(m,u?.callee),m}return g.value},ql=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 Gr;return f.issues.length?{success:!1,error:new(t??Gl)(f.issues.map(g=>qn(g,u,Xn())))}:{success:!0,data:f.value}},jd=ql(Xl),Yl=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(g=>qn(g,u,Xn())))}:{success:!0,data:f.value}},Gd=Yl(Xl),Xd=/^[cC][^\s-]{8,}$/,qd=/^[0-9a-z]+$/,Yd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Kd=/^[0-9a-vA-V]{20}$/,Jd=/^[A-Za-z0-9]{27}$/,Qd=/^[a-zA-Z0-9_-]{21}$/,e1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,t1=/^([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})$/,ws=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)$/,n1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,r1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function i1(){return new RegExp(r1,"u")}const o1=/^(?:(?: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])$/,s1=/^(([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})$/,a1=/^((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])$/,l1=/^(([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])$/,c1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Kl=/^[A-Za-z0-9_-]*$/,u1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,d1=/^\+(?:[0-9]){6,14}[0-9]$/,Jl="(?:(?:\\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])))",f1=new RegExp(`^${Jl}$`);function Ql(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 h1(t){return new RegExp(`^${Ql(t)}$`)}function p1(t){const r=Ql({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(`^${Jl}T(?:${c})$`)}const g1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},m1=/^\d+$/,x1=/^-?\d+(?:\.\d+)?/i,w1=/true|false/i,y1=/null/i,_1=/^[^A-Z]*$/,v1=/^[^a-z]*$/,tn=ne("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),ec={number:"number",bigint:"bigint",object:"date"},tc=ne("$ZodCheckLessThan",(t,r)=>{tn.init(t,r);const o=ec[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})}}),nc=ne("$ZodCheckGreaterThan",(t,r)=>{tn.init(t,r);const o=ec[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})}}),C1=ne("$ZodCheckMultipleOf",(t,r)=>{tn.init(t,r),t._zod.onattach.push(o=>{var c;(c=o._zod.bag).multipleOf??(c.multipleOf=r.value)}),t._zod.check=o=>{if(typeof o.value!=typeof r.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof o.value=="bigint"?o.value%r.value===BigInt(0):kd(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})}}),b1=ne("$ZodCheckNumberFormat",(t,r)=>{tn.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=Pd[r.format];t._zod.onattach.push(g=>{const m=g._zod.bag;m.format=r.format,m.minimum=u,m.maximum=f,o&&(m.pattern=m1)}),t._zod.check=g=>{const m=g.value;if(o){if(!Number.isInteger(m)){g.issues.push({expected:c,format:r.format,code:"invalid_type",input:m,inst:t});return}if(!Number.isSafeInteger(m)){m>0?g.issues.push({input:m,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:c,continue:!r.abort}):g.issues.push({input:m,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}}m<u&&g.issues.push({origin:"number",input:m,code:"too_small",minimum:u,inclusive:!0,inst:t,continue:!r.abort}),m>f&&g.issues.push({origin:"number",input:m,code:"too_big",maximum:f,inst:t})}}),E1=ne("$ZodCheckMaxLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Do(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 g=Lo(u);c.issues.push({origin:g,code:"too_big",maximum:r.maximum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),A1=ne("$ZodCheckMinLength",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Do(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 g=Lo(u);c.issues.push({origin:g,code:"too_small",minimum:r.minimum,inclusive:!0,input:u,inst:t,continue:!r.abort})}}),I1=ne("$ZodCheckLengthEquals",(t,r)=>{var o;tn.init(t,r),(o=t._zod.def).when??(o.when=c=>{const u=c.value;return!Do(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 g=Lo(u),m=f>r.length;c.issues.push({origin:g,...m?{code:"too_big",maximum:r.length}:{code:"too_small",minimum:r.length},inclusive:!0,exact:!0,input:c.value,inst:t,continue:!r.abort})}}),Mi=ne("$ZodCheckStringFormat",(t,r)=>{var o,c;tn.init(t,r),t._zod.onattach.push(u=>{const f=u._zod.bag;f.format=r.format,r.pattern&&(f.patterns??(f.patterns=new Set),f.patterns.add(r.pattern))}),r.pattern?(o=t._zod).check??(o.check=u=>{r.pattern.lastIndex=0,!r.pattern.test(u.value)&&u.issues.push({origin:"string",code:"invalid_format",format:r.format,input:u.value,...r.pattern?{pattern:r.pattern.toString()}:{},inst:t,continue:!r.abort})}):(c=t._zod).check??(c.check=()=>{})}),S1=ne("$ZodCheckRegex",(t,r)=>{Mi.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})}}),T1=ne("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=_1),Mi.init(t,r)}),N1=ne("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=v1),Mi.init(t,r)}),O1=ne("$ZodCheckIncludes",(t,r)=>{tn.init(t,r);const o=Qr(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})}}),k1=ne("$ZodCheckStartsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`^${Qr(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})}}),R1=ne("$ZodCheckEndsWith",(t,r)=>{tn.init(t,r);const o=new RegExp(`.*${Qr(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})}}),M1=ne("$ZodCheckOverwrite",(t,r)=>{tn.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class D1{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(`
|
|
8
|
-
`).filter(
|
|
9
|
-
`))}}const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _=require("vue"),Ut=require("@opentiny/tiny-robot"),fd=require("@opentiny/genui-sdk-vue"),Kn=require("@opentiny/tiny-robot-kit"),Or=require("@opentiny/tiny-robot-svgs"),Jn=require("@opentiny/next-sdk"),hd=require("@opentiny/vue-tooltip"),pd=require("@opentiny/vue-icon");function md(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 hl="vercel.ai.error",gd=Symbol.for(hl),pl,xd=class ml extends Error{constructor({name:r,message:o,cause:c}){super(o),this[pl]=!0,this.name=r,this.cause=c}static isInstance(r){return ml.hasMarker(r,hl)}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}};pl=gd;var zt=xd,gl="AI_APICallError",xl=`vercel.ai.error.${gl}`,yd=Symbol.for(xl),yl,Un=class extends zt{constructor({message:r,url:o,requestBodyValues:c,statusCode:u,responseHeaders:f,responseBody:m,cause:g,isRetryable:C=u!=null&&(u===408||u===409||u===429||u>=500),data:x}){super({name:gl,message:r,cause:g}),this[yl]=!0,this.url=o,this.requestBodyValues=c,this.statusCode=u,this.responseHeaders=f,this.responseBody=m,this.isRetryable=C,this.data=x}static isInstance(r){return zt.hasMarker(r,xl)}};yl=yd;var wl="AI_EmptyResponseBodyError",_l=`vercel.ai.error.${wl}`,wd=Symbol.for(_l),vl,_d=class extends zt{constructor({message:r="Empty response body"}={}){super({name:wl,message:r}),this[vl]=!0}static isInstance(r){return zt.hasMarker(r,_l)}};vl=wd;function Cl(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var bl="AI_InvalidArgumentError",El=`vercel.ai.error.${bl}`,vd=Symbol.for(El),Al,Il=class extends zt{constructor({message:r,cause:o,argument:c}){super({name:bl,message:r,cause:o}),this[Al]=!0,this.argument=c}static isInstance(r){return zt.hasMarker(r,El)}};Al=vd;var Sl="AI_InvalidResponseDataError",Tl=`vercel.ai.error.${Sl}`,Cd=Symbol.for(Tl),Nl,ws=class extends zt{constructor({data:r,message:o=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:Sl,message:o}),this[Nl]=!0,this.data=r}static isInstance(r){return zt.hasMarker(r,Tl)}};Nl=Cd;var Ol="AI_JSONParseError",kl=`vercel.ai.error.${Ol}`,bd=Symbol.for(kl),Rl,Ii=class extends zt{constructor({text:r,cause:o}){super({name:Ol,message:`JSON parsing failed: Text: ${r}.
|
|
2
|
+
Error message: ${Cl(o)}`,cause:o}),this[Rl]=!0,this.text=r}static isInstance(r){return zt.hasMarker(r,kl)}};Rl=bd;var Ml="AI_LoadAPIKeyError",Dl=`vercel.ai.error.${Ml}`,Ed=Symbol.for(Dl),Pl,mi=class extends zt{constructor({message:r}){super({name:Ml,message:r}),this[Pl]=!0}static isInstance(r){return zt.hasMarker(r,Dl)}};Pl=Ed;var Bl="AI_NoSuchModelError",Ll=`vercel.ai.error.${Bl}`,Ad=Symbol.for(Ll),Fl,_s=class extends zt{constructor({errorName:t=Bl,modelId:r,modelType:o,message:c=`No such ${o}: ${r}`}){super({name:t,message:c}),this[Fl]=!0,this.modelId=r,this.modelType=o}static isInstance(t){return zt.hasMarker(t,Ll)}};Fl=Ad;var Ul="AI_TypeValidationError",zl=`vercel.ai.error.${Ul}`,Id=Symbol.for(zl),Vl,Sd=class yo extends zt{constructor({value:r,cause:o}){super({name:Ul,message:`Type validation failed: Value: ${JSON.stringify(r)}.
|
|
3
|
+
Error message: ${Cl(o)}`,cause:o}),this[Vl]=!0,this.value=r}static isInstance(r){return zt.hasMarker(r,zl)}static wrap({value:r,cause:o}){return yo.isInstance(o)&&o.value===r?o:new yo({value:r,cause:o})}};Vl=Id;var qr=Sd,Zl="AI_UnsupportedFunctionalityError",$l=`vercel.ai.error.${Zl}`,Td=Symbol.for($l),Hl,Wl=class extends zt{constructor({functionality:r,message:o=`'${r}' functionality not supported.`}){super({name:Zl,message:o}),this[Hl]=!0,this.functionality=r}static isInstance(r){return zt.hasMarker(r,$l)}};Hl=Td;class vs extends Error{constructor(r,o){super(r),this.name="ParseError",this.type=o.type,this.field=o.field,this.value=o.value,this.line=o.line}}function ro(t){}function Nd(t){if(typeof t=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:r=ro,onError:o=ro,onRetry:c=ro,onComment:u}=t;let f="",m=!0,g,C="",x="";function A(D){const B=m?D.replace(/^\xEF\xBB\xBF/,""):D,[G,Z]=Od(`${f}${B}`);for(const U of G)v(U);f=Z,m=!1}function v(D){if(D===""){O();return}if(D.startsWith(":")){u&&u(D.slice(D.startsWith(": ")?2:1));return}const B=D.indexOf(":");if(B!==-1){const G=D.slice(0,B),Z=D[B+1]===" "?2:1,U=D.slice(B+Z);P(G,U,D);return}P(D,"",D)}function P(D,B,G){switch(D){case"event":x=B;break;case"data":C=`${C}${B}
|
|
4
|
+
`;break;case"id":g=B.includes("\0")?void 0:B;break;case"retry":/^\d+$/.test(B)?c(parseInt(B,10)):o(new vs(`Invalid \`retry\` value: "${B}"`,{type:"invalid-retry",value:B,line:G}));break;default:o(new vs(`Unknown field "${D.length>20?`${D.slice(0,20)}…`:D}"`,{type:"unknown-field",field:D,value:B,line:G}));break}}function O(){C.length>0&&r({id:g,event:x||void 0,data:C.endsWith(`
|
|
5
|
+
`)?C.slice(0,-1):C}),g=void 0,C="",x=""}function M(D={}){f&&D.consume&&v(f),m=!0,g=void 0,C="",x="",f=""}return{feed:A,reset:M}}function Od(t){const r=[];let o="",c=0;for(;c<t.length;){const u=t.indexOf("\r",c),f=t.indexOf(`
|
|
6
|
+
`,c);let m=-1;if(u!==-1&&f!==-1?m=Math.min(u,f):u!==-1?u===t.length-1?m=-1:m=u:f!==-1&&(m=f),m===-1){o=t.slice(c);break}else{const g=t.slice(c,m);r.push(g),c=m+1,t[c-1]==="\r"&&t[c]===`
|
|
7
|
+
`&&c++}}return[r,o]}class jl extends TransformStream{constructor({onError:r,onRetry:o,onComment:c}={}){let u;super({start(f){u=Nd({onEvent:m=>{f.enqueue(m)},onError(m){r==="terminate"?f.error(m):typeof r=="function"&&r(m)},onRetry:o,onComment:c})},transform(f){u.feed(f)}})}}function ee(t,r,o){function c(g,C){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,C);for(const A in m.prototype)A in g||Object.defineProperty(g,A,{value:m.prototype[A].bind(g)});g._zod.constr=m,g._zod.def=C}const u=o?.Parent??Object;class f extends u{}Object.defineProperty(f,"name",{value:t});function m(g){var C;const x=o?.Parent?new f:this;c(x,g),(C=x._zod).deferred??(C.deferred=[]);for(const A of x._zod.deferred)A();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 Gl={};function Qn(t){return Gl}function Xl(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 kd(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 Rd(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 tt(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 Ur(t){return JSON.stringify(t)}const ql=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Si(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const Md=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 Dd=new Set(["string","number","symbol"]);function ni(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pr(t,r,o){const c=new t._zod.constr(r??t._zod.def);return(!r||o?.parent)&&(c._zod.parent=t),c}function Ae(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 Pd(t){return Object.keys(t).filter(r=>t[r]._zod.optin==="optional"&&t[r]._zod.optout==="optional")}const Bd={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 Ld(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 pr(t,{...t._zod.def,shape:o,checks:[]})}function Fd(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 pr(t,{...t._zod.def,shape:o,checks:[]})}function Ud(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 pr(t,o)}function zd(t,r){return pr(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 Vd(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 pr(r,{...r._zod.def,shape:u,checks:[]})}function Zd(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 pr(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 dr(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 er(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 Yl=(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,kd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Kl=ee("$ZodError",Yl),Jl=ee("$ZodError",Yl,{Parent:Error});function $d(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 Hd(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,C=0;for(;C<m.path.length;){const x=m.path[C];C===m.path.length-1?(g[x]=g[x]||{_errors:[]},g[x]._errors.push(o(m))):g[x]=g[x]||{_errors:[]},g=g[x],C++}}};return u(t),c}const Wd=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(C=>er(C,f,Qn())));throw ql(g,u?.callee),g}return m.value},jd=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(C=>er(C,f,Qn())));throw ql(g,u?.callee),g}return m.value},Ql=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??Kl)(f.issues.map(m=>er(m,u,Qn())))}:{success:!0,data:f.value}},Gd=Ql(Jl),ec=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=>er(m,u,Qn())))}:{success:!0,data:f.value}},Xd=ec(Jl),qd=/^[cC][^\s-]{8,}$/,Yd=/^[0-9a-z]+$/,Kd=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Jd=/^[0-9a-vA-V]{20}$/,Qd=/^[A-Za-z0-9]{27}$/,e1=/^[a-zA-Z0-9_-]{21}$/,t1=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,n1=/^([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})$/,Cs=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)$/,r1=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,i1="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function o1(){return new RegExp(i1,"u")}const s1=/^(?:(?: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])$/,a1=/^(([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})$/,l1=/^((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])$/,u1=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,tc=/^[A-Za-z0-9_-]*$/,d1=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,f1=/^\+(?:[0-9]){6,14}[0-9]$/,nc="(?:(?:\\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])))",h1=new RegExp(`^${nc}$`);function rc(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 p1(t){return new RegExp(`^${rc(t)}$`)}function m1(t){const r=rc({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(`^${nc}T(?:${c})$`)}const g1=t=>{const r=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${r}$`)},x1=/^\d+$/,y1=/^-?\d+(?:\.\d+)?/i,w1=/true|false/i,_1=/null/i,v1=/^[^A-Z]*$/,C1=/^[^a-z]*$/,on=ee("$ZodCheck",(t,r)=>{var o;t._zod??(t._zod={}),t._zod.def=r,(o=t._zod).onattach??(o.onattach=[])}),ic={number:"number",bigint:"bigint",object:"date"},oc=ee("$ZodCheckLessThan",(t,r)=>{on.init(t,r);const o=ic[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})}}),sc=ee("$ZodCheckGreaterThan",(t,r)=>{on.init(t,r);const o=ic[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})}}),b1=ee("$ZodCheckMultipleOf",(t,r)=>{on.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):Rd(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})}}),E1=ee("$ZodCheckNumberFormat",(t,r)=>{on.init(t,r),r.format=r.format||"float64";const o=r.format?.includes("int"),c=o?"int":"number",[u,f]=Bd[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=x1)}),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})}}),A1=ee("$ZodCheckMaxLength",(t,r)=>{var o;on.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})}}),I1=ee("$ZodCheckMinLength",(t,r)=>{var o;on.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})}}),S1=ee("$ZodCheckLengthEquals",(t,r)=>{var o;on.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=ee("$ZodCheckStringFormat",(t,r)=>{var o,c;on.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=()=>{})}),T1=ee("$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})}}),N1=ee("$ZodCheckLowerCase",(t,r)=>{r.pattern??(r.pattern=v1),Di.init(t,r)}),O1=ee("$ZodCheckUpperCase",(t,r)=>{r.pattern??(r.pattern=C1),Di.init(t,r)}),k1=ee("$ZodCheckIncludes",(t,r)=>{on.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})}}),R1=ee("$ZodCheckStartsWith",(t,r)=>{on.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})}}),M1=ee("$ZodCheckEndsWith",(t,r)=>{on.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})}}),D1=ee("$ZodCheckOverwrite",(t,r)=>{on.init(t,r),t._zod.check=o=>{o.value=r.tx(o.value)}});class P1{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(`
|
|
8
|
+
`).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(`
|
|
9
|
+
`))}}const B1={major:4,minor:0,patch:0},at=ee("$ZodType",(t,r)=>{var o;t??(t={}),t._zod.def=r,t._zod.bag=t._zod.bag||{},t._zod.version=B1;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 C=Gr(f),x;for(const A of m){if(A._zod.def.when){if(!A._zod.def.when(f))continue}else if(C)continue;const v=f.issues.length,P=A._zod.check(f);if(P instanceof Promise&&g?.async===!1)throw new Yr;if(x||P instanceof Promise)x=(x??Promise.resolve()).then(async()=>{await P,f.issues.length!==v&&(C||(C=Gr(f,v)))});else{if(f.issues.length===v)continue;C||(C=Gr(f,v))}}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(C=>u(C,c,m))}return u(g,c,m)}}t["~standard"]={validate:u=>{try{const f=Gd(t,u);return f.success?{value:f.data}:{issues:f.error?.issues}}catch{return Xd(t,u).then(m=>m.success?{value:m.data}:{issues:m.error?.issues})}},vendor:"zod",version:1}}),Vo=ee("$ZodString",(t,r)=>{at.init(t,r),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??g1(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}}),xt=ee("$ZodStringFormat",(t,r)=>{Di.init(t,r),Vo.init(t,r)}),L1=ee("$ZodGUID",(t,r)=>{r.pattern??(r.pattern=n1),xt.init(t,r)}),F1=ee("$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=Cs(c))}else r.pattern??(r.pattern=Cs());xt.init(t,r)}),U1=ee("$ZodEmail",(t,r)=>{r.pattern??(r.pattern=r1),xt.init(t,r)}),z1=ee("$ZodURL",(t,r)=>{xt.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:d1.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})}}}),V1=ee("$ZodEmoji",(t,r)=>{r.pattern??(r.pattern=o1()),xt.init(t,r)}),Z1=ee("$ZodNanoID",(t,r)=>{r.pattern??(r.pattern=e1),xt.init(t,r)}),$1=ee("$ZodCUID",(t,r)=>{r.pattern??(r.pattern=qd),xt.init(t,r)}),H1=ee("$ZodCUID2",(t,r)=>{r.pattern??(r.pattern=Yd),xt.init(t,r)}),W1=ee("$ZodULID",(t,r)=>{r.pattern??(r.pattern=Kd),xt.init(t,r)}),j1=ee("$ZodXID",(t,r)=>{r.pattern??(r.pattern=Jd),xt.init(t,r)}),G1=ee("$ZodKSUID",(t,r)=>{r.pattern??(r.pattern=Qd),xt.init(t,r)}),X1=ee("$ZodISODateTime",(t,r)=>{r.pattern??(r.pattern=m1(r)),xt.init(t,r)}),q1=ee("$ZodISODate",(t,r)=>{r.pattern??(r.pattern=h1),xt.init(t,r)}),Y1=ee("$ZodISOTime",(t,r)=>{r.pattern??(r.pattern=p1(r)),xt.init(t,r)}),K1=ee("$ZodISODuration",(t,r)=>{r.pattern??(r.pattern=t1),xt.init(t,r)}),J1=ee("$ZodIPv4",(t,r)=>{r.pattern??(r.pattern=s1),xt.init(t,r),t._zod.onattach.push(o=>{const c=o._zod.bag;c.format="ipv4"})}),Q1=ee("$ZodIPv6",(t,r)=>{r.pattern??(r.pattern=a1),xt.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})}}}),e0=ee("$ZodCIDRv4",(t,r)=>{r.pattern??(r.pattern=l1),xt.init(t,r)}),t0=ee("$ZodCIDRv6",(t,r)=>{r.pattern??(r.pattern=c1),xt.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 ac(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const n0=ee("$ZodBase64",(t,r)=>{r.pattern??(r.pattern=u1),xt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64"}),t._zod.check=o=>{ac(o.value)||o.issues.push({code:"invalid_format",format:"base64",input:o.value,inst:t,continue:!r.abort})}});function r0(t){if(!tc.test(t))return!1;const r=t.replace(/[-_]/g,c=>c==="-"?"+":"/"),o=r.padEnd(Math.ceil(r.length/4)*4,"=");return ac(o)}const i0=ee("$ZodBase64URL",(t,r)=>{r.pattern??(r.pattern=tc),xt.init(t,r),t._zod.onattach.push(o=>{o._zod.bag.contentEncoding="base64url"}),t._zod.check=o=>{r0(o.value)||o.issues.push({code:"invalid_format",format:"base64url",input:o.value,inst:t,continue:!r.abort})}}),o0=ee("$ZodE164",(t,r)=>{r.pattern??(r.pattern=f1),xt.init(t,r)});function s0(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 a0=ee("$ZodJWT",(t,r)=>{xt.init(t,r),t._zod.check=o=>{s0(o.value,r.alg)||o.issues.push({code:"invalid_format",format:"jwt",input:o.value,inst:t,continue:!r.abort})}}),lc=ee("$ZodNumber",(t,r)=>{at.init(t,r),t._zod.pattern=t._zod.bag.pattern??y1,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}}),l0=ee("$ZodNumber",(t,r)=>{E1.init(t,r),lc.init(t,r)}),c0=ee("$ZodBoolean",(t,r)=>{at.init(t,r),t._zod.pattern=w1,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}}),u0=ee("$ZodNull",(t,r)=>{at.init(t,r),t._zod.pattern=_1,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}}),d0=ee("$ZodAny",(t,r)=>{at.init(t,r),t._zod.parse=o=>o}),f0=ee("$ZodUnknown",(t,r)=>{at.init(t,r),t._zod.parse=o=>o}),h0=ee("$ZodNever",(t,r)=>{at.init(t,r),t._zod.parse=(o,c)=>(o.issues.push({expected:"never",code:"invalid_type",input:o.value,inst:t}),o)});function bs(t,r,o){t.issues.length&&r.issues.push(...dr(o,t.issues)),r.value[o]=t.value}const p0=ee("$ZodArray",(t,r)=>{at.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],C=r.element._zod.run({value:g,issues:[]},c);C instanceof Promise?f.push(C.then(x=>bs(x,o,m))):bs(C,o,m)}return f.length?Promise.all(f).then(()=>o):o}});function xi(t,r,o){t.issues.length&&r.issues.push(...dr(o,t.issues)),r.value[o]=t.value}function Es(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(...dr(o,t.issues)):t.value===void 0?o in c&&(r.value[o]=void 0):r.value[o]=t.value}const m0=ee("$ZodObject",(t,r)=>{at.init(t,r);const o=Bo(()=>{const v=Object.keys(r.shape);for(const O of v)if(!(r.shape[O]instanceof at))throw new Error(`Invalid element at key "${O}": expected a Zod schema`);const P=Pd(r.shape);return{shape:r.shape,keys:v,keySet:new Set(v),numKeys:v.length,optionalKeys:new Set(P)}});tt(t._zod,"propValues",()=>{const v=r.shape,P={};for(const O in v){const M=v[O]._zod;if(M.values){P[O]??(P[O]=new Set);for(const D of M.values)P[O].add(D)}}return P});const c=v=>{const P=new P1(["shape","payload","ctx"]),O=o.value,M=Z=>{const U=Ur(Z);return`shape[${U}]._zod.run({ value: input[${U}], issues: [] }, ctx)`};P.write("const input = payload.value;");const D=Object.create(null);let B=0;for(const Z of O.keys)D[Z]=`key_${B++}`;P.write("const newResult = {}");for(const Z of O.keys)if(O.optionalKeys.has(Z)){const U=D[Z];P.write(`const ${U} = ${M(Z)};`);const Q=Ur(Z);P.write(`
|
|
10
10
|
if (${U}.issues.length) {
|
|
11
|
-
if (input[${
|
|
12
|
-
if (${
|
|
13
|
-
newResult[${
|
|
11
|
+
if (input[${Q}] === undefined) {
|
|
12
|
+
if (${Q} in input) {
|
|
13
|
+
newResult[${Q}] = undefined;
|
|
14
14
|
}
|
|
15
15
|
} else {
|
|
16
16
|
payload.issues = payload.issues.concat(
|
|
17
17
|
${U}.issues.map((iss) => ({
|
|
18
18
|
...iss,
|
|
19
|
-
path: iss.path ? [${
|
|
19
|
+
path: iss.path ? [${Q}, ...iss.path] : [${Q}],
|
|
20
20
|
}))
|
|
21
21
|
);
|
|
22
22
|
}
|
|
23
23
|
} else if (${U}.value === undefined) {
|
|
24
|
-
if (${
|
|
24
|
+
if (${Q} in input) newResult[${Q}] = undefined;
|
|
25
25
|
} else {
|
|
26
|
-
newResult[${
|
|
26
|
+
newResult[${Q}] = ${U}.value;
|
|
27
27
|
}
|
|
28
|
-
`)}else{const U=D[
|
|
28
|
+
`)}else{const U=D[Z];P.write(`const ${U} = ${M(Z)};`),P.write(`
|
|
29
29
|
if (${U}.issues.length) payload.issues = payload.issues.concat(${U}.issues.map(iss => ({
|
|
30
30
|
...iss,
|
|
31
|
-
path: iss.path ? [${
|
|
32
|
-
})));`),B.write(`newResult[${Pr($)}] = ${U}.value`)}B.write("payload.value = newResult;"),B.write("return payload;");const Y=B.compile();return($,U)=>Y(A,$,U)};let u;const f=Ii,g=!$l.jitless,v=g&&Rd.value,x=r.catchall;let E;t._zod.parse=(A,B)=>{E??(E=o.value);const O=A.value;if(!f(O))return A.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),A;const R=[];if(g&&v&&B?.async===!1&&B.jitless!==!0)u||(u=c(r.shape)),A=u(A,B);else{A.value={};const U=E.shape;for(const W of E.keys){const X=U[W],H=X._zod.run({value:O[W],issues:[]},B),z=X._zod.optin==="optional"&&X._zod.optout==="optional";H instanceof Promise?R.push(H.then(V=>z?_s(V,A,W,O):mi(V,A,W))):z?_s(H,A,W,O):mi(H,A,W)}}if(!x)return R.length?Promise.all(R).then(()=>A):A;const D=[],P=E.keySet,Y=x._zod,$=Y.def.type;for(const U of Object.keys(O)){if(P.has(U))continue;if($==="never"){D.push(U);continue}const W=Y.run({value:O[U],issues:[]},B);W instanceof Promise?R.push(W.then(X=>mi(X,A,U))):mi(W,A,U)}return D.length&&A.issues.push({code:"unrecognized_keys",keys:D,input:O,inst:t}),R.length?Promise.all(R).then(()=>A):A}});function vs(t,r,o,c){for(const u of t)if(u.issues.length===0)return r.value=u.value,r;return r.issues.push({code:"invalid_union",input:r.value,inst:o,errors:t.map(u=>u.issues.map(f=>qn(f,c,Xn())))}),r}const oc=ne("$ZodUnion",(t,r)=>{ot.init(t,r),Qe(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),Qe(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Qe(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),Qe(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=>Po(c.source)).join("|")})$`)}}),t._zod.parse=(o,c)=>{let u=!1;const f=[];for(const g of r.options){const m=g._zod.run({value:o.value,issues:[]},c);if(m instanceof Promise)f.push(m),u=!0;else{if(m.issues.length===0)return m;f.push(m)}}return u?Promise.all(f).then(g=>vs(g,o,t,c)):vs(f,o,t,c)}}),g0=ne("$ZodDiscriminatedUnion",(t,r)=>{oc.init(t,r);const o=t._zod.parse;Qe(t._zod,"propValues",()=>{const u={};for(const f of r.options){const g=f._zod.propValues;if(!g||Object.keys(g).length===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(f)}"`);for(const[m,v]of Object.entries(g)){u[m]||(u[m]=new Set);for(const x of v)u[m].add(x)}}return u});const c=Mo(()=>{const u=r.options,f=new Map;for(const g of u){const m=g._zod.propValues[r.discriminator];if(!m||m.size===0)throw new Error(`Invalid discriminated union option at index "${r.options.indexOf(g)}"`);for(const v of m){if(f.has(v))throw new Error(`Duplicate discriminator value "${String(v)}"`);f.set(v,g)}}return f});t._zod.parse=(u,f)=>{const g=u.value;if(!Ii(g))return u.issues.push({code:"invalid_type",expected:"object",input:g,inst:t}),u;const m=c.value.get(g?.[r.discriminator]);return m?m._zod.run(u,f):r.unionFallback?o(u,f):(u.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:g,path:[r.discriminator],inst:t}),u)}}),m0=ne("$ZodIntersection",(t,r)=>{ot.init(t,r),t._zod.parse=(o,c)=>{const u=o.value,f=r.left._zod.run({value:u,issues:[]},c),g=r.right._zod.run({value:u,issues:[]},c);return f instanceof Promise||g instanceof Promise?Promise.all([f,g]).then(([v,x])=>Cs(o,v,x)):Cs(o,f,g)}});function wo(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(Si(t)&&Si(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 g=wo(t[f],r[f]);if(!g.valid)return{valid:!1,mergeErrorPath:[f,...g.mergeErrorPath]};u[f]=g.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],g=wo(u,f);if(!g.valid)return{valid:!1,mergeErrorPath:[c,...g.mergeErrorPath]};o.push(g.data)}return{valid:!0,data:o}}return{valid:!1,mergeErrorPath:[]}}function Cs(t,r,o){if(r.issues.length&&t.issues.push(...r.issues),o.issues.length&&t.issues.push(...o.issues),Wr(t))return t;const c=wo(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 x0=ne("$ZodRecord",(t,r)=>{ot.init(t,r),t._zod.parse=(o,c)=>{const u=o.value;if(!Si(u))return o.issues.push({expected:"record",code:"invalid_type",input:u,inst:t}),o;const f=[];if(r.keyType._zod.values){const g=r.keyType._zod.values;o.value={};for(const v of g)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(...ar(v,E.issues)),o.value[v]=E.value})):(x.issues.length&&o.issues.push(...ar(v,x.issues)),o.value[v]=x.value)}let m;for(const v in u)g.has(v)||(m=m??[],m.push(v));m&&m.length>0&&o.issues.push({code:"unrecognized_keys",input:u,inst:t,keys:m})}else{o.value={};for(const g of Reflect.ownKeys(u)){if(g==="__proto__")continue;const m=r.keyType._zod.run({value:g,issues:[]},c);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(m.issues.length){o.issues.push({origin:"record",code:"invalid_key",issues:m.issues.map(x=>qn(x,c,Xn())),input:g,path:[g],inst:t}),o.value[m.value]=m.value;continue}const v=r.valueType._zod.run({value:u[g],issues:[]},c);v instanceof Promise?f.push(v.then(x=>{x.issues.length&&o.issues.push(...ar(g,x.issues)),o.value[m.value]=x.value})):(v.issues.length&&o.issues.push(...ar(g,v.issues)),o.value[m.value]=v.value)}}return f.length?Promise.all(f).then(()=>o):o}}),w0=ne("$ZodEnum",(t,r)=>{ot.init(t,r);const o=Wl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Md.has(typeof c)).map(c=>typeof c=="string"?Qr(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}}),y0=ne("$ZodLiteral",(t,r)=>{ot.init(t,r),t._zod.values=new Set(r.values),t._zod.pattern=new RegExp(`^(${r.values.map(o=>typeof o=="string"?Qr(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}}),_0=ne("$ZodTransform",(t,r)=>{ot.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(g=>(o.value=g,o));if(u instanceof Promise)throw new Gr;return o.value=u,o}}),v0=ne("$ZodOptional",(t,r)=>{ot.init(t,r),t._zod.optin="optional",t._zod.optout="optional",Qe(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),Qe(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Po(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)}),C0=ne("$ZodNullable",(t,r)=>{ot.init(t,r),Qe(t._zod,"optin",()=>r.innerType._zod.optin),Qe(t._zod,"optout",()=>r.innerType._zod.optout),Qe(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Po(o.source)}|null)$`):void 0}),Qe(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)}),b0=ne("$ZodDefault",(t,r)=>{ot.init(t,r),t._zod.optin="optional",Qe(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=>bs(f,r)):bs(u,r)}});function bs(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const E0=ne("$ZodPrefault",(t,r)=>{ot.init(t,r),t._zod.optin="optional",Qe(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))}),A0=ne("$ZodNonOptional",(t,r)=>{ot.init(t,r),Qe(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=>Es(f,t)):Es(u,t)}});function Es(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 I0=ne("$ZodCatch",(t,r)=>{ot.init(t,r),t._zod.optin="optional",Qe(t._zod,"optout",()=>r.innerType._zod.optout),Qe(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(g=>qn(g,c,Xn()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>qn(f,c,Xn()))},input:o.value}),o.issues=[]),o)}}),S0=ne("$ZodPipe",(t,r)=>{ot.init(t,r),Qe(t._zod,"values",()=>r.in._zod.values),Qe(t._zod,"optin",()=>r.in._zod.optin),Qe(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=>As(f,r,c)):As(u,r,c)}});function As(t,r,o){return Wr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const T0=ne("$ZodReadonly",(t,r)=>{ot.init(t,r),Qe(t._zod,"propValues",()=>r.innerType._zod.propValues),Qe(t._zod,"values",()=>r.innerType._zod.values),Qe(t._zod,"optin",()=>r.innerType._zod.optin),Qe(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(Is):Is(u)}});function Is(t){return t.value=Object.freeze(t.value),t}const N0=ne("$ZodLazy",(t,r)=>{ot.init(t,r),Qe(t._zod,"innerType",()=>r.getter()),Qe(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),Qe(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),Qe(t._zod,"optin",()=>t._zod.innerType._zod.optin),Qe(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),O0=ne("$ZodCustom",(t,r)=>{tn.init(t,r),ot.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=>Ss(f,o,c,t));Ss(u,o,c,t)}});function Ss(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(Xr(u))}}class sc{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 k0(){return new sc}const Vr=k0();function R0(t,r){return new t({type:"string",...ye(r)})}function M0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ye(r)})}function Ts(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ye(r)})}function D0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ye(r)})}function P0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ye(r)})}function B0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ye(r)})}function L0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ye(r)})}function F0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ye(r)})}function U0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ye(r)})}function z0(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ye(r)})}function V0(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ye(r)})}function Z0(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ye(r)})}function $0(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ye(r)})}function W0(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ye(r)})}function H0(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ye(r)})}function j0(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ye(r)})}function G0(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ye(r)})}function X0(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ye(r)})}function q0(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ye(r)})}function Y0(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ye(r)})}function K0(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ye(r)})}function J0(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ye(r)})}function Q0(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ye(r)})}function ef(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ye(r)})}function tf(t,r){return new t({type:"string",format:"date",check:"string_format",...ye(r)})}function nf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...ye(r)})}function rf(t,r){return new t({type:"string",format:"duration",check:"string_format",...ye(r)})}function of(t,r){return new t({type:"number",checks:[],...ye(r)})}function sf(t,r){return new t({type:"number",coerce:!0,checks:[],...ye(r)})}function af(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ye(r)})}function lf(t,r){return new t({type:"boolean",...ye(r)})}function cf(t,r){return new t({type:"null",...ye(r)})}function uf(t){return new t({type:"any"})}function df(t){return new t({type:"unknown"})}function ff(t,r){return new t({type:"never",...ye(r)})}function Ns(t,r){return new tc({check:"less_than",...ye(r),value:t,inclusive:!1})}function io(t,r){return new tc({check:"less_than",...ye(r),value:t,inclusive:!0})}function Os(t,r){return new nc({check:"greater_than",...ye(r),value:t,inclusive:!1})}function oo(t,r){return new nc({check:"greater_than",...ye(r),value:t,inclusive:!0})}function ks(t,r){return new C1({check:"multiple_of",...ye(r),value:t})}function ac(t,r){return new E1({check:"max_length",...ye(r),maximum:t})}function Ti(t,r){return new A1({check:"min_length",...ye(r),minimum:t})}function lc(t,r){return new I1({check:"length_equals",...ye(r),length:t})}function hf(t,r){return new S1({check:"string_format",format:"regex",...ye(r),pattern:t})}function pf(t){return new T1({check:"string_format",format:"lowercase",...ye(t)})}function gf(t){return new N1({check:"string_format",format:"uppercase",...ye(t)})}function mf(t,r){return new O1({check:"string_format",format:"includes",...ye(r),includes:t})}function xf(t,r){return new k1({check:"string_format",format:"starts_with",...ye(r),prefix:t})}function wf(t,r){return new R1({check:"string_format",format:"ends_with",...ye(r),suffix:t})}function ei(t){return new M1({check:"overwrite",tx:t})}function yf(t){return ei(r=>r.normalize(t))}function _f(){return ei(t=>t.trim())}function vf(){return ei(t=>t.toLowerCase())}function Cf(){return ei(t=>t.toUpperCase())}function bf(t,r,o){return new t({type:"array",element:r,...ye(o)})}function Ef(t,r,o){return new t({type:"custom",check:"custom",fn:r,...ye(o)})}class Rs{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??Vr,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:""},g=this.seen.get(r);if(g)return g.count++,o.schemaPath.includes(r)&&(g.cycle=o.path),g.schema;const m={schema:{},count:1,cycle:void 0,path:o.path};this.seen.set(r,m);const v=r._zod.toJSONSchema?.();if(v)m.schema=v;else{const A={...o,schemaPath:[...o.schemaPath,r],path:o.path},B=r._zod.parent;if(B)m.ref=B,this.process(B,A),this.seen.get(B).isParent=!0;else{const O=m.schema;switch(u.type){case"string":{const R=O;R.type="string";const{minimum:D,maximum:P,format:Y,patterns:$,contentEncoding:U}=r._zod.bag;if(typeof D=="number"&&(R.minLength=D),typeof P=="number"&&(R.maxLength=P),Y&&(R.format=f[Y]??Y,R.format===""&&delete R.format),U&&(R.contentEncoding=U),$&&$.size>0){const W=[...$];W.length===1?R.pattern=W[0].source:W.length>1&&(m.schema.allOf=[...W.map(X=>({...this.target==="draft-7"?{type:"string"}:{},pattern:X.source}))])}break}case"number":{const R=O,{minimum:D,maximum:P,format:Y,multipleOf:$,exclusiveMaximum:U,exclusiveMinimum:W}=r._zod.bag;typeof Y=="string"&&Y.includes("int")?R.type="integer":R.type="number",typeof W=="number"&&(R.exclusiveMinimum=W),typeof D=="number"&&(R.minimum=D,typeof W=="number"&&(W>=D?delete R.minimum:delete R.exclusiveMinimum)),typeof U=="number"&&(R.exclusiveMaximum=U),typeof P=="number"&&(R.maximum=P,typeof U=="number"&&(U<=P?delete R.maximum:delete R.exclusiveMaximum)),typeof $=="number"&&(R.multipleOf=$);break}case"boolean":{const R=O;R.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{O.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{O.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const R=O,{minimum:D,maximum:P}=r._zod.bag;typeof D=="number"&&(R.minItems=D),typeof P=="number"&&(R.maxItems=P),R.type="array",R.items=this.process(u.element,{...A,path:[...A.path,"items"]});break}case"object":{const R=O;R.type="object",R.properties={};const D=u.shape;for(const $ in D)R.properties[$]=this.process(D[$],{...A,path:[...A.path,"properties",$]});const P=new Set(Object.keys(D)),Y=new Set([...P].filter($=>{const U=u.shape[$]._zod;return this.io==="input"?U.optin===void 0:U.optout===void 0}));Y.size>0&&(R.required=Array.from(Y)),u.catchall?._zod.def.type==="never"?R.additionalProperties=!1:u.catchall?u.catchall&&(R.additionalProperties=this.process(u.catchall,{...A,path:[...A.path,"additionalProperties"]})):this.io==="output"&&(R.additionalProperties=!1);break}case"union":{const R=O;R.anyOf=u.options.map((D,P)=>this.process(D,{...A,path:[...A.path,"anyOf",P]}));break}case"intersection":{const R=O,D=this.process(u.left,{...A,path:[...A.path,"allOf",0]}),P=this.process(u.right,{...A,path:[...A.path,"allOf",1]}),Y=U=>"allOf"in U&&Object.keys(U).length===1,$=[...Y(D)?D.allOf:[D],...Y(P)?P.allOf:[P]];R.allOf=$;break}case"tuple":{const R=O;R.type="array";const D=u.items.map(($,U)=>this.process($,{...A,path:[...A.path,"prefixItems",U]}));if(this.target==="draft-2020-12"?R.prefixItems=D:R.items=D,u.rest){const $=this.process(u.rest,{...A,path:[...A.path,"items"]});this.target==="draft-2020-12"?R.items=$:R.additionalItems=$}u.rest&&(R.items=this.process(u.rest,{...A,path:[...A.path,"items"]}));const{minimum:P,maximum:Y}=r._zod.bag;typeof P=="number"&&(R.minItems=P),typeof Y=="number"&&(R.maxItems=Y);break}case"record":{const R=O;R.type="object",R.propertyNames=this.process(u.keyType,{...A,path:[...A.path,"propertyNames"]}),R.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 R=O,D=Wl(u.entries);D.every(P=>typeof P=="number")&&(R.type="number"),D.every(P=>typeof P=="string")&&(R.type="string"),R.enum=D;break}case"literal":{const R=O,D=[];for(const P of u.values)if(P===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof P=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");D.push(Number(P))}else D.push(P);if(D.length!==0)if(D.length===1){const P=D[0];R.type=P===null?"null":typeof P,R.const=P}else D.every(P=>typeof P=="number")&&(R.type="number"),D.every(P=>typeof P=="string")&&(R.type="string"),D.every(P=>typeof P=="boolean")&&(R.type="string"),D.every(P=>P===null)&&(R.type="null"),R.enum=D;break}case"file":{const R=O,D={type:"string",format:"binary",contentEncoding:"binary"},{minimum:P,maximum:Y,mime:$}=r._zod.bag;P!==void 0&&(D.minLength=P),Y!==void 0&&(D.maxLength=Y),$?$.length===1?(D.contentMediaType=$[0],Object.assign(R,D)):R.anyOf=$.map(U=>({...D,contentMediaType:U})):Object.assign(R,D);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const R=this.process(u.innerType,A);O.anyOf=[R,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,A),m.ref=u.innerType;break}case"success":{const R=O;R.type="boolean";break}case"default":{this.process(u.innerType,A),m.ref=u.innerType,O.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,A),m.ref=u.innerType,this.io==="input"&&(O._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,A),m.ref=u.innerType;let R;try{R=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}O.default=R;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const R=O,D=r._zod.pattern;if(!D)throw new Error("Pattern not found in template literal");R.type="string",R.pattern=D.source;break}case"pipe":{const R=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(R,A),m.ref=R;break}case"readonly":{this.process(u.innerType,A),m.ref=u.innerType,O.readOnly=!0;break}case"promise":{this.process(u.innerType,A),m.ref=u.innerType;break}case"optional":{this.process(u.innerType,A),m.ref=u.innerType;break}case"lazy":{const R=r._zod.innerType;this.process(R,A),m.ref=R;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(m.schema,x),this.io==="input"&&Ot(r)&&(delete m.schema.examples,delete m.schema.default),this.io==="input"&&m.schema._prefault&&((c=m.schema).default??(c.default=m.schema._prefault)),delete m.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 D=c.external.registry.get(E[0])?.id,P=c.external.uri??($=>$);if(D)return{ref:P(D)};const Y=E[1].defId??E[1].schema.id??`schema${this.counter++}`;return E[1].defId=Y,{defId:Y,ref:`${P("__shared")}#/${A}/${Y}`}}if(E[1]===u)return{ref:"#"};const O=`#/${A}/`,R=E[1].schema.id??`__schema${this.counter++}`;return{defId:R,ref:O+R}},g=E=>{if(E[1].schema.$ref)return;const A=E[1],{ref:B,defId:O}=f(E);A.def={...A.schema},O&&(A.defId=O);const R=A.schema;for(const D in R)delete R[D];R.$ref=B};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>
|
|
31
|
+
path: iss.path ? [${Ur(Z)}, ...iss.path] : [${Ur(Z)}]
|
|
32
|
+
})));`),P.write(`newResult[${Ur(Z)}] = ${U}.value`)}P.write("payload.value = newResult;"),P.write("return payload;");const G=P.compile();return(Z,U)=>G(v,Z,U)};let u;const f=Si,m=!Gl.jitless,C=m&&Md.value,x=r.catchall;let A;t._zod.parse=(v,P)=>{A??(A=o.value);const O=v.value;if(!f(O))return v.issues.push({expected:"object",code:"invalid_type",input:O,inst:t}),v;const M=[];if(m&&C&&P?.async===!1&&P.jitless!==!0)u||(u=c(r.shape)),v=u(v,P);else{v.value={};const U=A.shape;for(const Q of A.keys){const K=U[Q],V=K._zod.run({value:O[Q],issues:[]},P),z=K._zod.optin==="optional"&&K._zod.optout==="optional";V instanceof Promise?M.push(V.then(te=>z?Es(te,v,Q,O):xi(te,v,Q))):z?Es(V,v,Q,O):xi(V,v,Q)}}if(!x)return M.length?Promise.all(M).then(()=>v):v;const D=[],B=A.keySet,G=x._zod,Z=G.def.type;for(const U of Object.keys(O)){if(B.has(U))continue;if(Z==="never"){D.push(U);continue}const Q=G.run({value:O[U],issues:[]},P);Q instanceof Promise?M.push(Q.then(K=>xi(K,v,U))):xi(Q,v,U)}return D.length&&v.issues.push({code:"unrecognized_keys",keys:D,input:O,inst:t}),M.length?Promise.all(M).then(()=>v):v}});function As(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=>er(f,c,Qn())))}),r}const cc=ee("$ZodUnion",(t,r)=>{at.init(t,r),tt(t._zod,"optin",()=>r.options.some(o=>o._zod.optin==="optional")?"optional":void 0),tt(t._zod,"optout",()=>r.options.some(o=>o._zod.optout==="optional")?"optional":void 0),tt(t._zod,"values",()=>{if(r.options.every(o=>o._zod.values))return new Set(r.options.flatMap(o=>Array.from(o._zod.values)))}),tt(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=>As(m,o,t,c)):As(f,o,t,c)}}),g0=ee("$ZodDiscriminatedUnion",(t,r)=>{cc.init(t,r);const o=t._zod.parse;tt(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,C]of Object.entries(m)){u[g]||(u[g]=new Set);for(const x of C)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 C of g){if(f.has(C))throw new Error(`Duplicate discriminator value "${String(C)}"`);f.set(C,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)}}),x0=ee("$ZodIntersection",(t,r)=>{at.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(([C,x])=>Is(o,C,x)):Is(o,f,m)}});function wo(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=wo(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=wo(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 Is(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=wo(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 y0=ee("$ZodRecord",(t,r)=>{at.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 C of m)if(typeof C=="string"||typeof C=="number"||typeof C=="symbol"){const x=r.valueType._zod.run({value:u[C],issues:[]},c);x instanceof Promise?f.push(x.then(A=>{A.issues.length&&o.issues.push(...dr(C,A.issues)),o.value[C]=A.value})):(x.issues.length&&o.issues.push(...dr(C,x.issues)),o.value[C]=x.value)}let g;for(const C in u)m.has(C)||(g=g??[],g.push(C));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=>er(x,c,Qn())),input:m,path:[m],inst:t}),o.value[g.value]=g.value;continue}const C=r.valueType._zod.run({value:u[m],issues:[]},c);C instanceof Promise?f.push(C.then(x=>{x.issues.length&&o.issues.push(...dr(m,x.issues)),o.value[g.value]=x.value})):(C.issues.length&&o.issues.push(...dr(m,C.issues)),o.value[g.value]=C.value)}}return f.length?Promise.all(f).then(()=>o):o}}),w0=ee("$ZodEnum",(t,r)=>{at.init(t,r);const o=Xl(r.entries);t._zod.values=new Set(o),t._zod.pattern=new RegExp(`^(${o.filter(c=>Dd.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}}),_0=ee("$ZodLiteral",(t,r)=>{at.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}}),v0=ee("$ZodTransform",(t,r)=>{at.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}}),C0=ee("$ZodOptional",(t,r)=>{at.init(t,r),t._zod.optin="optional",t._zod.optout="optional",tt(t._zod,"values",()=>r.innerType._zod.values?new Set([...r.innerType._zod.values,void 0]):void 0),tt(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)}),b0=ee("$ZodNullable",(t,r)=>{at.init(t,r),tt(t._zod,"optin",()=>r.innerType._zod.optin),tt(t._zod,"optout",()=>r.innerType._zod.optout),tt(t._zod,"pattern",()=>{const o=r.innerType._zod.pattern;return o?new RegExp(`^(${Fo(o.source)}|null)$`):void 0}),tt(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)}),E0=ee("$ZodDefault",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(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=>Ss(f,r)):Ss(u,r)}});function Ss(t,r){return t.value===void 0&&(t.value=r.defaultValue),t}const A0=ee("$ZodPrefault",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(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))}),I0=ee("$ZodNonOptional",(t,r)=>{at.init(t,r),tt(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=>Ts(f,t)):Ts(u,t)}});function Ts(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 S0=ee("$ZodCatch",(t,r)=>{at.init(t,r),t._zod.optin="optional",tt(t._zod,"optout",()=>r.innerType._zod.optout),tt(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=>er(m,c,Qn()))},input:o.value}),o.issues=[]),o)):(o.value=u.value,u.issues.length&&(o.value=r.catchValue({...o,error:{issues:u.issues.map(f=>er(f,c,Qn()))},input:o.value}),o.issues=[]),o)}}),T0=ee("$ZodPipe",(t,r)=>{at.init(t,r),tt(t._zod,"values",()=>r.in._zod.values),tt(t._zod,"optin",()=>r.in._zod.optin),tt(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=>Ns(f,r,c)):Ns(u,r,c)}});function Ns(t,r,o){return Gr(t)?t:r.out._zod.run({value:t.value,issues:t.issues},o)}const N0=ee("$ZodReadonly",(t,r)=>{at.init(t,r),tt(t._zod,"propValues",()=>r.innerType._zod.propValues),tt(t._zod,"values",()=>r.innerType._zod.values),tt(t._zod,"optin",()=>r.innerType._zod.optin),tt(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(Os):Os(u)}});function Os(t){return t.value=Object.freeze(t.value),t}const O0=ee("$ZodLazy",(t,r)=>{at.init(t,r),tt(t._zod,"innerType",()=>r.getter()),tt(t._zod,"pattern",()=>t._zod.innerType._zod.pattern),tt(t._zod,"propValues",()=>t._zod.innerType._zod.propValues),tt(t._zod,"optin",()=>t._zod.innerType._zod.optin),tt(t._zod,"optout",()=>t._zod.innerType._zod.optout),t._zod.parse=(o,c)=>t._zod.innerType._zod.run(o,c)}),k0=ee("$ZodCustom",(t,r)=>{on.init(t,r),at.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=>ks(f,o,c,t));ks(u,o,c,t)}});function ks(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 uc{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 R0(){return new uc}const Hr=R0();function M0(t,r){return new t({type:"string",...Ae(r)})}function D0(t,r){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Ae(r)})}function Rs(t,r){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Ae(r)})}function P0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Ae(r)})}function B0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ae(r)})}function L0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ae(r)})}function F0(t,r){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ae(r)})}function U0(t,r){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Ae(r)})}function z0(t,r){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Ae(r)})}function V0(t,r){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ae(r)})}function Z0(t,r){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Ae(r)})}function $0(t,r){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ae(r)})}function H0(t,r){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Ae(r)})}function W0(t,r){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Ae(r)})}function j0(t,r){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ae(r)})}function G0(t,r){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ae(r)})}function X0(t,r){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ae(r)})}function q0(t,r){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ae(r)})}function Y0(t,r){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ae(r)})}function K0(t,r){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Ae(r)})}function J0(t,r){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Ae(r)})}function Q0(t,r){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Ae(r)})}function ef(t,r){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Ae(r)})}function tf(t,r){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ae(r)})}function nf(t,r){return new t({type:"string",format:"date",check:"string_format",...Ae(r)})}function rf(t,r){return new t({type:"string",format:"time",check:"string_format",precision:null,...Ae(r)})}function of(t,r){return new t({type:"string",format:"duration",check:"string_format",...Ae(r)})}function sf(t,r){return new t({type:"number",checks:[],...Ae(r)})}function af(t,r){return new t({type:"number",coerce:!0,checks:[],...Ae(r)})}function lf(t,r){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Ae(r)})}function cf(t,r){return new t({type:"boolean",...Ae(r)})}function uf(t,r){return new t({type:"null",...Ae(r)})}function df(t){return new t({type:"any"})}function ff(t){return new t({type:"unknown"})}function hf(t,r){return new t({type:"never",...Ae(r)})}function Ms(t,r){return new oc({check:"less_than",...Ae(r),value:t,inclusive:!1})}function io(t,r){return new oc({check:"less_than",...Ae(r),value:t,inclusive:!0})}function Ds(t,r){return new sc({check:"greater_than",...Ae(r),value:t,inclusive:!1})}function oo(t,r){return new sc({check:"greater_than",...Ae(r),value:t,inclusive:!0})}function Ps(t,r){return new b1({check:"multiple_of",...Ae(r),value:t})}function dc(t,r){return new A1({check:"max_length",...Ae(r),maximum:t})}function Ni(t,r){return new I1({check:"min_length",...Ae(r),minimum:t})}function fc(t,r){return new S1({check:"length_equals",...Ae(r),length:t})}function pf(t,r){return new T1({check:"string_format",format:"regex",...Ae(r),pattern:t})}function mf(t){return new N1({check:"string_format",format:"lowercase",...Ae(t)})}function gf(t){return new O1({check:"string_format",format:"uppercase",...Ae(t)})}function xf(t,r){return new k1({check:"string_format",format:"includes",...Ae(r),includes:t})}function yf(t,r){return new R1({check:"string_format",format:"starts_with",...Ae(r),prefix:t})}function wf(t,r){return new M1({check:"string_format",format:"ends_with",...Ae(r),suffix:t})}function ri(t){return new D1({check:"overwrite",tx:t})}function _f(t){return ri(r=>r.normalize(t))}function vf(){return ri(t=>t.trim())}function Cf(){return ri(t=>t.toLowerCase())}function bf(){return ri(t=>t.toUpperCase())}function Ef(t,r,o){return new t({type:"array",element:r,...Ae(o)})}function Af(t,r,o){return new t({type:"custom",check:"custom",fn:r,...Ae(o)})}class Bs{constructor(r){this.counter=0,this.metadataRegistry=r?.metadata??Hr,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 C=r._zod.toJSONSchema?.();if(C)g.schema=C;else{const v={...o,schemaPath:[...o.schemaPath,r],path:o.path},P=r._zod.parent;if(P)g.ref=P,this.process(P,v),this.seen.get(P).isParent=!0;else{const O=g.schema;switch(u.type){case"string":{const M=O;M.type="string";const{minimum:D,maximum:B,format:G,patterns:Z,contentEncoding:U}=r._zod.bag;if(typeof D=="number"&&(M.minLength=D),typeof B=="number"&&(M.maxLength=B),G&&(M.format=f[G]??G,M.format===""&&delete M.format),U&&(M.contentEncoding=U),Z&&Z.size>0){const Q=[...Z];Q.length===1?M.pattern=Q[0].source:Q.length>1&&(g.schema.allOf=[...Q.map(K=>({...this.target==="draft-7"?{type:"string"}:{},pattern:K.source}))])}break}case"number":{const M=O,{minimum:D,maximum:B,format:G,multipleOf:Z,exclusiveMaximum:U,exclusiveMinimum:Q}=r._zod.bag;typeof G=="string"&&G.includes("int")?M.type="integer":M.type="number",typeof Q=="number"&&(M.exclusiveMinimum=Q),typeof D=="number"&&(M.minimum=D,typeof Q=="number"&&(Q>=D?delete M.minimum:delete M.exclusiveMinimum)),typeof U=="number"&&(M.exclusiveMaximum=U),typeof B=="number"&&(M.maximum=B,typeof U=="number"&&(U<=B?delete M.maximum:delete M.exclusiveMaximum)),typeof Z=="number"&&(M.multipleOf=Z);break}case"boolean":{const M=O;M.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{O.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{O.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const M=O,{minimum:D,maximum:B}=r._zod.bag;typeof D=="number"&&(M.minItems=D),typeof B=="number"&&(M.maxItems=B),M.type="array",M.items=this.process(u.element,{...v,path:[...v.path,"items"]});break}case"object":{const M=O;M.type="object",M.properties={};const D=u.shape;for(const Z in D)M.properties[Z]=this.process(D[Z],{...v,path:[...v.path,"properties",Z]});const B=new Set(Object.keys(D)),G=new Set([...B].filter(Z=>{const U=u.shape[Z]._zod;return this.io==="input"?U.optin===void 0:U.optout===void 0}));G.size>0&&(M.required=Array.from(G)),u.catchall?._zod.def.type==="never"?M.additionalProperties=!1:u.catchall?u.catchall&&(M.additionalProperties=this.process(u.catchall,{...v,path:[...v.path,"additionalProperties"]})):this.io==="output"&&(M.additionalProperties=!1);break}case"union":{const M=O;M.anyOf=u.options.map((D,B)=>this.process(D,{...v,path:[...v.path,"anyOf",B]}));break}case"intersection":{const M=O,D=this.process(u.left,{...v,path:[...v.path,"allOf",0]}),B=this.process(u.right,{...v,path:[...v.path,"allOf",1]}),G=U=>"allOf"in U&&Object.keys(U).length===1,Z=[...G(D)?D.allOf:[D],...G(B)?B.allOf:[B]];M.allOf=Z;break}case"tuple":{const M=O;M.type="array";const D=u.items.map((Z,U)=>this.process(Z,{...v,path:[...v.path,"prefixItems",U]}));if(this.target==="draft-2020-12"?M.prefixItems=D:M.items=D,u.rest){const Z=this.process(u.rest,{...v,path:[...v.path,"items"]});this.target==="draft-2020-12"?M.items=Z:M.additionalItems=Z}u.rest&&(M.items=this.process(u.rest,{...v,path:[...v.path,"items"]}));const{minimum:B,maximum:G}=r._zod.bag;typeof B=="number"&&(M.minItems=B),typeof G=="number"&&(M.maxItems=G);break}case"record":{const M=O;M.type="object",M.propertyNames=this.process(u.keyType,{...v,path:[...v.path,"propertyNames"]}),M.additionalProperties=this.process(u.valueType,{...v,path:[...v.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 M=O,D=Xl(u.entries);D.every(B=>typeof B=="number")&&(M.type="number"),D.every(B=>typeof B=="string")&&(M.type="string"),M.enum=D;break}case"literal":{const M=O,D=[];for(const B of u.values)if(B===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof B=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");D.push(Number(B))}else D.push(B);if(D.length!==0)if(D.length===1){const B=D[0];M.type=B===null?"null":typeof B,M.const=B}else D.every(B=>typeof B=="number")&&(M.type="number"),D.every(B=>typeof B=="string")&&(M.type="string"),D.every(B=>typeof B=="boolean")&&(M.type="string"),D.every(B=>B===null)&&(M.type="null"),M.enum=D;break}case"file":{const M=O,D={type:"string",format:"binary",contentEncoding:"binary"},{minimum:B,maximum:G,mime:Z}=r._zod.bag;B!==void 0&&(D.minLength=B),G!==void 0&&(D.maxLength=G),Z?Z.length===1?(D.contentMediaType=Z[0],Object.assign(M,D)):M.anyOf=Z.map(U=>({...D,contentMediaType:U})):Object.assign(M,D);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const M=this.process(u.innerType,v);O.anyOf=[M,{type:"null"}];break}case"nonoptional":{this.process(u.innerType,v),g.ref=u.innerType;break}case"success":{const M=O;M.type="boolean";break}case"default":{this.process(u.innerType,v),g.ref=u.innerType,O.default=JSON.parse(JSON.stringify(u.defaultValue));break}case"prefault":{this.process(u.innerType,v),g.ref=u.innerType,this.io==="input"&&(O._prefault=JSON.parse(JSON.stringify(u.defaultValue)));break}case"catch":{this.process(u.innerType,v),g.ref=u.innerType;let M;try{M=u.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}O.default=M;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const M=O,D=r._zod.pattern;if(!D)throw new Error("Pattern not found in template literal");M.type="string",M.pattern=D.source;break}case"pipe":{const M=this.io==="input"?u.in._zod.def.type==="transform"?u.out:u.in:u.out;this.process(M,v),g.ref=M;break}case"readonly":{this.process(u.innerType,v),g.ref=u.innerType,O.readOnly=!0;break}case"promise":{this.process(u.innerType,v),g.ref=u.innerType;break}case"optional":{this.process(u.innerType,v),g.ref=u.innerType;break}case"lazy":{const M=r._zod.innerType;this.process(M,v),g.ref=M;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"&&Pt(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=A=>{const v=this.target==="draft-2020-12"?"$defs":"definitions";if(c.external){const D=c.external.registry.get(A[0])?.id,B=c.external.uri??(Z=>Z);if(D)return{ref:B(D)};const G=A[1].defId??A[1].schema.id??`schema${this.counter++}`;return A[1].defId=G,{defId:G,ref:`${B("__shared")}#/${v}/${G}`}}if(A[1]===u)return{ref:"#"};const O=`#/${v}/`,M=A[1].schema.id??`__schema${this.counter++}`;return{defId:M,ref:O+M}},m=A=>{if(A[1].schema.$ref)return;const v=A[1],{ref:P,defId:O}=f(A);v.def={...v.schema},O&&(v.defId=O);const M=v.schema;for(const D in M)delete M[D];M.$ref=P};if(c.cycles==="throw")for(const A of this.seen.entries()){const v=A[1];if(v.cycle)throw new Error(`Cycle detected: #/${v.cycle?.join("/")}/<root>
|
|
33
33
|
|
|
34
|
-
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]){g(E);continue}if(c.external){const O=c.external.registry.get(E[0])?.id;if(r!==E[0]&&O){g(E);continue}}if(this.metadataRegistry.get(E[0])?.id){g(E);continue}if(A.cycle){g(E);continue}if(A.count>1&&c.reused==="ref"){g(E);continue}}const m=(E,A)=>{const B=this.seen.get(E),O=B.def??B.schema,R={...O};if(B.ref===null)return;const D=B.ref;if(B.ref=null,D){m(D,A);const P=this.seen.get(D).schema;P.$ref&&A.target==="draft-7"?(O.allOf=O.allOf??[],O.allOf.push(P)):(Object.assign(O,P),Object.assign(O,R))}B.isParent||this.override({zodSchema:E,jsonSchema:O,path:B.path??[]})};for(const E of[...this.seen.entries()].reverse())m(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 Af(t,r){if(t instanceof sc){const c=new Rs(r),u={};for(const m of t._idmap.entries()){const[v,x]=m;c.process(x)}const f={},g={registry:t,uri:r?.uri,defs:u};for(const m of t._idmap.entries()){const[v,x]=m;f[v]=c.emit(x,{...r,external:g})}if(Object.keys(u).length>0){const m=c.target==="draft-2020-12"?"$defs":"definitions";f.__shared={[m]:u}}return{schemas:f}}const o=new Rs(r);return o.process(t),o.emit(t,r)}function Ot(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 Ot(u.element,o);case"object":{for(const f in u.shape)if(Ot(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(Ot(f,o))return!0;return!1}case"intersection":return Ot(u.left,o)||Ot(u.right,o);case"tuple":{for(const f of u.items)if(Ot(f,o))return!0;return!!(u.rest&&Ot(u.rest,o))}case"record":return Ot(u.keyType,o)||Ot(u.valueType,o);case"map":return Ot(u.keyType,o)||Ot(u.valueType,o);case"set":return Ot(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Ot(u.innerType,o);case"lazy":return Ot(u.getter(),o);case"default":return Ot(u.innerType,o);case"prefault":return Ot(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return Ot(u.in,o)||Ot(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const If=ne("ZodISODateTime",(t,r)=>{G1.init(t,r),mt.init(t,r)});function Sf(t){return ef(If,t)}const Tf=ne("ZodISODate",(t,r)=>{X1.init(t,r),mt.init(t,r)});function Nf(t){return tf(Tf,t)}const Of=ne("ZodISOTime",(t,r)=>{q1.init(t,r),mt.init(t,r)});function kf(t){return nf(Of,t)}const Rf=ne("ZodISODuration",(t,r)=>{Y1.init(t,r),mt.init(t,r)});function Mf(t){return rf(Rf,t)}const Df=(t,r)=>{Gl.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>$d(t,o)},flatten:{value:o=>Zd(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},Di=ne("ZodError",Df,{Parent:Error}),Pf=Wd(Di),Bf=Hd(Di),Lf=ql(Di),cc=Yl(Di),ut=ne("ZodType",(t,r)=>(ot.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)=>ur(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>Pf(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Lf(t,o,c),t.parseAsync=async(o,c)=>Bf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>cc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(Mh(o,c)),t.superRefine=o=>t.check(Dh(o)),t.overwrite=o=>t.check(ei(o)),t.optional=()=>Ps(t),t.nullable=()=>Bs(t),t.nullish=()=>Ps(Bs(t)),t.nonoptional=o=>Eh(t,o),t.array=()=>fe(t),t.or=o=>Je([t,o]),t.and=o=>ph(t,o),t.transform=o=>Ls(t,wh(o)),t.default=o=>vh(t,o),t.prefault=o=>bh(t,o),t.catch=o=>Ih(t,o),t.pipe=o=>Ls(t,o),t.readonly=()=>Nh(t),t.describe=o=>{const c=t.clone();return Vr.add(c,{description:o}),c},Object.defineProperty(t,"description",{get(){return Vr.get(t)?.description},configurable:!0}),t.meta=(...o)=>{if(o.length===0)return Vr.get(t);const c=t.clone();return Vr.add(c,o[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),uc=ne("_ZodString",(t,r)=>{Fo.init(t,r),ut.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(hf(...c)),t.includes=(...c)=>t.check(mf(...c)),t.startsWith=(...c)=>t.check(xf(...c)),t.endsWith=(...c)=>t.check(wf(...c)),t.min=(...c)=>t.check(Ti(...c)),t.max=(...c)=>t.check(ac(...c)),t.length=(...c)=>t.check(lc(...c)),t.nonempty=(...c)=>t.check(Ti(1,...c)),t.lowercase=c=>t.check(pf(c)),t.uppercase=c=>t.check(gf(c)),t.trim=()=>t.check(_f()),t.normalize=(...c)=>t.check(yf(...c)),t.toLowerCase=()=>t.check(vf()),t.toUpperCase=()=>t.check(Cf())}),Ff=ne("ZodString",(t,r)=>{Fo.init(t,r),uc.init(t,r),t.email=o=>t.check(M0(Uf,o)),t.url=o=>t.check(F0(zf,o)),t.jwt=o=>t.check(Q0(th,o)),t.emoji=o=>t.check(U0(Vf,o)),t.guid=o=>t.check(Ts(Ms,o)),t.uuid=o=>t.check(D0(xi,o)),t.uuidv4=o=>t.check(P0(xi,o)),t.uuidv6=o=>t.check(B0(xi,o)),t.uuidv7=o=>t.check(L0(xi,o)),t.nanoid=o=>t.check(z0(Zf,o)),t.guid=o=>t.check(Ts(Ms,o)),t.cuid=o=>t.check(V0($f,o)),t.cuid2=o=>t.check(Z0(Wf,o)),t.ulid=o=>t.check($0(Hf,o)),t.base64=o=>t.check(Y0(Jf,o)),t.base64url=o=>t.check(K0(Qf,o)),t.xid=o=>t.check(W0(jf,o)),t.ksuid=o=>t.check(H0(Gf,o)),t.ipv4=o=>t.check(j0(Xf,o)),t.ipv6=o=>t.check(G0(qf,o)),t.cidrv4=o=>t.check(X0(Yf,o)),t.cidrv6=o=>t.check(q0(Kf,o)),t.e164=o=>t.check(J0(eh,o)),t.datetime=o=>t.check(Sf(o)),t.date=o=>t.check(Nf(o)),t.time=o=>t.check(kf(o)),t.duration=o=>t.check(Mf(o))});function _(t){return R0(Ff,t)}const mt=ne("ZodStringFormat",(t,r)=>{ht.init(t,r),uc.init(t,r)}),Uf=ne("ZodEmail",(t,r)=>{F1.init(t,r),mt.init(t,r)}),Ms=ne("ZodGUID",(t,r)=>{B1.init(t,r),mt.init(t,r)}),xi=ne("ZodUUID",(t,r)=>{L1.init(t,r),mt.init(t,r)}),zf=ne("ZodURL",(t,r)=>{U1.init(t,r),mt.init(t,r)}),Vf=ne("ZodEmoji",(t,r)=>{z1.init(t,r),mt.init(t,r)}),Zf=ne("ZodNanoID",(t,r)=>{V1.init(t,r),mt.init(t,r)}),$f=ne("ZodCUID",(t,r)=>{Z1.init(t,r),mt.init(t,r)}),Wf=ne("ZodCUID2",(t,r)=>{$1.init(t,r),mt.init(t,r)}),Hf=ne("ZodULID",(t,r)=>{W1.init(t,r),mt.init(t,r)}),jf=ne("ZodXID",(t,r)=>{H1.init(t,r),mt.init(t,r)}),Gf=ne("ZodKSUID",(t,r)=>{j1.init(t,r),mt.init(t,r)}),Xf=ne("ZodIPv4",(t,r)=>{K1.init(t,r),mt.init(t,r)}),qf=ne("ZodIPv6",(t,r)=>{J1.init(t,r),mt.init(t,r)}),Yf=ne("ZodCIDRv4",(t,r)=>{Q1.init(t,r),mt.init(t,r)}),Kf=ne("ZodCIDRv6",(t,r)=>{e0.init(t,r),mt.init(t,r)}),Jf=ne("ZodBase64",(t,r)=>{t0.init(t,r),mt.init(t,r)}),Qf=ne("ZodBase64URL",(t,r)=>{r0.init(t,r),mt.init(t,r)}),eh=ne("ZodE164",(t,r)=>{i0.init(t,r),mt.init(t,r)}),th=ne("ZodJWT",(t,r)=>{s0.init(t,r),mt.init(t,r)}),Uo=ne("ZodNumber",(t,r)=>{ic.init(t,r),ut.init(t,r),t.gt=(c,u)=>t.check(Os(c,u)),t.gte=(c,u)=>t.check(oo(c,u)),t.min=(c,u)=>t.check(oo(c,u)),t.lt=(c,u)=>t.check(Ns(c,u)),t.lte=(c,u)=>t.check(io(c,u)),t.max=(c,u)=>t.check(io(c,u)),t.int=c=>t.check(Ds(c)),t.safe=c=>t.check(Ds(c)),t.positive=c=>t.check(Os(0,c)),t.nonnegative=c=>t.check(oo(0,c)),t.negative=c=>t.check(Ns(0,c)),t.nonpositive=c=>t.check(io(0,c)),t.multipleOf=(c,u)=>t.check(ks(c,u)),t.step=(c,u)=>t.check(ks(c,u)),t.finite=()=>t;const o=t._zod.bag;t.minValue=Math.max(o.minimum??Number.NEGATIVE_INFINITY,o.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(o.maximum??Number.POSITIVE_INFINITY,o.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(o.format??"").includes("int")||Number.isSafeInteger(o.multipleOf??.5),t.isFinite=!0,t.format=o.format??null});function q(t){return of(Uo,t)}const nh=ne("ZodNumberFormat",(t,r)=>{a0.init(t,r),Uo.init(t,r)});function Ds(t){return af(nh,t)}const rh=ne("ZodBoolean",(t,r)=>{l0.init(t,r),ut.init(t,r)});function kt(t){return lf(rh,t)}const ih=ne("ZodNull",(t,r)=>{c0.init(t,r),ut.init(t,r)});function oh(t){return cf(ih,t)}const sh=ne("ZodAny",(t,r)=>{u0.init(t,r),ut.init(t,r)});function dr(){return uf(sh)}const ah=ne("ZodUnknown",(t,r)=>{d0.init(t,r),ut.init(t,r)});function qr(){return df(ah)}const lh=ne("ZodNever",(t,r)=>{f0.init(t,r),ut.init(t,r)});function ch(t){return ff(lh,t)}const uh=ne("ZodArray",(t,r)=>{h0.init(t,r),ut.init(t,r),t.element=r.element,t.min=(o,c)=>t.check(Ti(o,c)),t.nonempty=o=>t.check(Ti(1,o)),t.max=(o,c)=>t.check(ac(o,c)),t.length=(o,c)=>t.check(lc(o,c)),t.unwrap=()=>t.element});function fe(t,r){return bf(uh,t,r)}const dh=ne("ZodObject",(t,r)=>{p0.init(t,r),ut.init(t,r),Qe(t,"shape",()=>r.shape),t.keyof=()=>Re(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:qr()}),t.loose=()=>t.clone({...t._zod.def,catchall:qr()}),t.strict=()=>t.clone({...t._zod.def,catchall:ch()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Fd(t,o),t.merge=o=>Ud(t,o),t.pick=o=>Bd(t,o),t.omit=o=>Ld(t,o),t.partial=(...o)=>zd(fc,t,o[0]),t.required=(...o)=>Vd(hc,t,o[0])});function T(t,r){const o={type:"object",get shape(){return Bo(this,"shape",{...t}),this.shape},...ye(r)};return new dh(o)}const dc=ne("ZodUnion",(t,r)=>{oc.init(t,r),ut.init(t,r),t.options=r.options});function Je(t,r){return new dc({type:"union",options:t,...ye(r)})}const fh=ne("ZodDiscriminatedUnion",(t,r)=>{dc.init(t,r),g0.init(t,r)});function at(t,r,o){return new fh({type:"union",options:r,discriminator:t,...ye(o)})}const hh=ne("ZodIntersection",(t,r)=>{m0.init(t,r),ut.init(t,r)});function ph(t,r){return new hh({type:"intersection",left:t,right:r})}const gh=ne("ZodRecord",(t,r)=>{x0.init(t,r),ut.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function Rt(t,r,o){return new gh({type:"record",keyType:t,valueType:r,...ye(o)})}const yo=ne("ZodEnum",(t,r)=>{w0.init(t,r),ut.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 g of c)if(o.has(g))f[g]=r.entries[g];else throw new Error(`Key ${g} not found in enum`);return new yo({...r,checks:[],...ye(u),entries:f})},t.exclude=(c,u)=>{const f={...r.entries};for(const g of c)if(o.has(g))delete f[g];else throw new Error(`Key ${g} not found in enum`);return new yo({...r,checks:[],...ye(u),entries:f})}});function Re(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new yo({type:"enum",entries:o,...ye(r)})}const mh=ne("ZodLiteral",(t,r)=>{y0.init(t,r),ut.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 K(t,r){return new mh({type:"literal",values:Array.isArray(t)?t:[t],...ye(r)})}const xh=ne("ZodTransform",(t,r)=>{_0.init(t,r),ut.init(t,r),t._zod.parse=(o,c)=>{o.addIssue=f=>{if(typeof f=="string")o.issues.push(Xr(f,o.value,r));else{const g=f;g.fatal&&(g.continue=!1),g.code??(g.code="custom"),g.input??(g.input=o.value),g.inst??(g.inst=t),g.continue??(g.continue=!0),o.issues.push(Xr(g))}};const u=r.transform(o.value,o);return u instanceof Promise?u.then(f=>(o.value=f,o)):(o.value=u,o)}});function wh(t){return new xh({type:"transform",transform:t})}const fc=ne("ZodOptional",(t,r)=>{v0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Ps(t){return new fc({type:"optional",innerType:t})}const yh=ne("ZodNullable",(t,r)=>{C0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Bs(t){return new yh({type:"nullable",innerType:t})}const _h=ne("ZodDefault",(t,r)=>{b0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function vh(t,r){return new _h({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ch=ne("ZodPrefault",(t,r)=>{E0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType});function bh(t,r){return new Ch({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const hc=ne("ZodNonOptional",(t,r)=>{A0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Eh(t,r){return new hc({type:"nonoptional",innerType:t,...ye(r)})}const Ah=ne("ZodCatch",(t,r)=>{I0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Ih(t,r){return new Ah({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Sh=ne("ZodPipe",(t,r)=>{S0.init(t,r),ut.init(t,r),t.in=r.in,t.out=r.out});function Ls(t,r){return new Sh({type:"pipe",in:t,out:r})}const Th=ne("ZodReadonly",(t,r)=>{T0.init(t,r),ut.init(t,r)});function Nh(t){return new Th({type:"readonly",innerType:t})}const Oh=ne("ZodLazy",(t,r)=>{N0.init(t,r),ut.init(t,r),t.unwrap=()=>t._zod.def.getter()});function pc(t){return new Oh({type:"lazy",getter:t})}const kh=ne("ZodCustom",(t,r)=>{O0.init(t,r),ut.init(t,r)});function Rh(t){const r=new tn({check:"custom"});return r._zod.check=t,r}function Mh(t,r={}){return Ef(kh,t,r)}function Dh(t){const r=Rh(o=>(o.addIssue=c=>{if(typeof c=="string")o.issues.push(Xr(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(Xr(u))}},t(o.value,o)));return r}function Ph(t){return sf(Uo,t)}var Oe;(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"})(Oe||(Oe={}));function Fs(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Pi(t){return Object.fromEntries([...t.headers])}var Bh=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,g=new Array(r);for(let m=0;m<r;m++)g[m]=o[Math.random()*f|0];return g.join("")};if(t==null)return u;if(o.includes(c))throw new Cl({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},wi=Bh();function _o(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Lh=["fetch failed","failed to fetch"];function Fh({error:t,url:r,requestBodyValues:o}){if(_o(t))return t;if(t instanceof TypeError&&Lh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Bn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function Uh(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 zh(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 gc(t,...r){const o=new Headers(zh(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var Vh="3.0.18";function Zh({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new pi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new pi({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 pi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new pi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}var $h=/"__proto__"\s*:/,Wh=/"constructor"\s*:/;function Us(t){const r=JSON.parse(t);return r===null||typeof r!="object"||$h.test(t)===!1&&Wh.test(t)===!1?r:Hh(r)}function Hh(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 zo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Us(t)}try{return Us(t)}finally{Error.stackTraceLimit=r}}var vo=Symbol.for("vercel.ai.validator");function jh(t){return{[vo]:!0,validate:t}}function Gh(t){return typeof t=="object"&&t!==null&&vo in t&&t[vo]===!0&&"validate"in t}function Xh(t){return Gh(t)?t:typeof t=="function"?t():qh(t)}function qh(t){return jh(async r=>{const o=await t["~standard"].validate(r);return o.issues==null?{success:!0,value:o.value}:{success:!1,error:new jr({value:r,cause:o.issues})}})}async function Yh({value:t,schema:r}){const o=await Yr({value:t,schema:r});if(!o.success)throw jr.wrap({value:t,cause:o.error});return o.value}async function Yr({value:t,schema:r}){const o=Xh(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: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 Kh({text:t,schema:r}){try{const o=zo(t);return r==null?o:Yh({value:o,schema:r})}catch(o){throw Ai.isInstance(o)||jr.isInstance(o)?o:new Ai({text:t,cause:o})}}async function mc({text:t,schema:r}){try{const o=zo(t);return r==null?{success:!0,value:o,rawValue:o}:await Yr({value:o,schema:r})}catch(o){return{success:!1,error:Ai.isInstance(o)?o:new Ai({text:t,cause:o}),rawValue:void 0}}}function zs(t){try{return zo(t),!0}catch{return!1}}function Jh({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Zl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await mc({text:o,schema:r}))}}))}async function Vs({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Yr({value:r[t],schema:o});if(!c.success)throw new Cl({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Qh=()=>globalThis.fetch,Zs=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g})=>ep({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g}),ep=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:g=Qh()})=>{try{const m=await g(t,{method:"POST",headers:gc(r,`ai-sdk/provider-utils/${Vh}`,Uh()),body:o.content,signal:f}),v=Pi(m);if(!m.ok){let x;try{x=await u({response:m,url:t,requestBodyValues:o.values})}catch(E){throw _o(E)||Bn.isInstance(E)?E:new Bn({message:"Failed to process error response",cause:E,statusCode:m.status,url:t,responseHeaders:v,requestBodyValues:o.values})}throw x.value}try{return await c({response:m,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(_o(x)||Bn.isInstance(x))?x:new Bn({message:"Failed to process successful response",cause:x,statusCode:m.status,url:t,responseHeaders:v,requestBodyValues:o.values})}}catch(m){throw Fh({error:m,url:t,requestBodyValues:o.values})}},tp=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const g=await c.text(),m=Pi(c);if(g.trim()==="")return{responseHeaders:m,value:new Bn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,isRetryable:o?.(c)})};try{const v=await Kh({text:g,schema:t});return{responseHeaders:m,value:new Bn({message:r(v),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,data:v,isRetryable:o?.(c,v)})}}catch{return{responseHeaders:m,value:new Bn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,isRetryable:o?.(c)})}}},np=t=>async({response:r})=>{const o=Pi(r);if(r.body==null)throw new yd({});return{responseHeaders:o,value:Jh({stream:r.body,schema:t})}},rp=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await mc({text:u,schema:t}),g=Pi(r);if(!f.success)throw new Bn({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:g,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:g,value:f.value,rawValue:f.rawValue}};new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");var{btoa:ip}=globalThis;function op(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return ip(r)}function sp(t){return t instanceof Uint8Array?op(t):t}function ap(t){return t?.replace(/\/$/,"")}function Br(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function lp(t){const r=[];for(const{role:o,content:c,...u}of t){const f=Br({...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,...Br(c[0])});break}r.push({role:"user",content:c.map(g=>{const m=Br(g);switch(g.type){case"text":return{type:"text",text:g.text,...m};case"file":if(g.mediaType.startsWith("image/")){const v=g.mediaType==="image/*"?"image/jpeg":g.mediaType;return{type:"image_url",image_url:{url:g.data instanceof URL?g.data.toString():`data:${v};base64,${sp(g.data)}`},...m}}else throw new Vl({functionality:`file part media type ${g.mediaType}`})}}),...f});break}case"assistant":{let g="";const m=[];for(const v of c){const x=Br(v);switch(v.type){case"text":{g+=v.text;break}case"tool-call":{m.push({id:v.toolCallId,type:"function",function:{name:v.toolName,arguments:JSON.stringify(v.input)},...x});break}}}r.push({role:"assistant",content:g,tool_calls:m.length>0?m:void 0,...f});break}case"tool":{for(const g of c){const m=g.output;let v;switch(m.type){case"text":case"error-text":v=m.value;break;case"content":case"json":case"error-json":v=JSON.stringify(m.value);break}const x=Br(g);r.push({role:"tool",tool_call_id:g.toolCallId,content:v,...x})}break}default:{const g=o;throw new Error(`Unsupported role: ${g}`)}}}return r}function $s({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 Ws(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 so=T({user:_().optional(),reasoningEffort:_().optional(),textVerbosity:_().optional()}),cp=T({error:T({message:_(),type:_().nullish(),param:dr().nullish(),code:Je([_(),q()]).nullish()})}),up={errorSchema:cp,errorToMessage:t=>t.error.message};function dp({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 Vl({functionality:`tool choice type: ${f}`})}}}var fp=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:up;this.chunkSchema=pp(u.errorSchema),this.failedResponseHandler=tp(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:g,providerOptions:m,stopSequences:v,responseFormat:x,seed:E,toolChoice:A,tools:B}){var O,R,D,P;const Y=[],$=Object.assign((O=await Vs({provider:"openai-compatible",providerOptions:m,schema:so}))!=null?O:{},(R=await Vs({provider:this.providerOptionsName,providerOptions:m,schema:so}))!=null?R:{});u!=null&&Y.push({type:"unsupported-setting",setting:"topK"}),x?.type==="json"&&x.schema!=null&&!this.supportsStructuredOutputs&&Y.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:U,toolChoice:W,toolWarnings:X}=dp({tools:B,toolChoice:A});return{args:{model:this.modelId,user:$.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:g,response_format:x?.type==="json"?this.supportsStructuredOutputs===!0&&x.schema!=null?{type:"json_schema",json_schema:{schema:x.schema,name:(D=x.name)!=null?D:"response",description:x.description}}:{type:"json_object"}:void 0,stop:v,seed:E,...Object.fromEntries(Object.entries((P=m?.[this.providerOptionsName])!=null?P:{}).filter(([H])=>!Object.keys(so.shape).includes(H))),reasoning_effort:$.reasoningEffort,verbosity:$.textVerbosity,messages:lp(t),tools:U,tool_choice:W},warnings:[...Y,...X]}}async doGenerate(t){var r,o,c,u,f,g,m,v,x,E,A,B,O,R,D,P,Y;const{args:$,warnings:U}=await this.getArgs({...t}),W=JSON.stringify($),{responseHeaders:X,value:H,rawValue:z}=await Zs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Fs(this.config.headers(),t.headers),body:$,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rp(hp),abortSignal:t.abortSignal,fetch:this.config.fetch}),V=H.choices[0],M=[],Ce=V.message.content;Ce!=null&&Ce.length>0&&M.push({type:"text",text:Ce});const me=(r=V.message.reasoning_content)!=null?r:V.message.reasoning;if(me!=null&&me.length>0&&M.push({type:"reasoning",text:me}),V.message.tool_calls!=null)for(const re of V.message.tool_calls)M.push({type:"tool-call",toolCallId:(o=re.id)!=null?o:wi(),toolName:re.function.name,input:re.function.arguments});const le={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:z}))},ie=(f=H.usage)==null?void 0:f.completion_tokens_details;return ie?.accepted_prediction_tokens!=null&&(le[this.providerOptionsName].acceptedPredictionTokens=ie?.accepted_prediction_tokens),ie?.rejected_prediction_tokens!=null&&(le[this.providerOptionsName].rejectedPredictionTokens=ie?.rejected_prediction_tokens),{content:M,finishReason:Ws(V.finish_reason),usage:{inputTokens:(m=(g=H.usage)==null?void 0:g.prompt_tokens)!=null?m:void 0,outputTokens:(x=(v=H.usage)==null?void 0:v.completion_tokens)!=null?x:void 0,totalTokens:(A=(E=H.usage)==null?void 0:E.total_tokens)!=null?A:void 0,reasoningTokens:(R=(O=(B=H.usage)==null?void 0:B.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?R:void 0,cachedInputTokens:(Y=(P=(D=H.usage)==null?void 0:D.prompt_tokens_details)==null?void 0:P.cached_tokens)!=null?Y:void 0},providerMetadata:le,request:{body:W},response:{...$s(H),headers:X,body:z},warnings:U}}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:g,value:m}=await Zs({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Fs(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:np(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 B=this.providerOptionsName;let O=!1,R=!1;return{stream:m.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:c})},transform(D,P){var Y,$,U,W,X,H,z,V,M,Ce,me,le,ie;if(t.includeRawChunks&&P.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){x="error",P.enqueue({type:"error",error:D.error});return}const re=D.value;if(f?.processChunk(D.rawValue),"error"in re){x="error",P.enqueue({type:"error",error:re.error.message});return}if(A&&(A=!1,P.enqueue({type:"response-metadata",...$s(re)})),re.usage!=null){const{prompt_tokens:he,completion_tokens:Ie,total_tokens:Te,prompt_tokens_details:ge,completion_tokens_details:De}=re.usage;E.promptTokens=he??void 0,E.completionTokens=Ie??void 0,E.totalTokens=Te??void 0,De?.reasoning_tokens!=null&&(E.completionTokensDetails.reasoningTokens=De?.reasoning_tokens),De?.accepted_prediction_tokens!=null&&(E.completionTokensDetails.acceptedPredictionTokens=De?.accepted_prediction_tokens),De?.rejected_prediction_tokens!=null&&(E.completionTokensDetails.rejectedPredictionTokens=De?.rejected_prediction_tokens),ge?.cached_tokens!=null&&(E.promptTokensDetails.cachedTokens=ge?.cached_tokens)}const Z=re.choices[0];if(Z?.finish_reason!=null&&(x=Ws(Z.finish_reason)),Z?.delta==null)return;const de=Z.delta,ee=(Y=de.reasoning_content)!=null?Y:de.reasoning;if(ee&&(O||(P.enqueue({type:"reasoning-start",id:"reasoning-0"}),O=!0),P.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ee})),de.content&&(R||(P.enqueue({type:"text-start",id:"txt-0"}),R=!0),P.enqueue({type:"text-delta",id:"txt-0",delta:de.content})),de.tool_calls!=null)for(const he of de.tool_calls){const Ie=he.index;if(v[Ie]==null){if(he.id==null)throw new gs({data:he,message:"Expected 'id' to be a string."});if((($=he.function)==null?void 0:$.name)==null)throw new gs({data:he,message:"Expected 'function.name' to be a string."});P.enqueue({type:"tool-input-start",id:he.id,toolName:he.function.name}),v[Ie]={id:he.id,type:"function",function:{name:he.function.name,arguments:(U=he.function.arguments)!=null?U:""},hasFinished:!1};const ge=v[Ie];((W=ge.function)==null?void 0:W.name)!=null&&((X=ge.function)==null?void 0:X.arguments)!=null&&(ge.function.arguments.length>0&&P.enqueue({type:"tool-input-delta",id:ge.id,delta:ge.function.arguments}),zs(ge.function.arguments)&&(P.enqueue({type:"tool-input-end",id:ge.id}),P.enqueue({type:"tool-call",toolCallId:(H=ge.id)!=null?H:wi(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0));continue}const Te=v[Ie];Te.hasFinished||(((z=he.function)==null?void 0:z.arguments)!=null&&(Te.function.arguments+=(M=(V=he.function)==null?void 0:V.arguments)!=null?M:""),P.enqueue({type:"tool-input-delta",id:Te.id,delta:(Ce=he.function.arguments)!=null?Ce:""}),((me=Te.function)==null?void 0:me.name)!=null&&((le=Te.function)==null?void 0:le.arguments)!=null&&zs(Te.function.arguments)&&(P.enqueue({type:"tool-input-end",id:Te.id}),P.enqueue({type:"tool-call",toolCallId:(ie=Te.id)!=null?ie:wi(),toolName:Te.function.name,input:Te.function.arguments}),Te.hasFinished=!0))}},flush(D){var P,Y,$,U,W,X;O&&D.enqueue({type:"reasoning-end",id:"reasoning-0"}),R&&D.enqueue({type:"text-end",id:"txt-0"});for(const z of v.filter(V=>!V.hasFinished))D.enqueue({type:"tool-input-end",id:z.id}),D.enqueue({type:"tool-call",toolCallId:(P=z.id)!=null?P:wi(),toolName:z.function.name,input:z.function.arguments});const H={[B]:{},...f?.buildMetadata()};E.completionTokensDetails.acceptedPredictionTokens!=null&&(H[B].acceptedPredictionTokens=E.completionTokensDetails.acceptedPredictionTokens),E.completionTokensDetails.rejectedPredictionTokens!=null&&(H[B].rejectedPredictionTokens=E.completionTokensDetails.rejectedPredictionTokens),D.enqueue({type:"finish",finishReason:x,usage:{inputTokens:(Y=E.promptTokens)!=null?Y:void 0,outputTokens:($=E.completionTokens)!=null?$:void 0,totalTokens:(U=E.totalTokens)!=null?U:void 0,reasoningTokens:(W=E.completionTokensDetails.reasoningTokens)!=null?W:void 0,cachedInputTokens:(X=E.promptTokensDetails.cachedTokens)!=null?X:void 0},providerMetadata:H})}})),request:{body:u},response:{headers:g}}}},xc=T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish(),hp=T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({message:T({role:K("assistant").nullish(),content:_().nullish(),reasoning_content:_().nullish(),reasoning:_().nullish(),tool_calls:fe(T({id:_().nullish(),function:T({name:_(),arguments:_()})})).nullish()}),finish_reason:_().nullish()})),usage:xc}),pp=t=>Je([T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({delta:T({role:Re(["assistant"]).nullish(),content:_().nullish(),reasoning_content:_().nullish(),reasoning:_().nullish(),tool_calls:fe(T({index:q(),id:_().nullish(),function:T({name:_().nullish(),arguments:_().nullish()})})).nullish()}).nullish(),finish_reason:_().nullish()})),usage:xc}),t]);T({echo:kt().optional(),logitBias:Rt(_(),q()).optional(),suffix:_().optional(),user:_().optional()});var gp=T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()});T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({text:_(),finish_reason:_()})),usage:gp.nullish()});T({dimensions:q().optional(),user:_().optional()});T({data:fe(T({embedding:fe(q())})),usage:T({prompt_tokens:q()}).nullish(),providerMetadata:Rt(_(),Rt(_(),dr())).optional()});T({data:fe(T({b64_json:_()}))});var Hs=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}}},mp={extractMetadata:async({parsedBody:t})=>{const r=await Yr({value:t,schema:xp});return!r.success||r.value.usage==null?void 0:Hs(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await Yr({value:r,schema:wp});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:()=>Hs(t)}}},wc=T({prompt_cache_hit_tokens:q().nullish(),prompt_cache_miss_tokens:q().nullish()}),xp=T({usage:wc.nullish()}),wp=T({choices:fe(T({finish_reason:_().nullish()})).nullish(),usage:wc.nullish()}),yp="1.0.30";function yc(t={}){var r;const o=ap((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>gc({Authorization:`Bearer ${Zh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${yp}`);class u extends fp{addJsonInstruction(v){var x;if(((x=v.responseFormat)==null?void 0:x.type)!=="json")return v;const B=[...Array.isArray(v.prompt)?v.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...v,prompt:B}}async doGenerate(v){return super.doGenerate(this.addJsonInstruction(v))}async doStream(v){return super.doStream(this.addJsonInstruction(v))}}const f=m=>new u(m,{provider:"deepseek.chat",url:({path:v})=>`${o}${v}`,headers:c,fetch:t.fetch,metadataExtractor:mp}),g=m=>f(m);return g.languageModel=f,g.chat=f,g.textEmbeddingModel=m=>{throw new ms({modelId:m,modelType:"textEmbeddingModel"})},g.imageModel=m=>{throw new ms({modelId:m,modelType:"imageModel"})},g}yc();var _c="vercel.ai.error",_p=Symbol.for(_c),js,Gs,Ct=class vc extends(Gs=Error,js=_p,Gs){constructor({name:r,message:o,cause:c}){super(o),this[js]=!0,this.name=r,this.cause=c}static isInstance(r){return vc.hasMarker(r,_c)}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}},Cc="AI_APICallError",bc=`vercel.ai.error.${Cc}`,vp=Symbol.for(bc),Xs,qs,ln=class extends(qs=Ct,Xs=vp,qs){constructor({message:t,url:r,requestBodyValues:o,statusCode:c,responseHeaders:u,responseBody:f,cause:g,isRetryable:m=c!=null&&(c===408||c===409||c===429||c>=500),data:v}){super({name:Cc,message:t,cause:g}),this[Xs]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=m,this.data=v}static isInstance(t){return Ct.hasMarker(t,bc)}},Ec="AI_EmptyResponseBodyError",Ac=`vercel.ai.error.${Ec}`,Cp=Symbol.for(Ac),Ys,Ks,bp=class extends(Ks=Ct,Ys=Cp,Ks){constructor({message:t="Empty response body"}={}){super({name:Ec,message:t}),this[Ys]=!0}static isInstance(t){return Ct.hasMarker(t,Ac)}};function Ic(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var Sc="AI_InvalidArgumentError",Tc=`vercel.ai.error.${Sc}`,Ep=Symbol.for(Tc),Js,Qs,Nc=class extends(Qs=Ct,Js=Ep,Qs){constructor({message:t,cause:r,argument:o}){super({name:Sc,message:t,cause:r}),this[Js]=!0,this.argument=o}static isInstance(t){return Ct.hasMarker(t,Tc)}},Oc="AI_InvalidPromptError",kc=`vercel.ai.error.${Oc}`,Ap=Symbol.for(kc),ea,ta,Ip=class extends(ta=Ct,ea=Ap,ta){constructor({prompt:t,message:r,cause:o}){super({name:Oc,message:`Invalid prompt: ${r}`,cause:o}),this[ea]=!0,this.prompt=t}static isInstance(t){return Ct.hasMarker(t,kc)}},Rc="AI_InvalidResponseDataError",Mc=`vercel.ai.error.${Rc}`,Sp=Symbol.for(Mc),na,ra,ao=class extends(ra=Ct,na=Sp,ra){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Rc,message:r}),this[na]=!0,this.data=t}static isInstance(t){return Ct.hasMarker(t,Mc)}},Dc="AI_JSONParseError",Pc=`vercel.ai.error.${Dc}`,Tp=Symbol.for(Pc),ia,oa,Ni=class extends(oa=Ct,ia=Tp,oa){constructor({text:t,cause:r}){super({name:Dc,message:`JSON parsing failed: Text: ${t}.
|
|
35
|
-
Error message: ${
|
|
36
|
-
Error message: ${Ic(o)}`,cause:o}),this[ua]=!0,this.value=r,this.context=c}static isInstance(r){return Ct.hasMarker(r,Vc)}static wrap({value:r,cause:o,context:c}){var u,f,g;return Co.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&&((g=o.context)==null?void 0:g.entityId)===c?.entityId?o:new Co({value:r,cause:o,context:c})}},Zc="AI_UnsupportedFunctionalityError",$c=`vercel.ai.error.${Zc}`,Mp=Symbol.for($c),fa,ha,Ln=class extends(ha=Ct,fa=Mp,ha){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:Zc,message:r}),this[fa]=!0,this.functionality=t}static isInstance(t){return Ct.hasMarker(t,$c)}};function bn(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Dp({tools:t=[],providerToolNames:r,resolveProviderToolName:o}){var c;const u={},f={};for(const g of t)if(g.type==="provider"){const m=(c=o?.(g))!=null?c:g.id in r?r[g.id]:void 0;if(m==null)continue;u[g.name]=m,f[m]=g.name}return{toProviderToolName:g=>{var m;return(m=u[g])!=null?m:g},toCustomToolName:g=>{var m;return(m=f[g])!=null?m:g}}}var Pp=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 ti(t){return Object.fromEntries([...t.headers])}var{btoa:Bp,atob:Lp}=globalThis;function Vo(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=Lp(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function Fp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return Bp(r)}function Er(t){return t instanceof Uint8Array?Fp(t):t}function Up(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 g=o?`${u}[]`:u;for(const m of f)c.append(g,m);continue}c.append(u,f)}return c}var Wc="AI_DownloadError",Hc=`vercel.ai.error.${Wc}`,zp=Symbol.for(Hc),pa,ga,vn=class extends(ga=Ct,pa=zp,ga){constructor({url:t,statusCode:r,statusText:o,cause:c,message:u=c==null?`Failed to download ${t}: ${r} ${o}`:`Failed to download ${t}: ${c}`}){super({name:Wc,message:u,cause:c}),this[pa]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return Ct.hasMarker(t,Hc)}},jc=2*1024*1024*1024;async function Vp({response:t,url:r,maxBytes:o=jc}){const c=t.headers.get("content-length");if(c!=null){const E=parseInt(c,10);if(!isNaN(E)&&E>o)throw new vn({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(),g=[];let m=0;try{for(;;){const{done:E,value:A}=await f.read();if(E)break;if(m+=A.length,m>o)throw new vn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});g.push(A)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const v=new Uint8Array(m);let x=0;for(const E of g)v.set(E,x),x+=E.length;return v}function Zp(t){let r;try{r=new URL(t)}catch{throw new vn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new vn({url:t,message:`URL scheme must be http or https, got ${r.protocol}`});const o=r.hostname;if(!o)throw new vn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new vn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if($p(c))throw new vn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(Gc(o)){if(bo(o))throw new vn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function Gc(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 bo(t){const r=t.split(".").map(Number),[o,c]=r;return o===0||o===10||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===168}function $p(t){const r=t.toLowerCase();if(r==="::1"||r==="::")return!0;if(r.startsWith("::ffff:")){const o=r.slice(7);if(Gc(o))return bo(o);const c=o.split(":");if(c.length===2){const u=parseInt(c[0],16),f=parseInt(c[1],16);if(!isNaN(u)&&!isNaN(f)){const g=u>>8&255,m=u&255,v=f>>8&255,x=f&255;return bo(`${g}.${m}.${v}.${x}`)}}}return!!(r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"))}async function Xc(t,r){var o,c;Zp(t);try{const u=await fetch(t,{signal:r?.abortSignal});if(!u.ok)throw new vn({url:t,statusCode:u.status,statusText:u.statusText});const f=await Vp({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:jc}),g=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],g?{type:g}:void 0)}catch(u){throw vn.isInstance(u)?u:new vn({url:t,cause:u})}}var Wp=({prefix:t,size:r=16,alphabet:o="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:c="-"}={})=>{const u=()=>{const f=o.length,g=new Array(r);for(let m=0;m<r;m++)g[m]=o[Math.random()*f|0];return g.join("")};if(t==null)return u;if(o.includes(c))throw new Nc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Xt=Wp();function Eo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Hp=["fetch failed","failed to fetch"],jp=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function Gp(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&jp.includes(r))}function Xp({error:t,url:r,requestBodyValues:o}){if(Eo(t))return t;if(t instanceof TypeError&&Hp.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new ln({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return Gp(t)?new ln({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function qp(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 Yp(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 qc(t,...r){const o=new Headers(Yp(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var Kp="4.0.19";function ma(t){return t!=null}function Jp({apiKey:t,environmentVariableName:r,apiKeyParameterName:o="apiKey",description:c}){if(typeof t=="string")return t;if(t!=null)throw new yi({message:`${c} API key must be a string.`});if(typeof process>"u")throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter. Environment variables is not supported in this environment.`});if(t=process.env[r],t==null)throw new yi({message:`${c} API key is missing. Pass it using the '${o}' parameter or the ${r} environment variable.`});if(typeof t!="string")throw new yi({message:`${c} API key must be a string. The value of the ${r} environment variable is not a string.`});return t}function Qp({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 eg(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 tg=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,ng=/"(?: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 xa(t){const r=JSON.parse(t);return r===null||typeof r!="object"||tg.test(t)===!1&&ng.test(t)===!1?r:rg(r)}function rg(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 Zo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return xa(t)}try{return xa(t)}finally{Error.stackTraceLimit=r}}function $o(t){if(t.type==="object"||Array.isArray(t.type)&&t.type.includes("object")){t.additionalProperties=!1;const{properties:o}=t;if(o!=null)for(const c of Object.keys(o))o[c]=or(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(or):or(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(or)),t.allOf!=null&&(t.allOf=t.allOf.map(or)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(or));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=or(r[o]);return t}function or(t){return typeof t=="boolean"?t:$o(t)}var ig=Symbol("Let zodToJsonSchema decide on which parser to use"),wa={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},og=t=>typeof t=="string"?{...wa,name:t}:{...wa,...t};function dn(){return{}}function sg(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)!==Oe.ZodAny&&(f.items=tt(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 ag(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 lg(){return{type:"boolean"}}function Yc(t,r){return tt(t.type._def,r)}var cg=(t,r)=>tt(t.innerType._def,r);function Kc(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>Kc(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 ug(t)}}var ug=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 dg(t,r){return{...tt(t.innerType._def,r),default:t.defaultValue()}}function fg(t,r){return r.effectStrategy==="input"?tt(t.schema._def,r):dn()}function hg(t){return{type:"string",enum:Array.from(t.values)}}var pg=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function gg(t,r){const o=[tt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),tt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(pg(u))c.push(...u.allOf);else{let f=u;if("additionalProperties"in u&&u.additionalProperties===!1){const{additionalProperties:g,...m}=u;f=m}c.push(f)}}),c.length?{allOf:c}:void 0}function mg(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 lo=void 0,yn={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:()=>(lo===void 0&&(lo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lo),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 Jc(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":_n(o,"email",c.message,r);break;case"format:idn-email":_n(o,"idn-email",c.message,r);break;case"pattern:zod":Gt(o,yn.email,c.message,r);break}break;case"url":_n(o,"uri",c.message,r);break;case"uuid":_n(o,"uuid",c.message,r);break;case"regex":Gt(o,c.regex,c.message,r);break;case"cuid":Gt(o,yn.cuid,c.message,r);break;case"cuid2":Gt(o,yn.cuid2,c.message,r);break;case"startsWith":Gt(o,RegExp(`^${co(c.value,r)}`),c.message,r);break;case"endsWith":Gt(o,RegExp(`${co(c.value,r)}$`),c.message,r);break;case"datetime":_n(o,"date-time",c.message,r);break;case"date":_n(o,"date",c.message,r);break;case"time":_n(o,"time",c.message,r);break;case"duration":_n(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":{Gt(o,RegExp(co(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(o,"ipv4",c.message,r),c.version!=="v4"&&_n(o,"ipv6",c.message,r);break}case"base64url":Gt(o,yn.base64url,c.message,r);break;case"jwt":Gt(o,yn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Gt(o,yn.ipv4Cidr,c.message,r),c.version!=="v4"&&Gt(o,yn.ipv6Cidr,c.message,r);break}case"emoji":Gt(o,yn.emoji(),c.message,r);break;case"ulid":{Gt(o,yn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Gt(o,yn.base64,c.message,r);break}}break}case"nanoid":Gt(o,yn.nanoid,c.message,r)}return o}function co(t,r){return r.patternStrategy==="escape"?wg(t):t}var xg=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function wg(t){let r="";for(let o=0;o<t.length;o++)xg.has(t[o])||(r+="\\"),r+=t[o];return r}function _n(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 Gt(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:ya(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=ya(r,c)}function ya(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="",g=!1,m=!1,v=!1;for(let x=0;x<u.length;x++){if(g){f+=u[x],g=!1;continue}if(c.i){if(m){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
|
|
34
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const A of this.seen.entries()){const v=A[1];if(r===A[0]){m(A);continue}if(c.external){const O=c.external.registry.get(A[0])?.id;if(r!==A[0]&&O){m(A);continue}}if(this.metadataRegistry.get(A[0])?.id){m(A);continue}if(v.cycle){m(A);continue}if(v.count>1&&c.reused==="ref"){m(A);continue}}const g=(A,v)=>{const P=this.seen.get(A),O=P.def??P.schema,M={...O};if(P.ref===null)return;const D=P.ref;if(P.ref=null,D){g(D,v);const B=this.seen.get(D).schema;B.$ref&&v.target==="draft-7"?(O.allOf=O.allOf??[],O.allOf.push(B)):(Object.assign(O,B),Object.assign(O,M))}P.isParent||this.override({zodSchema:A,jsonSchema:O,path:P.path??[]})};for(const A of[...this.seen.entries()].reverse())g(A[0],{target:this.target});const C={};if(this.target==="draft-2020-12"?C.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?C.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),c.external?.uri){const A=c.external.registry.get(r)?.id;if(!A)throw new Error("Schema is missing an `id` property");C.$id=c.external.uri(A)}Object.assign(C,u.def);const x=c.external?.defs??{};for(const A of this.seen.entries()){const v=A[1];v.def&&v.defId&&(x[v.defId]=v.def)}c.external||Object.keys(x).length>0&&(this.target==="draft-2020-12"?C.$defs=x:C.definitions=x);try{return JSON.parse(JSON.stringify(C))}catch{throw new Error("Error converting schema to JSON.")}}}function If(t,r){if(t instanceof uc){const c=new Bs(r),u={};for(const g of t._idmap.entries()){const[C,x]=g;c.process(x)}const f={},m={registry:t,uri:r?.uri,defs:u};for(const g of t._idmap.entries()){const[C,x]=g;f[C]=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 Bs(r);return o.process(t),o.emit(t,r)}function Pt(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 Pt(u.element,o);case"object":{for(const f in u.shape)if(Pt(u.shape[f],o))return!0;return!1}case"union":{for(const f of u.options)if(Pt(f,o))return!0;return!1}case"intersection":return Pt(u.left,o)||Pt(u.right,o);case"tuple":{for(const f of u.items)if(Pt(f,o))return!0;return!!(u.rest&&Pt(u.rest,o))}case"record":return Pt(u.keyType,o)||Pt(u.valueType,o);case"map":return Pt(u.keyType,o)||Pt(u.valueType,o);case"set":return Pt(u.valueType,o);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Pt(u.innerType,o);case"lazy":return Pt(u.getter(),o);case"default":return Pt(u.innerType,o);case"prefault":return Pt(u.innerType,o);case"custom":return!1;case"transform":return!0;case"pipe":return Pt(u.in,o)||Pt(u.out,o);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${u.type}`)}const Sf=ee("ZodISODateTime",(t,r)=>{X1.init(t,r),_t.init(t,r)});function Tf(t){return tf(Sf,t)}const Nf=ee("ZodISODate",(t,r)=>{q1.init(t,r),_t.init(t,r)});function Of(t){return nf(Nf,t)}const kf=ee("ZodISOTime",(t,r)=>{Y1.init(t,r),_t.init(t,r)});function Rf(t){return rf(kf,t)}const Mf=ee("ZodISODuration",(t,r)=>{K1.init(t,r),_t.init(t,r)});function Df(t){return of(Mf,t)}const Pf=(t,r)=>{Kl.init(t,r),t.name="ZodError",Object.defineProperties(t,{format:{value:o=>Hd(t,o)},flatten:{value:o=>$d(t,o)},addIssue:{value:o=>t.issues.push(o)},addIssues:{value:o=>t.issues.push(...o)},isEmpty:{get(){return t.issues.length===0}}})},Pi=ee("ZodError",Pf,{Parent:Error}),Bf=Wd(Pi),Lf=jd(Pi),Ff=Ql(Pi),hc=ec(Pi),pt=ee("ZodType",(t,r)=>(at.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)=>pr(t,o,c),t.brand=()=>t,t.register=((o,c)=>(o.add(t,c),t)),t.parse=(o,c)=>Bf(t,o,c,{callee:t.parse}),t.safeParse=(o,c)=>Ff(t,o,c),t.parseAsync=async(o,c)=>Lf(t,o,c,{callee:t.parseAsync}),t.safeParseAsync=async(o,c)=>hc(t,o,c),t.spa=t.safeParseAsync,t.refine=(o,c)=>t.check(Mh(o,c)),t.superRefine=o=>t.check(Dh(o)),t.overwrite=o=>t.check(ri(o)),t.optional=()=>Us(t),t.nullable=()=>zs(t),t.nullish=()=>Us(zs(t)),t.nonoptional=o=>Eh(t,o),t.array=()=>ue(t),t.or=o=>Qe([t,o]),t.and=o=>ph(t,o),t.transform=o=>Vs(t,yh(o)),t.default=o=>vh(t,o),t.prefault=o=>bh(t,o),t.catch=o=>Ih(t,o),t.pipe=o=>Vs(t,o),t.readonly=()=>Nh(t),t.describe=o=>{const c=t.clone();return Hr.add(c,{description:o}),c},Object.defineProperty(t,"description",{get(){return Hr.get(t)?.description},configurable:!0}),t.meta=(...o)=>{if(o.length===0)return Hr.get(t);const c=t.clone();return Hr.add(c,o[0]),c},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),pc=ee("_ZodString",(t,r)=>{Vo.init(t,r),pt.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(pf(...c)),t.includes=(...c)=>t.check(xf(...c)),t.startsWith=(...c)=>t.check(yf(...c)),t.endsWith=(...c)=>t.check(wf(...c)),t.min=(...c)=>t.check(Ni(...c)),t.max=(...c)=>t.check(dc(...c)),t.length=(...c)=>t.check(fc(...c)),t.nonempty=(...c)=>t.check(Ni(1,...c)),t.lowercase=c=>t.check(mf(c)),t.uppercase=c=>t.check(gf(c)),t.trim=()=>t.check(vf()),t.normalize=(...c)=>t.check(_f(...c)),t.toLowerCase=()=>t.check(Cf()),t.toUpperCase=()=>t.check(bf())}),Uf=ee("ZodString",(t,r)=>{Vo.init(t,r),pc.init(t,r),t.email=o=>t.check(D0(zf,o)),t.url=o=>t.check(U0(Vf,o)),t.jwt=o=>t.check(ef(nh,o)),t.emoji=o=>t.check(z0(Zf,o)),t.guid=o=>t.check(Rs(Ls,o)),t.uuid=o=>t.check(P0(yi,o)),t.uuidv4=o=>t.check(B0(yi,o)),t.uuidv6=o=>t.check(L0(yi,o)),t.uuidv7=o=>t.check(F0(yi,o)),t.nanoid=o=>t.check(V0($f,o)),t.guid=o=>t.check(Rs(Ls,o)),t.cuid=o=>t.check(Z0(Hf,o)),t.cuid2=o=>t.check($0(Wf,o)),t.ulid=o=>t.check(H0(jf,o)),t.base64=o=>t.check(K0(Qf,o)),t.base64url=o=>t.check(J0(eh,o)),t.xid=o=>t.check(W0(Gf,o)),t.ksuid=o=>t.check(j0(Xf,o)),t.ipv4=o=>t.check(G0(qf,o)),t.ipv6=o=>t.check(X0(Yf,o)),t.cidrv4=o=>t.check(q0(Kf,o)),t.cidrv6=o=>t.check(Y0(Jf,o)),t.e164=o=>t.check(Q0(th,o)),t.datetime=o=>t.check(Tf(o)),t.date=o=>t.check(Of(o)),t.time=o=>t.check(Rf(o)),t.duration=o=>t.check(Df(o))});function w(t){return M0(Uf,t)}const _t=ee("ZodStringFormat",(t,r)=>{xt.init(t,r),pc.init(t,r)}),zf=ee("ZodEmail",(t,r)=>{U1.init(t,r),_t.init(t,r)}),Ls=ee("ZodGUID",(t,r)=>{L1.init(t,r),_t.init(t,r)}),yi=ee("ZodUUID",(t,r)=>{F1.init(t,r),_t.init(t,r)}),Vf=ee("ZodURL",(t,r)=>{z1.init(t,r),_t.init(t,r)}),Zf=ee("ZodEmoji",(t,r)=>{V1.init(t,r),_t.init(t,r)}),$f=ee("ZodNanoID",(t,r)=>{Z1.init(t,r),_t.init(t,r)}),Hf=ee("ZodCUID",(t,r)=>{$1.init(t,r),_t.init(t,r)}),Wf=ee("ZodCUID2",(t,r)=>{H1.init(t,r),_t.init(t,r)}),jf=ee("ZodULID",(t,r)=>{W1.init(t,r),_t.init(t,r)}),Gf=ee("ZodXID",(t,r)=>{j1.init(t,r),_t.init(t,r)}),Xf=ee("ZodKSUID",(t,r)=>{G1.init(t,r),_t.init(t,r)}),qf=ee("ZodIPv4",(t,r)=>{J1.init(t,r),_t.init(t,r)}),Yf=ee("ZodIPv6",(t,r)=>{Q1.init(t,r),_t.init(t,r)}),Kf=ee("ZodCIDRv4",(t,r)=>{e0.init(t,r),_t.init(t,r)}),Jf=ee("ZodCIDRv6",(t,r)=>{t0.init(t,r),_t.init(t,r)}),Qf=ee("ZodBase64",(t,r)=>{n0.init(t,r),_t.init(t,r)}),eh=ee("ZodBase64URL",(t,r)=>{i0.init(t,r),_t.init(t,r)}),th=ee("ZodE164",(t,r)=>{o0.init(t,r),_t.init(t,r)}),nh=ee("ZodJWT",(t,r)=>{a0.init(t,r),_t.init(t,r)}),Zo=ee("ZodNumber",(t,r)=>{lc.init(t,r),pt.init(t,r),t.gt=(c,u)=>t.check(Ds(c,u)),t.gte=(c,u)=>t.check(oo(c,u)),t.min=(c,u)=>t.check(oo(c,u)),t.lt=(c,u)=>t.check(Ms(c,u)),t.lte=(c,u)=>t.check(io(c,u)),t.max=(c,u)=>t.check(io(c,u)),t.int=c=>t.check(Fs(c)),t.safe=c=>t.check(Fs(c)),t.positive=c=>t.check(Ds(0,c)),t.nonnegative=c=>t.check(oo(0,c)),t.negative=c=>t.check(Ms(0,c)),t.nonpositive=c=>t.check(io(0,c)),t.multipleOf=(c,u)=>t.check(Ps(c,u)),t.step=(c,u)=>t.check(Ps(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 sf(Zo,t)}const rh=ee("ZodNumberFormat",(t,r)=>{l0.init(t,r),Zo.init(t,r)});function Fs(t){return lf(rh,t)}const ih=ee("ZodBoolean",(t,r)=>{c0.init(t,r),pt.init(t,r)});function Rt(t){return cf(ih,t)}const oh=ee("ZodNull",(t,r)=>{u0.init(t,r),pt.init(t,r)});function mc(t){return uf(oh,t)}const sh=ee("ZodAny",(t,r)=>{d0.init(t,r),pt.init(t,r)});function mr(){return df(sh)}const ah=ee("ZodUnknown",(t,r)=>{f0.init(t,r),pt.init(t,r)});function bn(){return ff(ah)}const lh=ee("ZodNever",(t,r)=>{h0.init(t,r),pt.init(t,r)});function ch(t){return hf(lh,t)}const uh=ee("ZodArray",(t,r)=>{p0.init(t,r),pt.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(dc(o,c)),t.length=(o,c)=>t.check(fc(o,c)),t.unwrap=()=>t.element});function ue(t,r){return Ef(uh,t,r)}const dh=ee("ZodObject",(t,r)=>{m0.init(t,r),pt.init(t,r),tt(t,"shape",()=>r.shape),t.keyof=()=>Se(Object.keys(t._zod.def.shape)),t.catchall=o=>t.clone({...t._zod.def,catchall:o}),t.passthrough=()=>t.clone({...t._zod.def,catchall:bn()}),t.loose=()=>t.clone({...t._zod.def,catchall:bn()}),t.strict=()=>t.clone({...t._zod.def,catchall:ch()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=o=>Ud(t,o),t.merge=o=>zd(t,o),t.pick=o=>Ld(t,o),t.omit=o=>Fd(t,o),t.partial=(...o)=>Vd(xc,t,o[0]),t.required=(...o)=>Zd(yc,t,o[0])});function T(t,r){const o={type:"object",get shape(){return Uo(this,"shape",{...t}),this.shape},...Ae(r)};return new dh(o)}const gc=ee("ZodUnion",(t,r)=>{cc.init(t,r),pt.init(t,r),t.options=r.options});function Qe(t,r){return new gc({type:"union",options:t,...Ae(r)})}const fh=ee("ZodDiscriminatedUnion",(t,r)=>{gc.init(t,r),g0.init(t,r)});function ut(t,r,o){return new fh({type:"union",options:r,discriminator:t,...Ae(o)})}const hh=ee("ZodIntersection",(t,r)=>{x0.init(t,r),pt.init(t,r)});function ph(t,r){return new hh({type:"intersection",left:t,right:r})}const mh=ee("ZodRecord",(t,r)=>{y0.init(t,r),pt.init(t,r),t.keyType=r.keyType,t.valueType=r.valueType});function ht(t,r,o){return new mh({type:"record",keyType:t,valueType:r,...Ae(o)})}const _o=ee("ZodEnum",(t,r)=>{w0.init(t,r),pt.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 _o({...r,checks:[],...Ae(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 _o({...r,checks:[],...Ae(u),entries:f})}});function Se(t,r){const o=Array.isArray(t)?Object.fromEntries(t.map(c=>[c,c])):t;return new _o({type:"enum",entries:o,...Ae(r)})}const gh=ee("ZodLiteral",(t,r)=>{_0.init(t,r),pt.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 X(t,r){return new gh({type:"literal",values:Array.isArray(t)?t:[t],...Ae(r)})}const xh=ee("ZodTransform",(t,r)=>{v0.init(t,r),pt.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 yh(t){return new xh({type:"transform",transform:t})}const xc=ee("ZodOptional",(t,r)=>{C0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Us(t){return new xc({type:"optional",innerType:t})}const wh=ee("ZodNullable",(t,r)=>{b0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function zs(t){return new wh({type:"nullable",innerType:t})}const _h=ee("ZodDefault",(t,r)=>{E0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function vh(t,r){return new _h({type:"default",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const Ch=ee("ZodPrefault",(t,r)=>{A0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function bh(t,r){return new Ch({type:"prefault",innerType:t,get defaultValue(){return typeof r=="function"?r():r}})}const yc=ee("ZodNonOptional",(t,r)=>{I0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType});function Eh(t,r){return new yc({type:"nonoptional",innerType:t,...Ae(r)})}const Ah=ee("ZodCatch",(t,r)=>{S0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function Ih(t,r){return new Ah({type:"catch",innerType:t,catchValue:typeof r=="function"?r:()=>r})}const Sh=ee("ZodPipe",(t,r)=>{T0.init(t,r),pt.init(t,r),t.in=r.in,t.out=r.out});function Vs(t,r){return new Sh({type:"pipe",in:t,out:r})}const Th=ee("ZodReadonly",(t,r)=>{N0.init(t,r),pt.init(t,r)});function Nh(t){return new Th({type:"readonly",innerType:t})}const Oh=ee("ZodLazy",(t,r)=>{O0.init(t,r),pt.init(t,r),t.unwrap=()=>t._zod.def.getter()});function $o(t){return new Oh({type:"lazy",getter:t})}const kh=ee("ZodCustom",(t,r)=>{k0.init(t,r),pt.init(t,r)});function Rh(t){const r=new on({check:"custom"});return r._zod.check=t,r}function Mh(t,r={}){return Af(kh,t,r)}function Dh(t){const r=Rh(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 Ph(t){return af(Zo,t)}var Le;(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"})(Le||(Le={}));function Zs(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Bi(t){return Object.fromEntries([...t.headers])}var Bh=({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 Il({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},wi=Bh();function vo(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Lh=["fetch failed","failed to fetch"];function Fh({error:t,url:r,requestBodyValues:o}){if(vo(t))return t;if(t instanceof TypeError&&Lh.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new Un({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return t}function Uh(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 zh(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 wc(t,...r){const o=new Headers(zh(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var Vh="3.0.18";function Zh({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 $h=/"__proto__"\s*:/,Hh=/"constructor"\s*:/;function $s(t){const r=JSON.parse(t);return r===null||typeof r!="object"||$h.test(t)===!1&&Hh.test(t)===!1?r:Wh(r)}function Wh(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 Ho(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return $s(t)}try{return $s(t)}finally{Error.stackTraceLimit=r}}var Co=Symbol.for("vercel.ai.validator");function jh(t){return{[Co]:!0,validate:t}}function Gh(t){return typeof t=="object"&&t!==null&&Co in t&&t[Co]===!0&&"validate"in t}function Xh(t){return Gh(t)?t:typeof t=="function"?t():qh(t)}function qh(t){return jh(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 Yh({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=Xh(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 Kh({text:t,schema:r}){try{const o=Ho(t);return r==null?o:Yh({value:o,schema:r})}catch(o){throw Ii.isInstance(o)||qr.isInstance(o)?o:new Ii({text:t,cause:o})}}async function _c({text:t,schema:r}){try{const o=Ho(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 Hs(t){try{return Ho(t),!0}catch{return!1}}function Jh({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new jl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await _c({text:o,schema:r}))}}))}async function Ws({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 Il({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Qh=()=>globalThis.fetch,js=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>ep({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),ep=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=Qh()})=>{try{const g=await m(t,{method:"POST",headers:wc(r,`ai-sdk/provider-utils/${Vh}`,Uh()),body:o.content,signal:f}),C=Bi(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(A){throw vo(A)||Un.isInstance(A)?A:new Un({message:"Failed to process error response",cause:A,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(vo(x)||Un.isInstance(x))?x:new Un({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}}catch(g){throw Fh({error:g,url:t,requestBodyValues:o.values})}},tp=({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 Un({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const C=await Kh({text:m,schema:t});return{responseHeaders:g,value:new Un({message:r(C),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:C,isRetryable:o?.(c,C)})}}catch{return{responseHeaders:g,value:new Un({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},np=t=>async({response:r})=>{const o=Bi(r);if(r.body==null)throw new _d({});return{responseHeaders:o,value:Jh({stream:r.body,schema:t})}},rp=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await _c({text:u,schema:t}),m=Bi(r);if(!f.success)throw new Un({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:ip}=globalThis;function op(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return ip(r)}function sp(t){return t instanceof Uint8Array?op(t):t}function ap(t){return t?.replace(/\/$/,"")}function zr(t){var r,o;return(o=(r=t?.providerOptions)==null?void 0:r.openaiCompatible)!=null?o:{}}function lp(t){const r=[];for(const{role:o,content:c,...u}of t){const f=zr({...u});switch(o){case"system":{r.push({role:"system",content:c,...f});break}case"user":{if(c.length===1&&c[0].type==="text"){r.push({role:"user",content:c[0].text,...zr(c[0])});break}r.push({role:"user",content:c.map(m=>{const g=zr(m);switch(m.type){case"text":return{type:"text",text:m.text,...g};case"file":if(m.mediaType.startsWith("image/")){const C=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${C};base64,${sp(m.data)}`},...g}}else throw new Wl({functionality:`file part media type ${m.mediaType}`})}}),...f});break}case"assistant":{let m="";const g=[];for(const C of c){const x=zr(C);switch(C.type){case"text":{m+=C.text;break}case"tool-call":{g.push({id:C.toolCallId,type:"function",function:{name:C.toolName,arguments:JSON.stringify(C.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 C;switch(g.type){case"text":case"error-text":C=g.value;break;case"content":case"json":case"error-json":C=JSON.stringify(g.value);break}const x=zr(m);r.push({role:"tool",tool_call_id:m.toolCallId,content:C,...x})}break}default:{const m=o;throw new Error(`Unsupported role: ${m}`)}}}return r}function Gs({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 Xs(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 so=T({user:w().optional(),reasoningEffort:w().optional(),textVerbosity:w().optional()}),cp=T({error:T({message:w(),type:w().nullish(),param:mr().nullish(),code:Qe([w(),j()]).nullish()})}),up={errorSchema:cp,errorToMessage:t=>t.error.message};function dp({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 Wl({functionality:`tool choice type: ${f}`})}}}var fp=class{constructor(t,r){this.specificationVersion="v2";var o,c;this.modelId=t,this.config=r;const u=(o=r.errorStructure)!=null?o:up;this.chunkSchema=pp(u.errorSchema),this.failedResponseHandler=tp(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:C,responseFormat:x,seed:A,toolChoice:v,tools:P}){var O,M,D,B;const G=[],Z=Object.assign((O=await Ws({provider:"openai-compatible",providerOptions:g,schema:so}))!=null?O:{},(M=await Ws({provider:this.providerOptionsName,providerOptions:g,schema:so}))!=null?M:{});u!=null&&G.push({type:"unsupported-setting",setting:"topK"}),x?.type==="json"&&x.schema!=null&&!this.supportsStructuredOutputs&&G.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});const{tools:U,toolChoice:Q,toolWarnings:K}=dp({tools:P,toolChoice:v});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:(D=x.name)!=null?D:"response",description:x.description}}:{type:"json_object"}:void 0,stop:C,seed:A,...Object.fromEntries(Object.entries((B=g?.[this.providerOptionsName])!=null?B:{}).filter(([V])=>!Object.keys(so.shape).includes(V))),reasoning_effort:Z.reasoningEffort,verbosity:Z.textVerbosity,messages:lp(t),tools:U,tool_choice:Q},warnings:[...G,...K]}}async doGenerate(t){var r,o,c,u,f,m,g,C,x,A,v,P,O,M,D,B,G;const{args:Z,warnings:U}=await this.getArgs({...t}),Q=JSON.stringify(Z),{responseHeaders:K,value:V,rawValue:z}=await js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Zs(this.config.headers(),t.headers),body:Z,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:rp(hp),abortSignal:t.abortSignal,fetch:this.config.fetch}),te=V.choices[0],S=[],Te=te.message.content;Te!=null&&Te.length>0&&S.push({type:"text",text:Te});const ye=(r=te.message.reasoning_content)!=null?r:te.message.reasoning;if(ye!=null&&ye.length>0&&S.push({type:"reasoning",text:ye}),te.message.tool_calls!=null)for(const Me of te.message.tool_calls)S.push({type:"tool-call",toolCallId:(o=Me.id)!=null?o:wi(),toolName:Me.function.name,input:Me.function.arguments});const re={[this.providerOptionsName]:{},...await((u=(c=this.config.metadataExtractor)==null?void 0:c.extractMetadata)==null?void 0:u.call(c,{parsedBody:z}))},xe=(f=V.usage)==null?void 0:f.completion_tokens_details;return xe?.accepted_prediction_tokens!=null&&(re[this.providerOptionsName].acceptedPredictionTokens=xe?.accepted_prediction_tokens),xe?.rejected_prediction_tokens!=null&&(re[this.providerOptionsName].rejectedPredictionTokens=xe?.rejected_prediction_tokens),{content:S,finishReason:Xs(te.finish_reason),usage:{inputTokens:(g=(m=V.usage)==null?void 0:m.prompt_tokens)!=null?g:void 0,outputTokens:(x=(C=V.usage)==null?void 0:C.completion_tokens)!=null?x:void 0,totalTokens:(v=(A=V.usage)==null?void 0:A.total_tokens)!=null?v:void 0,reasoningTokens:(M=(O=(P=V.usage)==null?void 0:P.completion_tokens_details)==null?void 0:O.reasoning_tokens)!=null?M:void 0,cachedInputTokens:(G=(B=(D=V.usage)==null?void 0:D.prompt_tokens_details)==null?void 0:B.cached_tokens)!=null?G:void 0},providerMetadata:re,request:{body:Q},response:{...Gs(V),headers:K,body:z},warnings:U}}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 js({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:Zs(this.config.headers(),t.headers),body:u,failedResponseHandler:this.failedResponseHandler,successfulResponseHandler:np(this.chunkSchema),abortSignal:t.abortSignal,fetch:this.config.fetch}),C=[];let x="unknown";const A={completionTokens:void 0,completionTokensDetails:{reasoningTokens:void 0,acceptedPredictionTokens:void 0,rejectedPredictionTokens:void 0},promptTokens:void 0,promptTokensDetails:{cachedTokens:void 0},totalTokens:void 0};let v=!0;const P=this.providerOptionsName;let O=!1,M=!1;return{stream:g.pipeThrough(new TransformStream({start(D){D.enqueue({type:"stream-start",warnings:c})},transform(D,B){var G,Z,U,Q,K,V,z,te,S,Te,ye,re,xe;if(t.includeRawChunks&&B.enqueue({type:"raw",rawValue:D.rawValue}),!D.success){x="error",B.enqueue({type:"error",error:D.error});return}const Me=D.value;if(f?.processChunk(D.rawValue),"error"in Me){x="error",B.enqueue({type:"error",error:Me.error.message});return}if(v&&(v=!1,B.enqueue({type:"response-metadata",...Gs(Me)})),Me.usage!=null){const{prompt_tokens:J,completion_tokens:me,total_tokens:fe,prompt_tokens_details:ie,completion_tokens_details:pe}=Me.usage;A.promptTokens=J??void 0,A.completionTokens=me??void 0,A.totalTokens=fe??void 0,pe?.reasoning_tokens!=null&&(A.completionTokensDetails.reasoningTokens=pe?.reasoning_tokens),pe?.accepted_prediction_tokens!=null&&(A.completionTokensDetails.acceptedPredictionTokens=pe?.accepted_prediction_tokens),pe?.rejected_prediction_tokens!=null&&(A.completionTokensDetails.rejectedPredictionTokens=pe?.rejected_prediction_tokens),ie?.cached_tokens!=null&&(A.promptTokensDetails.cachedTokens=ie?.cached_tokens)}const $=Me.choices[0];if($?.finish_reason!=null&&(x=Xs($.finish_reason)),$?.delta==null)return;const ge=$.delta,ne=(G=ge.reasoning_content)!=null?G:ge.reasoning;if(ne&&(O||(B.enqueue({type:"reasoning-start",id:"reasoning-0"}),O=!0),B.enqueue({type:"reasoning-delta",id:"reasoning-0",delta:ne})),ge.content&&(M||(B.enqueue({type:"text-start",id:"txt-0"}),M=!0),B.enqueue({type:"text-delta",id:"txt-0",delta:ge.content})),ge.tool_calls!=null)for(const J of ge.tool_calls){const me=J.index;if(C[me]==null){if(J.id==null)throw new ws({data:J,message:"Expected 'id' to be a string."});if(((Z=J.function)==null?void 0:Z.name)==null)throw new ws({data:J,message:"Expected 'function.name' to be a string."});B.enqueue({type:"tool-input-start",id:J.id,toolName:J.function.name}),C[me]={id:J.id,type:"function",function:{name:J.function.name,arguments:(U=J.function.arguments)!=null?U:""},hasFinished:!1};const ie=C[me];((Q=ie.function)==null?void 0:Q.name)!=null&&((K=ie.function)==null?void 0:K.arguments)!=null&&(ie.function.arguments.length>0&&B.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),Hs(ie.function.arguments)&&(B.enqueue({type:"tool-input-end",id:ie.id}),B.enqueue({type:"tool-call",toolCallId:(V=ie.id)!=null?V:wi(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const fe=C[me];fe.hasFinished||(((z=J.function)==null?void 0:z.arguments)!=null&&(fe.function.arguments+=(S=(te=J.function)==null?void 0:te.arguments)!=null?S:""),B.enqueue({type:"tool-input-delta",id:fe.id,delta:(Te=J.function.arguments)!=null?Te:""}),((ye=fe.function)==null?void 0:ye.name)!=null&&((re=fe.function)==null?void 0:re.arguments)!=null&&Hs(fe.function.arguments)&&(B.enqueue({type:"tool-input-end",id:fe.id}),B.enqueue({type:"tool-call",toolCallId:(xe=fe.id)!=null?xe:wi(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}},flush(D){var B,G,Z,U,Q,K;O&&D.enqueue({type:"reasoning-end",id:"reasoning-0"}),M&&D.enqueue({type:"text-end",id:"txt-0"});for(const z of C.filter(te=>!te.hasFinished))D.enqueue({type:"tool-input-end",id:z.id}),D.enqueue({type:"tool-call",toolCallId:(B=z.id)!=null?B:wi(),toolName:z.function.name,input:z.function.arguments});const V={[P]:{},...f?.buildMetadata()};A.completionTokensDetails.acceptedPredictionTokens!=null&&(V[P].acceptedPredictionTokens=A.completionTokensDetails.acceptedPredictionTokens),A.completionTokensDetails.rejectedPredictionTokens!=null&&(V[P].rejectedPredictionTokens=A.completionTokensDetails.rejectedPredictionTokens),D.enqueue({type:"finish",finishReason:x,usage:{inputTokens:(G=A.promptTokens)!=null?G:void 0,outputTokens:(Z=A.completionTokens)!=null?Z:void 0,totalTokens:(U=A.totalTokens)!=null?U:void 0,reasoningTokens:(Q=A.completionTokensDetails.reasoningTokens)!=null?Q:void 0,cachedInputTokens:(K=A.promptTokensDetails.cachedTokens)!=null?K:void 0},providerMetadata:V})}})),request:{body:u},response:{headers:m}}}},vc=T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish(),hp=T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({message:T({role:X("assistant").nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(T({id:w().nullish(),function:T({name:w(),arguments:w()})})).nullish()}),finish_reason:w().nullish()})),usage:vc}),pp=t=>Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({delta:T({role:Se(["assistant"]).nullish(),content:w().nullish(),reasoning_content:w().nullish(),reasoning:w().nullish(),tool_calls:ue(T({index:j(),id:w().nullish(),function:T({name:w().nullish(),arguments:w().nullish()})})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:vc}),t]);T({echo:Rt().optional(),logitBias:ht(w(),j()).optional(),suffix:w().optional(),user:w().optional()});var mp=T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()});T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w()})),usage:mp.nullish()});T({dimensions:j().optional(),user:w().optional()});T({data:ue(T({embedding:ue(j())})),usage:T({prompt_tokens:j()}).nullish(),providerMetadata:ht(w(),ht(w(),mr())).optional()});T({data:ue(T({b64_json:w()}))});var qs=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}}},gp={extractMetadata:async({parsedBody:t})=>{const r=await Jr({value:t,schema:xp});return!r.success||r.value.usage==null?void 0:qs(r.value.usage)},createStreamExtractor:()=>{let t;return{processChunk:async r=>{var o,c;const u=await Jr({value:r,schema:yp});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:()=>qs(t)}}},Cc=T({prompt_cache_hit_tokens:j().nullish(),prompt_cache_miss_tokens:j().nullish()}),xp=T({usage:Cc.nullish()}),yp=T({choices:ue(T({finish_reason:w().nullish()})).nullish(),usage:Cc.nullish()}),wp="1.0.30";function bc(t={}){var r;const o=ap((r=t.baseURL)!=null?r:"https://api.deepseek.com/v1"),c=()=>wc({Authorization:`Bearer ${Zh({apiKey:t.apiKey,environmentVariableName:"DEEPSEEK_API_KEY",description:"DeepSeek API key"})}`,...t.headers},`ai-sdk/deepseek/${wp}`);class u extends fp{addJsonInstruction(C){var x;if(((x=C.responseFormat)==null?void 0:x.type)!=="json")return C;const P=[...Array.isArray(C.prompt)?C.prompt:[],{role:"user",content:[{type:"text",text:"Return ONLY a valid JSON object."}]}];return{...C,prompt:P}}async doGenerate(C){return super.doGenerate(this.addJsonInstruction(C))}async doStream(C){return super.doStream(this.addJsonInstruction(C))}}const f=g=>new u(g,{provider:"deepseek.chat",url:({path:C})=>`${o}${C}`,headers:c,fetch:t.fetch,metadataExtractor:gp}),m=g=>f(g);return m.languageModel=f,m.chat=f,m.textEmbeddingModel=g=>{throw new _s({modelId:g,modelType:"textEmbeddingModel"})},m.imageModel=g=>{throw new _s({modelId:g,modelType:"imageModel"})},m}bc();var Ec="vercel.ai.error",_p=Symbol.for(Ec),Ys,Ks,St=class Ac extends(Ks=Error,Ys=_p,Ks){constructor({name:r,message:o,cause:c}){super(o),this[Ys]=!0,this.name=r,this.cause=c}static isInstance(r){return Ac.hasMarker(r,Ec)}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}},Ic="AI_APICallError",Sc=`vercel.ai.error.${Ic}`,vp=Symbol.for(Sc),Js,Qs,cn=class extends(Qs=St,Js=vp,Qs){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:C}){super({name:Ic,message:t,cause:m}),this[Js]=!0,this.url=r,this.requestBodyValues=o,this.statusCode=c,this.responseHeaders=u,this.responseBody=f,this.isRetryable=g,this.data=C}static isInstance(t){return St.hasMarker(t,Sc)}},Tc="AI_EmptyResponseBodyError",Nc=`vercel.ai.error.${Tc}`,Cp=Symbol.for(Nc),ea,ta,bp=class extends(ta=St,ea=Cp,ta){constructor({message:t="Empty response body"}={}){super({name:Tc,message:t}),this[ea]=!0}static isInstance(t){return St.hasMarker(t,Nc)}};function Oc(t){return t==null?"unknown error":typeof t=="string"?t:t instanceof Error?t.message:JSON.stringify(t)}var kc="AI_InvalidArgumentError",Rc=`vercel.ai.error.${kc}`,Ep=Symbol.for(Rc),na,ra,Mc=class extends(ra=St,na=Ep,ra){constructor({message:t,cause:r,argument:o}){super({name:kc,message:t,cause:r}),this[na]=!0,this.argument=o}static isInstance(t){return St.hasMarker(t,Rc)}},Dc="AI_InvalidPromptError",Pc=`vercel.ai.error.${Dc}`,Ap=Symbol.for(Pc),ia,oa,Ip=class extends(oa=St,ia=Ap,oa){constructor({prompt:t,message:r,cause:o}){super({name:Dc,message:`Invalid prompt: ${r}`,cause:o}),this[ia]=!0,this.prompt=t}static isInstance(t){return St.hasMarker(t,Pc)}},Bc="AI_InvalidResponseDataError",Lc=`vercel.ai.error.${Bc}`,Sp=Symbol.for(Lc),sa,aa,ao=class extends(aa=St,sa=Sp,aa){constructor({data:t,message:r=`Invalid response data: ${JSON.stringify(t)}.`}){super({name:Bc,message:r}),this[sa]=!0,this.data=t}static isInstance(t){return St.hasMarker(t,Lc)}},Fc="AI_JSONParseError",Uc=`vercel.ai.error.${Fc}`,Tp=Symbol.for(Uc),la,ca,Oi=class extends(ca=St,la=Tp,ca){constructor({text:t,cause:r}){super({name:Fc,message:`JSON parsing failed: Text: ${t}.
|
|
35
|
+
Error message: ${Oc(r)}`,cause:r}),this[la]=!0,this.text=t}static isInstance(t){return St.hasMarker(t,Uc)}},zc="AI_LoadAPIKeyError",Vc=`vercel.ai.error.${zc}`,Np=Symbol.for(Vc),ua,da,_i=class extends(da=St,ua=Np,da){constructor({message:t}){super({name:zc,message:t}),this[ua]=!0}static isInstance(t){return St.hasMarker(t,Vc)}},Zc="AI_TooManyEmbeddingValuesForCallError",$c=`vercel.ai.error.${Zc}`,Op=Symbol.for($c),fa,ha,kp=class extends(ha=St,fa=Op,ha){constructor(t){super({name:Zc,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[fa]=!0,this.provider=t.provider,this.modelId=t.modelId,this.maxEmbeddingsPerCall=t.maxEmbeddingsPerCall,this.values=t.values}static isInstance(t){return St.hasMarker(t,$c)}},Hc="AI_TypeValidationError",Wc=`vercel.ai.error.${Hc}`,Rp=Symbol.for(Wc),pa,ma,Qr=class bo extends(ma=St,pa=Rp,ma){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:Hc,message:`${u}: Value: ${JSON.stringify(r)}.
|
|
36
|
+
Error message: ${Oc(o)}`,cause:o}),this[pa]=!0,this.value=r,this.context=c}static isInstance(r){return St.hasMarker(r,Wc)}static wrap({value:r,cause:o,context:c}){var u,f,m;return bo.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 bo({value:r,cause:o,context:c})}},jc="AI_UnsupportedFunctionalityError",Gc=`vercel.ai.error.${jc}`,Mp=Symbol.for(Gc),ga,xa,zn=class extends(xa=St,ga=Mp,xa){constructor({functionality:t,message:r=`'${t}' functionality not supported.`}){super({name:jc,message:r}),this[ga]=!0,this.functionality=t}static isInstance(t){return St.hasMarker(t,Gc)}};function En(...t){return t.reduce((r,o)=>({...r,...o??{}}),{})}function Dp({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 Pp=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:Bp,atob:Lp}=globalThis;function Wo(t){const r=t.replace(/-/g,"+").replace(/_/g,"/"),o=Lp(r);return Uint8Array.from(o,c=>c.codePointAt(0))}function Fp(t){let r="";for(let o=0;o<t.length;o++)r+=String.fromCodePoint(t[o]);return Bp(r)}function Tr(t){return t instanceof Uint8Array?Fp(t):t}function Up(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}var Xc="AI_DownloadError",qc=`vercel.ai.error.${Xc}`,zp=Symbol.for(qc),ya,wa,vn=class extends(wa=St,ya=zp,wa){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:Xc,message:u,cause:c}),this[ya]=!0,this.url=t,this.statusCode=r,this.statusText=o}static isInstance(t){return St.hasMarker(t,qc)}},Yc=2*1024*1024*1024;async function Vp({response:t,url:r,maxBytes:o=Yc}){const c=t.headers.get("content-length");if(c!=null){const A=parseInt(c,10);if(!isNaN(A)&&A>o)throw new vn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes (Content-Length: ${A}).`})}const u=t.body;if(u==null)return new Uint8Array(0);const f=u.getReader(),m=[];let g=0;try{for(;;){const{done:A,value:v}=await f.read();if(A)break;if(g+=v.length,g>o)throw new vn({url:r,message:`Download of ${r} exceeded maximum size of ${o} bytes.`});m.push(v)}}finally{try{await f.cancel()}finally{f.releaseLock()}}const C=new Uint8Array(g);let x=0;for(const A of m)C.set(A,x),x+=A.length;return C}function _a(t){let r;try{r=new URL(t)}catch{throw new vn({url:t,message:`Invalid URL: ${t}`})}if(r.protocol!=="http:"&&r.protocol!=="https:")throw new vn({url:t,message:`URL scheme must be http or https, got ${r.protocol}`});const o=r.hostname;if(!o)throw new vn({url:t,message:"URL must have a hostname"});if(o==="localhost"||o.endsWith(".local")||o.endsWith(".localhost"))throw new vn({url:t,message:`URL with hostname ${o} is not allowed`});if(o.startsWith("[")&&o.endsWith("]")){const c=o.slice(1,-1);if(Zp(c))throw new vn({url:t,message:`URL with IPv6 address ${o} is not allowed`});return}if(Kc(o)){if(Eo(o))throw new vn({url:t,message:`URL with IP address ${o} is not allowed`});return}}function Kc(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 Eo(t){const r=t.split(".").map(Number),[o,c]=r;return o===0||o===10||o===127||o===169&&c===254||o===172&&c>=16&&c<=31||o===192&&c===168}function Zp(t){const r=t.toLowerCase();if(r==="::1"||r==="::")return!0;if(r.startsWith("::ffff:")){const o=r.slice(7);if(Kc(o))return Eo(o);const c=o.split(":");if(c.length===2){const u=parseInt(c[0],16),f=parseInt(c[1],16);if(!isNaN(u)&&!isNaN(f)){const m=u>>8&255,g=u&255,C=f>>8&255,x=f&255;return Eo(`${m}.${g}.${C}.${x}`)}}}return!!(r.startsWith("fc")||r.startsWith("fd")||r.startsWith("fe80"))}async function Jc(t,r){var o,c;_a(t);try{const u=await fetch(t,{signal:r?.abortSignal});if(u.redirected&&_a(u.url),!u.ok)throw new vn({url:t,statusCode:u.status,statusText:u.statusText});const f=await Vp({response:u,url:t,maxBytes:(o=r?.maxBytes)!=null?o:Yc}),m=(c=u.headers.get("content-type"))!=null?c:void 0;return new Blob([f],m?{type:m}:void 0)}catch(u){throw vn.isInstance(u)?u:new vn({url:t,cause:u})}}var $p=({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 Mc({argument:"separator",message:`The separator "${c}" must not be part of the alphabet "${o}".`});return()=>`${t}${c}${u()}`},Kt=$p();function Ao(t){return(t instanceof Error||t instanceof DOMException)&&(t.name==="AbortError"||t.name==="ResponseAborted"||t.name==="TimeoutError")}var Hp=["fetch failed","failed to fetch"],Wp=["ConnectionRefused","ConnectionClosed","FailedToOpenSocket","ECONNRESET","ECONNREFUSED","ETIMEDOUT","EPIPE"];function jp(t){if(!(t instanceof Error))return!1;const r=t.code;return!!(typeof r=="string"&&Wp.includes(r))}function Gp({error:t,url:r,requestBodyValues:o}){if(Ao(t))return t;if(t instanceof TypeError&&Hp.includes(t.message.toLowerCase())){const c=t.cause;if(c!=null)return new cn({message:`Cannot connect to API: ${c.message}`,cause:c,url:r,requestBodyValues:o,isRetryable:!0})}return jp(t)?new cn({message:`Cannot connect to API: ${t.message}`,cause:t,url:r,requestBodyValues:o,isRetryable:!0}):t}function Xp(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 qp(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 Qc(t,...r){const o=new Headers(qp(t)),c=o.get("user-agent")||"";return o.set("user-agent",[c,...r].filter(Boolean).join(" ")),Object.fromEntries(o.entries())}var Yp="4.0.21";function va(t){return t!=null}function Kp({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 is 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 Jp({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 Qp(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 em=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,tm=/"(?: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 Ca(t){const r=JSON.parse(t);return r===null||typeof r!="object"||em.test(t)===!1&&tm.test(t)===!1?r:nm(r)}function nm(t){let r=[t];for(;r.length;){const o=r;r=[];for(const c of o){if(Object.prototype.hasOwnProperty.call(c,"__proto__"))throw new SyntaxError("Object contains forbidden prototype property");if(Object.prototype.hasOwnProperty.call(c,"constructor")&&c.constructor!==null&&typeof c.constructor=="object"&&Object.prototype.hasOwnProperty.call(c.constructor,"prototype"))throw new SyntaxError("Object contains forbidden prototype property");for(const u in c){const f=c[u];f&&typeof f=="object"&&r.push(f)}}}return t}function jo(t){const{stackTraceLimit:r}=Error;try{Error.stackTraceLimit=0}catch{return Ca(t)}try{return Ca(t)}finally{Error.stackTraceLimit=r}}function Go(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]=cr(o[c])}t.items!=null&&(t.items=Array.isArray(t.items)?t.items.map(cr):cr(t.items)),t.anyOf!=null&&(t.anyOf=t.anyOf.map(cr)),t.allOf!=null&&(t.allOf=t.allOf.map(cr)),t.oneOf!=null&&(t.oneOf=t.oneOf.map(cr));const{definitions:r}=t;if(r!=null)for(const o of Object.keys(r))r[o]=cr(r[o]);return t}function cr(t){return typeof t=="boolean"?t:Go(t)}var rm=Symbol("Let zodToJsonSchema decide on which parser to use"),ba={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"},im=t=>typeof t=="string"?{...ba,name:t}:{...ba,...t};function fn(){return{}}function om(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)!==Le.ZodAny&&(f.items=rt(t.type._def,{...r,currentPath:[...r.currentPath,"items"]})),t.minLength&&(f.minItems=t.minLength.value),t.maxLength&&(f.maxItems=t.maxLength.value),t.exactLength&&(f.minItems=t.exactLength.value,f.maxItems=t.exactLength.value),f}function sm(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 am(){return{type:"boolean"}}function eu(t,r){return rt(t.type._def,r)}var lm=(t,r)=>rt(t.innerType._def,r);function tu(t,r,o){const c=o??r.dateStrategy;if(Array.isArray(c))return{anyOf:c.map((u,f)=>tu(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 cm(t)}}var cm=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 um(t,r){return{...rt(t.innerType._def,r),default:t.defaultValue()}}function dm(t,r){return r.effectStrategy==="input"?rt(t.schema._def,r):fn()}function fm(t){return{type:"string",enum:Array.from(t.values)}}var hm=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function pm(t,r){const o=[rt(t.left._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),rt(t.right._def,{...r,currentPath:[...r.currentPath,"allOf","1"]})].filter(u=>!!u),c=[];return o.forEach(u=>{if(hm(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 mm(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 lo=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:()=>(lo===void 0&&(lo=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),lo),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 nu(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":_n(o,"email",c.message,r);break;case"format:idn-email":_n(o,"idn-email",c.message,r);break;case"pattern:zod":Yt(o,wn.email,c.message,r);break}break;case"url":_n(o,"uri",c.message,r);break;case"uuid":_n(o,"uuid",c.message,r);break;case"regex":Yt(o,c.regex,c.message,r);break;case"cuid":Yt(o,wn.cuid,c.message,r);break;case"cuid2":Yt(o,wn.cuid2,c.message,r);break;case"startsWith":Yt(o,RegExp(`^${co(c.value,r)}`),c.message,r);break;case"endsWith":Yt(o,RegExp(`${co(c.value,r)}$`),c.message,r);break;case"datetime":_n(o,"date-time",c.message,r);break;case"date":_n(o,"date",c.message,r);break;case"time":_n(o,"time",c.message,r);break;case"duration":_n(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":{Yt(o,RegExp(co(c.value,r)),c.message,r);break}case"ip":{c.version!=="v6"&&_n(o,"ipv4",c.message,r),c.version!=="v4"&&_n(o,"ipv6",c.message,r);break}case"base64url":Yt(o,wn.base64url,c.message,r);break;case"jwt":Yt(o,wn.jwt,c.message,r);break;case"cidr":{c.version!=="v6"&&Yt(o,wn.ipv4Cidr,c.message,r),c.version!=="v4"&&Yt(o,wn.ipv6Cidr,c.message,r);break}case"emoji":Yt(o,wn.emoji(),c.message,r);break;case"ulid":{Yt(o,wn.ulid,c.message,r);break}case"base64":{switch(r.base64Strategy){case"format:binary":{_n(o,"binary",c.message,r);break}case"contentEncoding:base64":{o.contentEncoding="base64";break}case"pattern:zod":{Yt(o,wn.base64,c.message,r);break}}break}case"nanoid":Yt(o,wn.nanoid,c.message,r)}return o}function co(t,r){return r.patternStrategy==="escape"?xm(t):t}var gm=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function xm(t){let r="";for(let o=0;o<t.length;o++)gm.has(t[o])||(r+="\\"),r+=t[o];return r}function _n(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 Yt(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:Ea(r,c),...o&&c.errorMessages&&{errorMessage:{pattern:o}}})):t.pattern=Ea(r,c)}function Ea(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,C=!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]/)){C?(f+=u[x],f+=`${u[x-2]}-${u[x]}`.toUpperCase(),C=!1):u[x+1]==="-"&&((o=u[x+2])!=null&&o.match(/[a-z]/))?(f+=u[x],C=!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
|
|
37
37
|
]))`;continue}else if(u[x]==="$"){f+=`($|(?=[\r
|
|
38
|
-
]))`;continue}}if(c.s&&u[x]==="."){f+=
|
|
38
|
+
]))`;continue}}if(c.s&&u[x]==="."){f+=g?`${u[x]}\r
|
|
39
39
|
`:`[${u[x]}\r
|
|
40
|
-
]`;continue}f+=u[x],u[x]==="\\"?g=!0:m&&u[x]==="]"?m=!1:!m&&u[x]==="["&&(m=!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 Qc(t,r){var o,c,u,f,g,m;const v={type:"object",additionalProperties:(o=tt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===Oe.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:x,...E}=Jc(t.keyType._def,r);return{...v,propertyNames:E}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===Oe.ZodEnum)return{...v,propertyNames:{enum:t.keyType._def.values}};if(((g=t.keyType)==null?void 0:g._def.typeName)===Oe.ZodBranded&&t.keyType._def.type._def.typeName===Oe.ZodString&&((m=t.keyType._def.type._def.checks)!=null&&m.length)){const{type:x,...E}=Yc(t.keyType._def,r);return{...v,propertyNames:E}}}return v}function yg(t,r){if(r.mapStrategy==="record")return Qc(t,r);const o=tt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||dn(),c=tt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||dn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function _g(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 vg(){return{not:dn()}}function Cg(){return{type:"null"}}var Ao={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function bg(t,r){const o=t.options instanceof Map?Array.from(t.options.values()):t.options;if(o.every(c=>c._def.typeName in Ao&&(!c._def.checks||!c._def.checks.length))){const c=o.reduce((u,f)=>{const g=Ao[f._def.typeName];return g&&!u.includes(g)?[...u,g]: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 g=typeof f._def.value;switch(g){case"string":case"number":case"boolean":return[...u,g];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,g,m)=>m.indexOf(f)===g);return{type:u.length>1?u:u[0],enum:o.reduce((f,g)=>f.includes(g._def.value)?f:[...f,g._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 Eg(t,r)}var Eg=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>tt(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 Ag(t,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return{type:[Ao[t.innerType._def.typeName],"null"]};const o=tt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function Ig(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 Sg(t,r){const o={type:"object",properties:{}},c=[],u=t.shape();for(const g in u){let m=u[g];if(m===void 0||m._def===void 0)continue;const v=Ng(m),x=tt(m._def,{...r,currentPath:[...r.currentPath,"properties",g],propertyPath:[...r.currentPath,"properties",g]});x!==void 0&&(o.properties[g]=x,v||c.push(g))}c.length&&(o.required=c);const f=Tg(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Tg(t,r){if(t.catchall._def.typeName!=="ZodNever")return tt(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 Ng(t){try{return t.isOptional()}catch{return!0}}var Og=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return tt(t.innerType._def,r);const c=tt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:dn()},c]}:dn()},kg=(t,r)=>{if(r.pipeStrategy==="input")return tt(t.in._def,r);if(r.pipeStrategy==="output")return tt(t.out._def,r);const o=tt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=tt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function Rg(t,r){return tt(t.type._def,r)}function Mg(t,r){const c={type:"array",uniqueItems:!0,items:tt(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 Dg(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>tt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:tt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>tt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Pg(){return{not:dn()}}function Bg(){return dn()}var Lg=(t,r)=>tt(t.innerType._def,r),Fg=(t,r,o)=>{switch(r){case Oe.ZodString:return Jc(t,o);case Oe.ZodNumber:return Ig(t);case Oe.ZodObject:return Sg(t,o);case Oe.ZodBigInt:return ag(t);case Oe.ZodBoolean:return lg();case Oe.ZodDate:return Kc(t,o);case Oe.ZodUndefined:return Pg();case Oe.ZodNull:return Cg();case Oe.ZodArray:return sg(t,o);case Oe.ZodUnion:case Oe.ZodDiscriminatedUnion:return bg(t,o);case Oe.ZodIntersection:return gg(t,o);case Oe.ZodTuple:return Dg(t,o);case Oe.ZodRecord:return Qc(t,o);case Oe.ZodLiteral:return mg(t);case Oe.ZodEnum:return hg(t);case Oe.ZodNativeEnum:return _g(t);case Oe.ZodNullable:return Ag(t,o);case Oe.ZodOptional:return Og(t,o);case Oe.ZodMap:return yg(t,o);case Oe.ZodSet:return Mg(t,o);case Oe.ZodLazy:return()=>t.getter()._def;case Oe.ZodPromise:return Rg(t,o);case Oe.ZodNaN:case Oe.ZodNever:return vg();case Oe.ZodEffects:return fg(t,o);case Oe.ZodAny:return dn();case Oe.ZodUnknown:return Bg();case Oe.ZodDefault:return dg(t,o);case Oe.ZodBranded:return Yc(t,o);case Oe.ZodReadonly:return Lg(t,o);case Oe.ZodCatch:return cg(t,o);case Oe.ZodPipeline:return kg(t,o);case Oe.ZodFunction:case Oe.ZodVoid:case Oe.ZodSymbol:return;default:return(c=>{})()}},Ug=(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 tt(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!==ig)return v}if(u&&!o){const v=zg(u,r);if(v!==void 0)return v}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const g=Fg(t,t.typeName,r),m=typeof g=="function"?tt(g(),r):g;if(m&&Vg(t,r,m),r.postProcess){const v=r.postProcess(m,t,r);return f.jsonSchema=m,v}return f.jsonSchema=m,m}var zg=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ug(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`),dn()):r.$refStrategy==="seen"?dn():void 0}},Vg=(t,r,o)=>(t.description&&(o.description=t.description),o),Zg=t=>{const r=og(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}]))}},$g=(t,r)=>{var o;const c=Zg(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((x,[E,A])=>{var B;return{...x,[E]:(B=tt(A._def,{...c,currentPath:[...c.basePath,c.definitionPath,E]},!0))!=null?B:dn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,g=(o=tt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:dn(),m=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;m!==void 0&&(g.title=m);const v=f===void 0?u?{...g,[c.definitionPath]:u}:g:{$ref:[...c.$refStrategy==="relative"?[]:c.basePath,c.definitionPath,f].join("/"),[c.definitionPath]:{...u,[f]:g}};return v.$schema="http://json-schema.org/draft-07/schema#",v},Io=Symbol.for("vercel.ai.schema");function Pe(t){let r;return()=>(r==null&&(r=t()),r)}function Bi(t,{validate:r}={}){return{[Io]:!0,_type:void 0,get jsonSchema(){return typeof t=="function"&&(t=t()),t},validate:r}}function Wg(t){return typeof t=="object"&&t!==null&&Io in t&&t[Io]===!0&&"jsonSchema"in t&&"validate"in t}function Hg(t){return t==null?Bi({properties:{},additionalProperties:!1}):Wg(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Me(t):jg(t):t()}function jg(t){return Bi(()=>$o(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 Kr({value:r,cause:o.issues})}}})}function Gg(t,r){var o;const c=(o=void 0)!=null?o:!1;return Bi(()=>$g(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 Xg(t,r){var o;const c=(o=void 0)!=null?o:!1;return Bi(()=>$o(Af(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await cc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function qg(t){return"_zod"in t}function Me(t,r){return qg(t)?Xg(t):Gg(t)}async function Wt({value:t,schema:r,context:o}){const c=await Wo({value:t,schema:r,context:o});if(!c.success)throw Kr.wrap({value:t,cause:c.error,context:o});return c.value}async function Wo({value:t,schema:r,context:o}){const c=Hg(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:Kr.wrap({value:t,cause:u.error,context:o}),rawValue:t}}catch(u){return{success:!1,error:Kr.wrap({value:t,cause:u,context:o}),rawValue:t}}}async function Yg({text:t,schema:r}){try{const o=Zo(t);return r==null?o:Wt({value:o,schema:r})}catch(o){throw Ni.isInstance(o)||Kr.isInstance(o)?o:new Ni({text:t,cause:o})}}async function eu({text:t,schema:r}){try{const o=Zo(t);return r==null?{success:!0,value:o,rawValue:o}:await Wo({value:o,schema:r})}catch(o){return{success:!1,error:Ni.isInstance(o)?o:new Ni({text:t,cause:o}),rawValue:void 0}}}function _a(t){try{return Zo(t),!0}catch{return!1}}function Kg({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new Zl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await eu({text:o,schema:r}))}}))}async function Fn({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Wo({value:r[t],schema:o});if(!c.success)throw new Nc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Jg=()=>globalThis.fetch,Un=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g})=>nu({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g}),tu=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g})=>nu({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:g}),nu=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:g=Jg()})=>{try{const m=await g(t,{method:"POST",headers:qc(r,`ai-sdk/provider-utils/${Kp}`,qp()),body:o.content,signal:f}),v=ti(m);if(!m.ok){let x;try{x=await u({response:m,url:t,requestBodyValues:o.values})}catch(E){throw Eo(E)||ln.isInstance(E)?E:new ln({message:"Failed to process error response",cause:E,statusCode:m.status,url:t,responseHeaders:v,requestBodyValues:o.values})}throw x.value}try{return await c({response:m,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(Eo(x)||ln.isInstance(x))?x:new ln({message:"Failed to process successful response",cause:x,statusCode:m.status,url:t,responseHeaders:v,requestBodyValues:o.values})}}catch(m){throw Xp({error:m,url:t,requestBodyValues:o.values})}};function Qg({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:g,onInputDelta:m,onInputAvailable:v,...x})=>({type:"provider",id:t,args:x,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:g,onInputDelta:m,onInputAvailable:v})}function zn({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:g,onInputStart:m,onInputDelta:v,onInputAvailable:x,...E})=>({type:"provider",id:t,args:E,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:g,onInputStart:m,onInputDelta:v,onInputAvailable:x,supportsDeferredResults:c})}var em=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const g=await c.text(),m=ti(c);if(g.trim()==="")return{responseHeaders:m,value:new ln({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,isRetryable:o?.(c)})};try{const v=await Yg({text:g,schema:t});return{responseHeaders:m,value:new ln({message:r(v),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,data:v,isRetryable:o?.(c,v)})}}catch{return{responseHeaders:m,value:new ln({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:m,responseBody:g,isRetryable:o?.(c)})}}},Ho=t=>async({response:r})=>{const o=ti(r);if(r.body==null)throw new bp({});return{responseHeaders:o,value:Kg({stream:r.body,schema:t})}},cr=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await eu({text:u,schema:t}),g=ti(r);if(!f.success)throw new ln({message:"Invalid JSON response",cause:f.error,statusCode:r.status,responseHeaders:g,responseBody:u,url:o,requestBodyValues:c});return{responseHeaders:g,value:f.value,rawValue:f.rawValue}},tm=()=>async({response:t,url:r,requestBodyValues:o})=>{const c=ti(t);if(!t.body)throw new ln({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 ln({message:"Failed to read response as array buffer",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:u})}};function nm(t){return t?.replace(/\/$/,"")}var jo=T({error:T({message:_(),type:_().nullish(),param:dr().nullish(),code:Je([_(),q()]).nullish()})}),En=em({errorSchema:jo,errorToMessage:t=>t.error.message});function ru(t){const r=t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),o=t.startsWith("gpt-4")||t.startsWith("gpt-5-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-nano")&&!t.startsWith("gpt-5-chat")||t.startsWith("o3")||t.startsWith("o4-mini"),c=t.startsWith("o1")||t.startsWith("o3")||t.startsWith("o4-mini")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat"),u=t.startsWith("gpt-5.1")||t.startsWith("gpt-5.2");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function va(t){var r,o,c,u,f,g;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 m=(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=(g=(f=t.completion_tokens_details)==null?void 0:f.reasoning_tokens)!=null?g:0;return{inputTokens:{total:m,noCache:m-x,cacheRead:x,cacheWrite:void 0},outputTokens:{total:v,text:v-E,reasoning:E},raw:t}}function rm({prompt:t,systemMessageMode:r="system"}){var o;const c=[],u=[];for(const{role:f,content:g}of t)switch(f){case"system":{switch(r){case"system":{c.push({role:"system",content:g});break}case"developer":{c.push({role:"developer",content:g});break}case"remove":{u.push({type:"other",message:"system messages are removed for this model"});break}default:{const m=r;throw new Error(`Unsupported system message mode: ${m}`)}}break}case"user":{if(g.length===1&&g[0].type==="text"){c.push({role:"user",content:g[0].text});break}c.push({role:"user",content:g.map((m,v)=>{var x,E,A;switch(m.type){case"text":return{type:"text",text:m.text};case"file":if(m.mediaType.startsWith("image/")){const B=m.mediaType==="image/*"?"image/jpeg":m.mediaType;return{type:"image_url",image_url:{url:m.data instanceof URL?m.data.toString():`data:${B};base64,${Er(m.data)}`,detail:(E=(x=m.providerOptions)==null?void 0:x.openai)==null?void 0:E.imageDetail}}}else if(m.mediaType.startsWith("audio/")){if(m.data instanceof URL)throw new Ln({functionality:"audio file parts with URLs"});switch(m.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Er(m.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Er(m.data),format:"mp3"}};default:throw new Ln({functionality:`audio content parts with media type ${m.mediaType}`})}}else if(m.mediaType==="application/pdf"){if(m.data instanceof URL)throw new Ln({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof m.data=="string"&&m.data.startsWith("file-")?{file_id:m.data}:{filename:(A=m.filename)!=null?A:`part-${v}.pdf`,file_data:`data:application/pdf;base64,${Er(m.data)}`}}}else throw new Ln({functionality:`file part media type ${m.mediaType}`})}})});break}case"assistant":{let m="";const v=[];for(const x of g)switch(x.type){case"text":{m+=x.text;break}case"tool-call":{v.push({id:x.toolCallId,type:"function",function:{name:x.toolName,arguments:JSON.stringify(x.input)}});break}}c.push({role:"assistant",content:m,tool_calls:v.length>0?v:void 0});break}case"tool":{for(const m of g){if(m.type==="tool-approval-response")continue;const v=m.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:m.toolCallId,content:x})}break}default:{const m=f;throw new Error(`Unsupported role: ${m}`)}}return{messages:c,warnings:u}}function uo({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Ca(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 im=Pe(()=>Me(T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({message:T({role:K("assistant").nullish(),content:_().nullish(),tool_calls:fe(T({id:_().nullish(),type:K("function"),function:T({name:_(),arguments:_()})})).nullish(),annotations:fe(T({type:K("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:_(),title:_()})})).nullish()}),index:q(),logprobs:T({content:fe(T({token:_(),logprob:q(),top_logprobs:fe(T({token:_(),logprob:q()}))})).nullish()}).nullish(),finish_reason:_().nullish()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}))),om=Pe(()=>Me(Je([T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({delta:T({role:Re(["assistant"]).nullish(),content:_().nullish(),tool_calls:fe(T({index:q(),id:_().nullish(),type:K("function").nullish(),function:T({name:_().nullish(),arguments:_().nullish()})})).nullish(),annotations:fe(T({type:K("url_citation"),url_citation:T({start_index:q(),end_index:q(),url:_(),title:_()})})).nullish()}).nullish(),logprobs:T({content:fe(T({token:_(),logprob:q(),top_logprobs:fe(T({token:_(),logprob:q()}))})).nullish()}).nullish(),finish_reason:_().nullish(),index:q()})),usage:T({prompt_tokens:q().nullish(),completion_tokens:q().nullish(),total_tokens:q().nullish(),prompt_tokens_details:T({cached_tokens:q().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:q().nullish(),accepted_prediction_tokens:q().nullish(),rejected_prediction_tokens:q().nullish()}).nullish()}).nullish()}),jo]))),sm=Pe(()=>Me(T({logitBias:Rt(Ph(),q()).optional(),logprobs:Je([kt(),q()]).optional(),parallelToolCalls:kt().optional(),user:_().optional(),reasoningEffort:Re(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:q().optional(),store:kt().optional(),metadata:Rt(_().max(64),_().max(512)).optional(),prediction:Rt(_(),dr()).optional(),serviceTier:Re(["auto","flex","priority","default"]).optional(),strictJsonSchema:kt().optional(),textVerbosity:Re(["low","medium","high"]).optional(),promptCacheKey:_().optional(),promptCacheRetention:Re(["in_memory","24h"]).optional(),safetyIdentifier:_().optional(),systemMessageMode:Re(["system","developer","remove"]).optional(),forceReasoning:kt().optional()})));function am({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 Ln({functionality:`tool choice type: ${f}`})}}}var lm=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:g,stopSequences:m,responseFormat:v,seed:x,tools:E,toolChoice:A,providerOptions:B}){var O,R,D,P,Y;const $=[],U=(O=await Fn({provider:"openai",providerOptions:B,schema:sm}))!=null?O:{},W=ru(this.modelId),X=(R=U.forceReasoning)!=null?R:W.isReasoningModel;u!=null&&$.push({type:"unsupported",feature:"topK"});const{messages:H,warnings:z}=rm({prompt:t,systemMessageMode:(D=U.systemMessageMode)!=null?D:X?"developer":W.systemMessageMode});$.push(...z);const V=(P=U.strictJsonSchema)!=null?P:!0,M={model:this.modelId,logit_bias:U.logitBias,logprobs:U.logprobs===!0||typeof U.logprobs=="number"?!0:void 0,top_logprobs:typeof U.logprobs=="number"?U.logprobs:typeof U.logprobs=="boolean"&&U.logprobs?0:void 0,user:U.user,parallel_tool_calls:U.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:g,response_format:v?.type==="json"?v.schema!=null?{type:"json_schema",json_schema:{schema:v.schema,strict:V,name:(Y=v.name)!=null?Y:"response",description:v.description}}:{type:"json_object"}:void 0,stop:m,seed:x,verbosity:U.textVerbosity,max_completion_tokens:U.maxCompletionTokens,store:U.store,metadata:U.metadata,prediction:U.prediction,reasoning_effort:U.reasoningEffort,service_tier:U.serviceTier,prompt_cache_key:U.promptCacheKey,prompt_cache_retention:U.promptCacheRetention,safety_identifier:U.safetyIdentifier,messages:H};X?((U.reasoningEffort!=="none"||!W.supportsNonReasoningParameters)&&(M.temperature!=null&&(M.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),M.top_p!=null&&(M.top_p=void 0,$.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),M.logprobs!=null&&(M.logprobs=void 0,$.push({type:"other",message:"logprobs is not supported for reasoning models"}))),M.frequency_penalty!=null&&(M.frequency_penalty=void 0,$.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),M.presence_penalty!=null&&(M.presence_penalty=void 0,$.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),M.logit_bias!=null&&(M.logit_bias=void 0,$.push({type:"other",message:"logitBias is not supported for reasoning models"})),M.top_logprobs!=null&&(M.top_logprobs=void 0,$.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),M.max_tokens!=null&&(M.max_completion_tokens==null&&(M.max_completion_tokens=M.max_tokens),M.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&M.temperature!=null&&(M.temperature=void 0,$.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),U.serviceTier==="flex"&&!W.supportsFlexProcessing&&($.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),M.service_tier=void 0),U.serviceTier==="priority"&&!W.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"}),M.service_tier=void 0);const{tools:Ce,toolChoice:me,toolWarnings:le}=am({tools:E,toolChoice:A});return{args:{...M,tools:Ce,tool_choice:me},warnings:[...$,...le]}}async doGenerate(t){var r,o,c,u,f,g,m;const{args:v,warnings:x}=await this.getArgs(t),{responseHeaders:E,value:A,rawValue:B}=await Un({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:v,failedResponseHandler:En,successfulResponseHandler:cr(im),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=A.choices[0],R=[],D=O.message.content;D!=null&&D.length>0&&R.push({type:"text",text:D});for(const $ of(r=O.message.tool_calls)!=null?r:[])R.push({type:"tool-call",toolCallId:(o=$.id)!=null?o:Xt(),toolName:$.function.name,input:$.function.arguments});for(const $ of(c=O.message.annotations)!=null?c:[])R.push({type:"source",sourceType:"url",id:Xt(),url:$.url_citation.url,title:$.url_citation.title});const P=(u=A.usage)==null?void 0:u.completion_tokens_details;(f=A.usage)==null||f.prompt_tokens_details;const Y={openai:{}};return P?.accepted_prediction_tokens!=null&&(Y.openai.acceptedPredictionTokens=P?.accepted_prediction_tokens),P?.rejected_prediction_tokens!=null&&(Y.openai.rejectedPredictionTokens=P?.rejected_prediction_tokens),((g=O.logprobs)==null?void 0:g.content)!=null&&(Y.openai.logprobs=O.logprobs.content),{content:R,finishReason:{unified:Ca(O.finish_reason),raw:(m=O.finish_reason)!=null?m:void 0},usage:va(A.usage),request:{body:v},response:{...uo(A),headers:E,body:B},warnings:x,providerMetadata:Y}}async doStream(t){const{args:r,warnings:o}=await this.getArgs(t),c={...r,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:u,value:f}=await Un({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ho(om),abortSignal:t.abortSignal,fetch:this.config.fetch}),g=[];let m={unified:"other",raw:void 0},v,x=!1,E=!1;const A={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(B){B.enqueue({type:"stream-start",warnings:o})},transform(B,O){var R,D,P,Y,$,U,W,X,H,z,V,M,Ce,me,le,ie,re;if(t.includeRawChunks&&O.enqueue({type:"raw",rawValue:B.rawValue}),!B.success){m={unified:"error",raw:void 0},O.enqueue({type:"error",error:B.error});return}const Z=B.value;if("error"in Z){m={unified:"error",raw:void 0},O.enqueue({type:"error",error:Z.error});return}if(!x){const he=uo(Z);Object.values(he).some(Boolean)&&(x=!0,O.enqueue({type:"response-metadata",...uo(Z)}))}Z.usage!=null&&(v=Z.usage,((R=Z.usage.completion_tokens_details)==null?void 0:R.accepted_prediction_tokens)!=null&&(A.openai.acceptedPredictionTokens=(D=Z.usage.completion_tokens_details)==null?void 0:D.accepted_prediction_tokens),((P=Z.usage.completion_tokens_details)==null?void 0:P.rejected_prediction_tokens)!=null&&(A.openai.rejectedPredictionTokens=(Y=Z.usage.completion_tokens_details)==null?void 0:Y.rejected_prediction_tokens));const de=Z.choices[0];if(de?.finish_reason!=null&&(m={unified:Ca(de.finish_reason),raw:de.finish_reason}),(($=de?.logprobs)==null?void 0:$.content)!=null&&(A.openai.logprobs=de.logprobs.content),de?.delta==null)return;const ee=de.delta;if(ee.content!=null&&(E||(O.enqueue({type:"text-start",id:"0"}),E=!0),O.enqueue({type:"text-delta",id:"0",delta:ee.content})),ee.tool_calls!=null)for(const he of ee.tool_calls){const Ie=he.index;if(g[Ie]==null){if(he.type!=null&&he.type!=="function")throw new ao({data:he,message:"Expected 'function' type."});if(he.id==null)throw new ao({data:he,message:"Expected 'id' to be a string."});if(((U=he.function)==null?void 0:U.name)==null)throw new ao({data:he,message:"Expected 'function.name' to be a string."});O.enqueue({type:"tool-input-start",id:he.id,toolName:he.function.name}),g[Ie]={id:he.id,type:"function",function:{name:he.function.name,arguments:(W=he.function.arguments)!=null?W:""},hasFinished:!1};const ge=g[Ie];((X=ge.function)==null?void 0:X.name)!=null&&((H=ge.function)==null?void 0:H.arguments)!=null&&(ge.function.arguments.length>0&&O.enqueue({type:"tool-input-delta",id:ge.id,delta:ge.function.arguments}),_a(ge.function.arguments)&&(O.enqueue({type:"tool-input-end",id:ge.id}),O.enqueue({type:"tool-call",toolCallId:(z=ge.id)!=null?z:Xt(),toolName:ge.function.name,input:ge.function.arguments}),ge.hasFinished=!0));continue}const Te=g[Ie];Te.hasFinished||(((V=he.function)==null?void 0:V.arguments)!=null&&(Te.function.arguments+=(Ce=(M=he.function)==null?void 0:M.arguments)!=null?Ce:""),O.enqueue({type:"tool-input-delta",id:Te.id,delta:(me=he.function.arguments)!=null?me:""}),((le=Te.function)==null?void 0:le.name)!=null&&((ie=Te.function)==null?void 0:ie.arguments)!=null&&_a(Te.function.arguments)&&(O.enqueue({type:"tool-input-end",id:Te.id}),O.enqueue({type:"tool-call",toolCallId:(re=Te.id)!=null?re:Xt(),toolName:Te.function.name,input:Te.function.arguments}),Te.hasFinished=!0))}if(ee.annotations!=null)for(const he of ee.annotations)O.enqueue({type:"source",sourceType:"url",id:Xt(),url:he.url_citation.url,title:he.url_citation.title})},flush(B){E&&B.enqueue({type:"text-end",id:"0"}),B.enqueue({type:"finish",finishReason:m,usage:va(v),...A!=null?{providerMetadata:A}:{}})}})),request:{body:c},response:{headers:u}}}};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=(r=t.prompt_tokens)!=null?r:0,g=(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:g,reasoning:void 0},raw:t}}function cm({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
40
|
+
]`;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 ru(t,r){var o,c,u,f,m,g;const C={type:"object",additionalProperties:(o=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]}))!=null?o:r.allowedAdditionalProperties};if(((c=t.keyType)==null?void 0:c._def.typeName)===Le.ZodString&&((u=t.keyType._def.checks)!=null&&u.length)){const{type:x,...A}=nu(t.keyType._def,r);return{...C,propertyNames:A}}else{if(((f=t.keyType)==null?void 0:f._def.typeName)===Le.ZodEnum)return{...C,propertyNames:{enum:t.keyType._def.values}};if(((m=t.keyType)==null?void 0:m._def.typeName)===Le.ZodBranded&&t.keyType._def.type._def.typeName===Le.ZodString&&((g=t.keyType._def.type._def.checks)!=null&&g.length)){const{type:x,...A}=eu(t.keyType._def,r);return{...C,propertyNames:A}}}return C}function ym(t,r){if(r.mapStrategy==="record")return ru(t,r);const o=rt(t.keyType._def,{...r,currentPath:[...r.currentPath,"items","items","0"]})||fn(),c=rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items","items","1"]})||fn();return{type:"array",maxItems:125,items:{type:"array",items:[o,c],minItems:2,maxItems:2}}}function wm(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 _m(){return{not:fn()}}function vm(){return{type:"null"}}var Io={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Cm(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 bm(t,r)}var bm=(t,r)=>{const o=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((c,u)=>rt(c._def,{...r,currentPath:[...r.currentPath,"anyOf",`${u}`]})).filter(c=>!!c&&(!r.strictUnions||typeof c=="object"&&Object.keys(c).length>0));return o.length?{anyOf:o}:void 0};function Em(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=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","0"]});return o&&{anyOf:[o,{type:"null"}]}}function Am(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 Im(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 C=Tm(g),x=rt(g._def,{...r,currentPath:[...r.currentPath,"properties",m],propertyPath:[...r.currentPath,"properties",m]});x!==void 0&&(o.properties[m]=x,C||c.push(m))}c.length&&(o.required=c);const f=Sm(t,r);return f!==void 0&&(o.additionalProperties=f),o}function Sm(t,r){if(t.catchall._def.typeName!=="ZodNever")return rt(t.catchall._def,{...r,currentPath:[...r.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return r.allowedAdditionalProperties;case"strict":return r.rejectedAdditionalProperties;case"strip":return r.removeAdditionalStrategy==="strict"?r.allowedAdditionalProperties:r.rejectedAdditionalProperties}}function Tm(t){try{return t.isOptional()}catch{return!0}}var Nm=(t,r)=>{var o;if(r.currentPath.toString()===((o=r.propertyPath)==null?void 0:o.toString()))return rt(t.innerType._def,r);const c=rt(t.innerType._def,{...r,currentPath:[...r.currentPath,"anyOf","1"]});return c?{anyOf:[{not:fn()},c]}:fn()},Om=(t,r)=>{if(r.pipeStrategy==="input")return rt(t.in._def,r);if(r.pipeStrategy==="output")return rt(t.out._def,r);const o=rt(t.in._def,{...r,currentPath:[...r.currentPath,"allOf","0"]}),c=rt(t.out._def,{...r,currentPath:[...r.currentPath,"allOf",o?"1":"0"]});return{allOf:[o,c].filter(u=>u!==void 0)}};function km(t,r){return rt(t.type._def,r)}function Rm(t,r){const c={type:"array",uniqueItems:!0,items:rt(t.valueType._def,{...r,currentPath:[...r.currentPath,"items"]})};return t.minSize&&(c.minItems=t.minSize.value),t.maxSize&&(c.maxItems=t.maxSize.value),c}function Mm(t,r){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[]),additionalItems:rt(t.rest._def,{...r,currentPath:[...r.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((o,c)=>rt(o._def,{...r,currentPath:[...r.currentPath,"items",`${c}`]})).reduce((o,c)=>c===void 0?o:[...o,c],[])}}function Dm(){return{not:fn()}}function Pm(){return fn()}var Bm=(t,r)=>rt(t.innerType._def,r),Lm=(t,r,o)=>{switch(r){case Le.ZodString:return nu(t,o);case Le.ZodNumber:return Am(t);case Le.ZodObject:return Im(t,o);case Le.ZodBigInt:return sm(t);case Le.ZodBoolean:return am();case Le.ZodDate:return tu(t,o);case Le.ZodUndefined:return Dm();case Le.ZodNull:return vm();case Le.ZodArray:return om(t,o);case Le.ZodUnion:case Le.ZodDiscriminatedUnion:return Cm(t,o);case Le.ZodIntersection:return pm(t,o);case Le.ZodTuple:return Mm(t,o);case Le.ZodRecord:return ru(t,o);case Le.ZodLiteral:return mm(t);case Le.ZodEnum:return fm(t);case Le.ZodNativeEnum:return wm(t);case Le.ZodNullable:return Em(t,o);case Le.ZodOptional:return Nm(t,o);case Le.ZodMap:return ym(t,o);case Le.ZodSet:return Rm(t,o);case Le.ZodLazy:return()=>t.getter()._def;case Le.ZodPromise:return km(t,o);case Le.ZodNaN:case Le.ZodNever:return _m();case Le.ZodEffects:return dm(t,o);case Le.ZodAny:return fn();case Le.ZodUnknown:return Pm();case Le.ZodDefault:return um(t,o);case Le.ZodBranded:return eu(t,o);case Le.ZodReadonly:return Bm(t,o);case Le.ZodCatch:return lm(t,o);case Le.ZodPipeline:return Om(t,o);case Le.ZodFunction:case Le.ZodVoid:case Le.ZodSymbol:return;default:return(c=>{})()}},Fm=(t,r)=>{let o=0;for(;o<t.length&&o<r.length&&t[o]===r[o];o++);return[(t.length-o).toString(),...r.slice(o)].join("/")};function rt(t,r,o=!1){var c;const u=r.seen.get(t);if(r.override){const C=(c=r.override)==null?void 0:c.call(r,t,r,u,o);if(C!==rm)return C}if(u&&!o){const C=Um(u,r);if(C!==void 0)return C}const f={def:t,path:r.currentPath,jsonSchema:void 0};r.seen.set(t,f);const m=Lm(t,t.typeName,r),g=typeof m=="function"?rt(m(),r):m;if(g&&zm(t,r,g),r.postProcess){const C=r.postProcess(g,t,r);return f.jsonSchema=g,C}return f.jsonSchema=g,g}var Um=(t,r)=>{switch(r.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Fm(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`),fn()):r.$refStrategy==="seen"?fn():void 0}},zm=(t,r,o)=>(t.description&&(o.description=t.description),o),Vm=t=>{const r=im(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}]))}},Zm=(t,r)=>{var o;const c=Vm(r);let u=typeof r=="object"&&r.definitions?Object.entries(r.definitions).reduce((x,[A,v])=>{var P;return{...x,[A]:(P=rt(v._def,{...c,currentPath:[...c.basePath,c.definitionPath,A]},!0))!=null?P:fn()}},{}):void 0;const f=typeof r=="string"?r:r?.nameStrategy==="title"?void 0:r?.name,m=(o=rt(t._def,f===void 0?c:{...c,currentPath:[...c.basePath,c.definitionPath,f]},!1))!=null?o:fn(),g=typeof r=="object"&&r.name!==void 0&&r.nameStrategy==="title"?r.name:void 0;g!==void 0&&(m.title=g);const C=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 C.$schema="http://json-schema.org/draft-07/schema#",C},So=Symbol.for("vercel.ai.schema");function Be(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 $m(t){return typeof t=="object"&&t!==null&&So in t&&t[So]===!0&&"jsonSchema"in t&&"validate"in t}function Hm(t){return t==null?Li({properties:{},additionalProperties:!1}):$m(t)?t:"~standard"in t?t["~standard"].vendor==="zod"?Pe(t):Wm(t):t()}function Wm(t){return Li(()=>Go(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 jm(t,r){var o;const c=(o=void 0)!=null?o:!1;return Li(()=>Zm(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 Gm(t,r){var o;const c=(o=void 0)!=null?o:!1;return Li(()=>Go(If(t,{target:"draft-7",io:"input",reused:c?"ref":"inline"})),{validate:async u=>{const f=await hc(t,u);return f.success?{success:!0,value:f.data}:{success:!1,error:f.error}}})}function Xm(t){return"_zod"in t}function Pe(t,r){return Xm(t)?Gm(t):jm(t)}async function kt({value:t,schema:r,context:o}){const c=await Xo({value:t,schema:r,context:o});if(!c.success)throw Qr.wrap({value:t,cause:c.error,context:o});return c.value}async function Xo({value:t,schema:r,context:o}){const c=Hm(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 iu({text:t,schema:r}){try{const o=jo(t);return r==null?o:kt({value:o,schema:r})}catch(o){throw Oi.isInstance(o)||Qr.isInstance(o)?o:new Oi({text:t,cause:o})}}async function ou({text:t,schema:r}){try{const o=jo(t);return r==null?{success:!0,value:o,rawValue:o}:await Xo({value:o,schema:r})}catch(o){return{success:!1,error:Oi.isInstance(o)?o:new Oi({text:t,cause:o}),rawValue:void 0}}}function Aa(t){try{return jo(t),!0}catch{return!1}}function qm({stream:t,schema:r}){return t.pipeThrough(new TextDecoderStream).pipeThrough(new jl).pipeThrough(new TransformStream({async transform({data:o},c){o!=="[DONE]"&&c.enqueue(await ou({text:o,schema:r}))}}))}async function Vn({provider:t,providerOptions:r,schema:o}){if(r?.[t]==null)return;const c=await Xo({value:r[t],schema:o});if(!c.success)throw new Mc({argument:"providerOptions",message:`invalid ${t} provider options`,cause:c.error});return c.value}var Ym=()=>globalThis.fetch,Zn=async({url:t,headers:r,body:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>au({url:t,headers:{"Content-Type":"application/json",...r},body:{content:JSON.stringify(o),values:o},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),su=async({url:t,headers:r,formData:o,failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m})=>au({url:t,headers:r,body:{content:o,values:Object.fromEntries(o.entries())},failedResponseHandler:c,successfulResponseHandler:u,abortSignal:f,fetch:m}),au=async({url:t,headers:r={},body:o,successfulResponseHandler:c,failedResponseHandler:u,abortSignal:f,fetch:m=Ym()})=>{try{const g=await m(t,{method:"POST",headers:Qc(r,`ai-sdk/provider-utils/${Yp}`,Xp()),body:o.content,signal:f}),C=ii(g);if(!g.ok){let x;try{x=await u({response:g,url:t,requestBodyValues:o.values})}catch(A){throw Ao(A)||cn.isInstance(A)?A:new cn({message:"Failed to process error response",cause:A,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}throw x.value}try{return await c({response:g,url:t,requestBodyValues:o.values})}catch(x){throw x instanceof Error&&(Ao(x)||cn.isInstance(x))?x:new cn({message:"Failed to process successful response",cause:x,statusCode:g.status,url:t,responseHeaders:C,requestBodyValues:o.values})}}catch(g){throw Gp({error:g,url:t,requestBodyValues:o.values})}};function Km({id:t,inputSchema:r}){return({execute:o,outputSchema:c,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:C,...x})=>({type:"provider",id:t,args:x,inputSchema:r,outputSchema:c,execute:o,needsApproval:u,toModelOutput:f,onInputStart:m,onInputDelta:g,onInputAvailable:C})}function Dn({id:t,inputSchema:r,outputSchema:o,supportsDeferredResults:c}){return({execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:C,onInputAvailable:x,...A})=>({type:"provider",id:t,args:A,inputSchema:r,outputSchema:o,execute:u,needsApproval:f,toModelOutput:m,onInputStart:g,onInputDelta:C,onInputAvailable:x,supportsDeferredResults:c})}var Jm=({errorSchema:t,errorToMessage:r,isRetryable:o})=>async({response:c,url:u,requestBodyValues:f})=>{const m=await c.text(),g=ii(c);if(m.trim()==="")return{responseHeaders:g,value:new cn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})};try{const C=await iu({text:m,schema:t});return{responseHeaders:g,value:new cn({message:r(C),url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,data:C,isRetryable:o?.(c,C)})}}catch{return{responseHeaders:g,value:new cn({message:c.statusText,url:u,requestBodyValues:f,statusCode:c.status,responseHeaders:g,responseBody:m,isRetryable:o?.(c)})}}},qo=t=>async({response:r})=>{const o=ii(r);if(r.body==null)throw new bp({});return{responseHeaders:o,value:qm({stream:r.body,schema:t})}},hr=t=>async({response:r,url:o,requestBodyValues:c})=>{const u=await r.text(),f=await ou({text:u,schema:t}),m=ii(r);if(!f.success)throw new cn({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}},Qm=()=>async({response:t,url:r,requestBodyValues:o})=>{const c=ii(t);if(!t.body)throw new cn({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 cn({message:"Failed to read response as array buffer",url:r,requestBodyValues:o,statusCode:t.status,responseHeaders:c,responseBody:void 0,cause:u})}};function eg(t){return t?.replace(/\/$/,"")}var Yo=T({error:T({message:w(),type:w().nullish(),param:mr().nullish(),code:Qe([w(),j()]).nullish()})}),An=Jm({errorSchema:Yo,errorToMessage:t=>t.error.message});function lu(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");return{supportsFlexProcessing:r,supportsPriorityProcessing:o,isReasoningModel:c,systemMessageMode:c?"developer":"system",supportsNonReasoningParameters:u}}function Ia(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,C=(o=t.completion_tokens)!=null?o:0,x=(u=(c=t.prompt_tokens_details)==null?void 0:c.cached_tokens)!=null?u:0,A=(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:C,text:C-A,reasoning:A},raw:t}}function tg({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,C)=>{var x,A,v;switch(g.type){case"text":return{type:"text",text:g.text};case"file":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,${Tr(g.data)}`,detail:(A=(x=g.providerOptions)==null?void 0:x.openai)==null?void 0:A.imageDetail}}}else if(g.mediaType.startsWith("audio/")){if(g.data instanceof URL)throw new zn({functionality:"audio file parts with URLs"});switch(g.mediaType){case"audio/wav":return{type:"input_audio",input_audio:{data:Tr(g.data),format:"wav"}};case"audio/mp3":case"audio/mpeg":return{type:"input_audio",input_audio:{data:Tr(g.data),format:"mp3"}};default:throw new zn({functionality:`audio content parts with media type ${g.mediaType}`})}}else if(g.mediaType==="application/pdf"){if(g.data instanceof URL)throw new zn({functionality:"PDF file parts with URLs"});return{type:"file",file:typeof g.data=="string"&&g.data.startsWith("file-")?{file_id:g.data}:{filename:(v=g.filename)!=null?v:`part-${C}.pdf`,file_data:`data:application/pdf;base64,${Tr(g.data)}`}}}else throw new zn({functionality:`file part media type ${g.mediaType}`})}})});break}case"assistant":{let g="";const C=[];for(const x of m)switch(x.type){case"text":{g+=x.text;break}case"tool-call":{C.push({id:x.toolCallId,type:"function",function:{name:x.toolName,arguments:JSON.stringify(x.input)}});break}}c.push({role:"assistant",content:g,tool_calls:C.length>0?C:void 0});break}case"tool":{for(const g of m){if(g.type==="tool-approval-response")continue;const C=g.output;let x;switch(C.type){case"text":case"error-text":x=C.value;break;case"execution-denied":x=(o=C.reason)!=null?o:"Tool execution denied.";break;case"content":case"json":case"error-json":x=JSON.stringify(C.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 uo({id:t,model:r,created:o}){return{id:t??void 0,modelId:r??void 0,timestamp:o?new Date(o*1e3):void 0}}function Sa(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 ng=Be(()=>Pe(T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({message:T({role:X("assistant").nullish(),content:w().nullish(),tool_calls:ue(T({id:w().nullish(),type:X("function"),function:T({name:w(),arguments:w()})})).nullish(),annotations:ue(T({type:X("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}),index:j(),logprobs:T({content:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}))),rg=Be(()=>Pe(Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({delta:T({role:Se(["assistant"]).nullish(),content:w().nullish(),tool_calls:ue(T({index:j(),id:w().nullish(),type:X("function").nullish(),function:T({name:w().nullish(),arguments:w().nullish()})})).nullish(),annotations:ue(T({type:X("url_citation"),url_citation:T({start_index:j(),end_index:j(),url:w(),title:w()})})).nullish()}).nullish(),logprobs:T({content:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}).nullish(),finish_reason:w().nullish(),index:j()})),usage:T({prompt_tokens:j().nullish(),completion_tokens:j().nullish(),total_tokens:j().nullish(),prompt_tokens_details:T({cached_tokens:j().nullish()}).nullish(),completion_tokens_details:T({reasoning_tokens:j().nullish(),accepted_prediction_tokens:j().nullish(),rejected_prediction_tokens:j().nullish()}).nullish()}).nullish()}),Yo]))),ig=Be(()=>Pe(T({logitBias:ht(Ph(),j()).optional(),logprobs:Qe([Rt(),j()]).optional(),parallelToolCalls:Rt().optional(),user:w().optional(),reasoningEffort:Se(["none","minimal","low","medium","high","xhigh"]).optional(),maxCompletionTokens:j().optional(),store:Rt().optional(),metadata:ht(w().max(64),w().max(512)).optional(),prediction:ht(w(),mr()).optional(),serviceTier:Se(["auto","flex","priority","default"]).optional(),strictJsonSchema:Rt().optional(),textVerbosity:Se(["low","medium","high"]).optional(),promptCacheKey:w().optional(),promptCacheRetention:Se(["in_memory","24h"]).optional(),safetyIdentifier:w().optional(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:Rt().optional()})));function og({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 zn({functionality:`tool choice type: ${f}`})}}}var sg=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:C,seed:x,tools:A,toolChoice:v,providerOptions:P}){var O,M,D,B,G;const Z=[],U=(O=await Vn({provider:"openai",providerOptions:P,schema:ig}))!=null?O:{},Q=lu(this.modelId),K=(M=U.forceReasoning)!=null?M:Q.isReasoningModel;u!=null&&Z.push({type:"unsupported",feature:"topK"});const{messages:V,warnings:z}=tg({prompt:t,systemMessageMode:(D=U.systemMessageMode)!=null?D:K?"developer":Q.systemMessageMode});Z.push(...z);const te=(B=U.strictJsonSchema)!=null?B:!0,S={model:this.modelId,logit_bias:U.logitBias,logprobs:U.logprobs===!0||typeof U.logprobs=="number"?!0:void 0,top_logprobs:typeof U.logprobs=="number"?U.logprobs:typeof U.logprobs=="boolean"&&U.logprobs?0:void 0,user:U.user,parallel_tool_calls:U.parallelToolCalls,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,response_format:C?.type==="json"?C.schema!=null?{type:"json_schema",json_schema:{schema:C.schema,strict:te,name:(G=C.name)!=null?G:"response",description:C.description}}:{type:"json_object"}:void 0,stop:g,seed:x,verbosity:U.textVerbosity,max_completion_tokens:U.maxCompletionTokens,store:U.store,metadata:U.metadata,prediction:U.prediction,reasoning_effort:U.reasoningEffort,service_tier:U.serviceTier,prompt_cache_key:U.promptCacheKey,prompt_cache_retention:U.promptCacheRetention,safety_identifier:U.safetyIdentifier,messages:V};K?((U.reasoningEffort!=="none"||!Q.supportsNonReasoningParameters)&&(S.temperature!=null&&(S.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,Z.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"})),S.logprobs!=null&&(S.logprobs=void 0,Z.push({type:"other",message:"logprobs is not supported for reasoning models"}))),S.frequency_penalty!=null&&(S.frequency_penalty=void 0,Z.push({type:"unsupported",feature:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),S.presence_penalty!=null&&(S.presence_penalty=void 0,Z.push({type:"unsupported",feature:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),S.logit_bias!=null&&(S.logit_bias=void 0,Z.push({type:"other",message:"logitBias is not supported for reasoning models"})),S.top_logprobs!=null&&(S.top_logprobs=void 0,Z.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),S.max_tokens!=null&&(S.max_completion_tokens==null&&(S.max_completion_tokens=S.max_tokens),S.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&S.temperature!=null&&(S.temperature=void 0,Z.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),U.serviceTier==="flex"&&!Q.supportsFlexProcessing&&(Z.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),S.service_tier=void 0),U.serviceTier==="priority"&&!Q.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"}),S.service_tier=void 0);const{tools:Te,toolChoice:ye,toolWarnings:re}=og({tools:A,toolChoice:v});return{args:{...S,tools:Te,tool_choice:ye},warnings:[...Z,...re]}}async doGenerate(t){var r,o,c,u,f,m,g;const{args:C,warnings:x}=await this.getArgs(t),{responseHeaders:A,value:v,rawValue:P}=await Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:C,failedResponseHandler:An,successfulResponseHandler:hr(ng),abortSignal:t.abortSignal,fetch:this.config.fetch}),O=v.choices[0],M=[],D=O.message.content;D!=null&&D.length>0&&M.push({type:"text",text:D});for(const Z of(r=O.message.tool_calls)!=null?r:[])M.push({type:"tool-call",toolCallId:(o=Z.id)!=null?o:Kt(),toolName:Z.function.name,input:Z.function.arguments});for(const Z of(c=O.message.annotations)!=null?c:[])M.push({type:"source",sourceType:"url",id:Kt(),url:Z.url_citation.url,title:Z.url_citation.title});const B=(u=v.usage)==null?void 0:u.completion_tokens_details;(f=v.usage)==null||f.prompt_tokens_details;const G={openai:{}};return B?.accepted_prediction_tokens!=null&&(G.openai.acceptedPredictionTokens=B?.accepted_prediction_tokens),B?.rejected_prediction_tokens!=null&&(G.openai.rejectedPredictionTokens=B?.rejected_prediction_tokens),((m=O.logprobs)==null?void 0:m.content)!=null&&(G.openai.logprobs=O.logprobs.content),{content:M,finishReason:{unified:Sa(O.finish_reason),raw:(g=O.finish_reason)!=null?g:void 0},usage:Ia(v.usage),request:{body:C},response:{...uo(v),headers:A,body:P},warnings:x,providerMetadata:G}}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 Zn({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:An,successfulResponseHandler:qo(rg),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=[];let g={unified:"other",raw:void 0},C,x=!1,A=!1;const v={openai:{}};return{stream:f.pipeThrough(new TransformStream({start(P){P.enqueue({type:"stream-start",warnings:o})},transform(P,O){var M,D,B,G,Z,U,Q,K,V,z,te,S,Te,ye,re,xe,Me;if(t.includeRawChunks&&O.enqueue({type:"raw",rawValue:P.rawValue}),!P.success){g={unified:"error",raw:void 0},O.enqueue({type:"error",error:P.error});return}const $=P.value;if("error"in $){g={unified:"error",raw:void 0},O.enqueue({type:"error",error:$.error});return}if(!x){const J=uo($);Object.values(J).some(Boolean)&&(x=!0,O.enqueue({type:"response-metadata",...uo($)}))}$.usage!=null&&(C=$.usage,((M=$.usage.completion_tokens_details)==null?void 0:M.accepted_prediction_tokens)!=null&&(v.openai.acceptedPredictionTokens=(D=$.usage.completion_tokens_details)==null?void 0:D.accepted_prediction_tokens),((B=$.usage.completion_tokens_details)==null?void 0:B.rejected_prediction_tokens)!=null&&(v.openai.rejectedPredictionTokens=(G=$.usage.completion_tokens_details)==null?void 0:G.rejected_prediction_tokens));const ge=$.choices[0];if(ge?.finish_reason!=null&&(g={unified:Sa(ge.finish_reason),raw:ge.finish_reason}),((Z=ge?.logprobs)==null?void 0:Z.content)!=null&&(v.openai.logprobs=ge.logprobs.content),ge?.delta==null)return;const ne=ge.delta;if(ne.content!=null&&(A||(O.enqueue({type:"text-start",id:"0"}),A=!0),O.enqueue({type:"text-delta",id:"0",delta:ne.content})),ne.tool_calls!=null)for(const J of ne.tool_calls){const me=J.index;if(m[me]==null){if(J.type!=null&&J.type!=="function")throw new ao({data:J,message:"Expected 'function' type."});if(J.id==null)throw new ao({data:J,message:"Expected 'id' to be a string."});if(((U=J.function)==null?void 0:U.name)==null)throw new ao({data:J,message:"Expected 'function.name' to be a string."});O.enqueue({type:"tool-input-start",id:J.id,toolName:J.function.name}),m[me]={id:J.id,type:"function",function:{name:J.function.name,arguments:(Q=J.function.arguments)!=null?Q:""},hasFinished:!1};const ie=m[me];((K=ie.function)==null?void 0:K.name)!=null&&((V=ie.function)==null?void 0:V.arguments)!=null&&(ie.function.arguments.length>0&&O.enqueue({type:"tool-input-delta",id:ie.id,delta:ie.function.arguments}),Aa(ie.function.arguments)&&(O.enqueue({type:"tool-input-end",id:ie.id}),O.enqueue({type:"tool-call",toolCallId:(z=ie.id)!=null?z:Kt(),toolName:ie.function.name,input:ie.function.arguments}),ie.hasFinished=!0));continue}const fe=m[me];fe.hasFinished||(((te=J.function)==null?void 0:te.arguments)!=null&&(fe.function.arguments+=(Te=(S=J.function)==null?void 0:S.arguments)!=null?Te:""),O.enqueue({type:"tool-input-delta",id:fe.id,delta:(ye=J.function.arguments)!=null?ye:""}),((re=fe.function)==null?void 0:re.name)!=null&&((xe=fe.function)==null?void 0:xe.arguments)!=null&&Aa(fe.function.arguments)&&(O.enqueue({type:"tool-input-end",id:fe.id}),O.enqueue({type:"tool-call",toolCallId:(Me=fe.id)!=null?Me:Kt(),toolName:fe.function.name,input:fe.function.arguments}),fe.hasFinished=!0))}if(ne.annotations!=null)for(const J of ne.annotations)O.enqueue({type:"source",sourceType:"url",id:Kt(),url:J.url_citation.url,title:J.url_citation.title})},flush(P){A&&P.enqueue({type:"text-end",id:"0"}),P.enqueue({type:"finish",finishReason:g,usage:Ia(C),...v!=null?{providerMetadata:v}:{}})}})),request:{body:c},response:{headers:u}}}};function Ta(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 ag({prompt:t,user:r="user",assistant:o="assistant"}){let c="";t[0].role==="system"&&(c+=`${t[0].content}
|
|
41
41
|
|
|
42
|
-
`,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Ip({message:"Unexpected system message in prompt: ${content}",prompt:t});case"user":{const
|
|
43
|
-
${
|
|
42
|
+
`,t=t.slice(1));for(const{role:u,content:f}of t)switch(u){case"system":throw new Ip({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}:
|
|
43
|
+
${m}
|
|
44
44
|
|
|
45
|
-
`;break}case"assistant":{const
|
|
46
|
-
${
|
|
45
|
+
`;break}case"assistant":{const m=f.map(g=>{switch(g.type){case"text":return g.text;case"tool-call":throw new zn({functionality:"tool-call messages"})}}).join("");c+=`${o}:
|
|
46
|
+
${m}
|
|
47
47
|
|
|
48
|
-
`;break}case"tool":throw new
|
|
48
|
+
`;break}case"tool":throw new zn({functionality:"tool messages"});default:{const m=u;throw new Error(`Unsupported role: ${m}`)}}return c+=`${o}:
|
|
49
49
|
`,{prompt:c,stopSequences:[`
|
|
50
|
-
${r}:`]}}function Ea({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 Aa(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 um=Pe(()=>Me(T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({text:_(),finish_reason:_(),logprobs:T({tokens:fe(_()),token_logprobs:fe(q()),top_logprobs:fe(Rt(_(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}))),dm=Pe(()=>Me(Je([T({id:_().nullish(),created:q().nullish(),model:_().nullish(),choices:fe(T({text:_(),finish_reason:_().nullish(),index:q(),logprobs:T({tokens:fe(_()),token_logprobs:fe(q()),top_logprobs:fe(Rt(_(),q())).nullish()}).nullish()})),usage:T({prompt_tokens:q(),completion_tokens:q(),total_tokens:q()}).nullish()}),jo]))),Ia=Pe(()=>Me(T({echo:kt().optional(),logitBias:Rt(_(),q()).optional(),suffix:_().optional(),user:_().optional(),logprobs:Je([kt(),q()]).optional()}))),fm=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:g,stopSequences:m,responseFormat:v,tools:x,toolChoice:E,seed:A,providerOptions:B}){const O=[],R={...await Fn({provider:"openai",providerOptions:B,schema:Ia}),...await Fn({provider:this.providerOptionsName,providerOptions:B,schema:Ia})};u!=null&&O.push({type:"unsupported",feature:"topK"}),x?.length&&O.push({type:"unsupported",feature:"tools"}),E!=null&&O.push({type:"unsupported",feature:"toolChoice"}),v!=null&&v.type!=="text"&&O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:D,stopSequences:P}=cm({prompt:t}),Y=[...P??[],...m??[]];return{args:{model:this.modelId,echo:R.echo,logit_bias:R.logitBias,logprobs:R?.logprobs===!0?0:R?.logprobs===!1?void 0:R?.logprobs,suffix:R.suffix,user:R.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:g,seed:A,prompt:D,stop:Y.length>0?Y:void 0},warnings:O}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:g}=await Un({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:o,failedResponseHandler:En,successfulResponseHandler:cr(um),abortSignal:t.abortSignal,fetch:this.config.fetch}),m=f.choices[0],v={openai:{}};return m.logprobs!=null&&(v.openai.logprobs=m.logprobs),{content:[{type:"text",text:m.text}],usage:ba(f.usage),finishReason:{unified:Aa(m.finish_reason),raw:(r=m.finish_reason)!=null?r:void 0},request:{body:o},response:{...Ea(f),headers:u,body:g},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 Un({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:c,failedResponseHandler:En,successfulResponseHandler:Ho(dm),abortSignal:t.abortSignal,fetch:this.config.fetch});let g={unified:"other",raw:void 0};const m={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){g={unified:"error",raw:void 0},A.enqueue({type:"error",error:E.error});return}const B=E.value;if("error"in B){g={unified:"error",raw:void 0},A.enqueue({type:"error",error:B.error});return}x&&(x=!1,A.enqueue({type:"response-metadata",...Ea(B)}),A.enqueue({type:"text-start",id:"0"})),B.usage!=null&&(v=B.usage);const O=B.choices[0];O?.finish_reason!=null&&(g={unified:Aa(O.finish_reason),raw:O.finish_reason}),O?.logprobs!=null&&(m.openai.logprobs=O.logprobs),O?.text!=null&&O.text.length>0&&A.enqueue({type:"text-delta",id:"0",delta:O.text})},flush(E){x||E.enqueue({type:"text-end",id:"0"}),E.enqueue({type:"finish",finishReason:g,providerMetadata:m,usage:ba(v)})}})),request:{body:c},response:{headers:u}}}},hm=Pe(()=>Me(T({dimensions:q().optional(),user:_().optional()}))),pm=Pe(()=>Me(T({data:fe(T({embedding:fe(q())})),usage:T({prompt_tokens:q()}).nullish()}))),gm=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 kp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await Fn({provider:"openai",providerOptions:c,schema:hm}))!=null?u:{},{responseHeaders:g,value:m,rawValue:v}=await Un({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:cr(pm),abortSignal:o,fetch:this.config.fetch});return{warnings:[],embeddings:m.data.map(x=>x.embedding),usage:m.usage?{tokens:m.usage.prompt_tokens}:void 0,response:{headers:g,body:v}}}},Sa=Pe(()=>Me(T({created:q().nullish(),data:fe(T({b64_json:_(),revised_prompt:_().nullish()})),background:_().nullish(),output_format:_().nullish(),size:_().nullish(),quality:_().nullish(),usage:T({input_tokens:q().nullish(),output_tokens:q().nullish(),total_tokens:q().nullish(),input_tokens_details:T({image_tokens:q().nullish(),text_tokens:q().nullish()}).nullish()}).nullish()}))),mm={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},xm=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function wm(t){return xm.some(r=>t.startsWith(r))}var ym=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=mm[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:g,providerOptions:m,headers:v,abortSignal:x}){var E,A,B,O,R,D,P,Y,$,U,W;const X=[];f!=null&&X.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),g!=null&&X.push({type:"unsupported",feature:"seed"});const H=(B=(A=(E=this.config._internal)==null?void 0:E.currentDate)==null?void 0:A.call(E))!=null?B:new Date;if(r!=null){const{value:M,responseHeaders:Ce}=await tu({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:bn(this.config.headers(),v),formData:Up({model:this.modelId,prompt:t,image:await Promise.all(r.map(me=>me.type==="file"?new Blob([me.data instanceof Uint8Array?new Blob([me.data],{type:me.mediaType}):new Blob([Vo(me.data)],{type:me.mediaType})],{type:me.mediaType}):Xc(me.url))),mask:o!=null?await _m(o):void 0,n:c,size:u,...(O=m.openai)!=null?O:{}}),failedResponseHandler:En,successfulResponseHandler:cr(Sa),abortSignal:x,fetch:this.config.fetch});return{images:M.data.map(me=>me.b64_json),warnings:X,usage:M.usage!=null?{inputTokens:(R=M.usage.input_tokens)!=null?R:void 0,outputTokens:(D=M.usage.output_tokens)!=null?D:void 0,totalTokens:(P=M.usage.total_tokens)!=null?P:void 0}:void 0,response:{timestamp:H,modelId:this.modelId,headers:Ce},providerMetadata:{openai:{images:M.data.map((me,le)=>{var ie,re,Z,de,ee,he;return{...me.revised_prompt?{revisedPrompt:me.revised_prompt}:{},created:(ie=M.created)!=null?ie:void 0,size:(re=M.size)!=null?re:void 0,quality:(Z=M.quality)!=null?Z:void 0,background:(de=M.background)!=null?de:void 0,outputFormat:(ee=M.output_format)!=null?ee:void 0,...Ta((he=M.usage)==null?void 0:he.input_tokens_details,le,M.data.length)}})}}}}const{value:z,responseHeaders:V}=await Un({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:u,...(Y=m.openai)!=null?Y:{},...wm(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:En,successfulResponseHandler:cr(Sa),abortSignal:x,fetch:this.config.fetch});return{images:z.data.map(M=>M.b64_json),warnings:X,usage:z.usage!=null?{inputTokens:($=z.usage.input_tokens)!=null?$:void 0,outputTokens:(U=z.usage.output_tokens)!=null?U:void 0,totalTokens:(W=z.usage.total_tokens)!=null?W:void 0}:void 0,response:{timestamp:H,modelId:this.modelId,headers:V},providerMetadata:{openai:{images:z.data.map((M,Ce)=>{var me,le,ie,re,Z,de;return{...M.revised_prompt?{revisedPrompt:M.revised_prompt}:{},created:(me=z.created)!=null?me:void 0,size:(le=z.size)!=null?le:void 0,quality:(ie=z.quality)!=null?ie:void 0,background:(re=z.background)!=null?re:void 0,outputFormat:(Z=z.output_format)!=null?Z:void 0,...Ta((de=z.usage)==null?void 0:de.input_tokens_details,Ce,z.data.length)}})}}}}};function Ta(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 _m(t){if(!t)return;if(t.type==="url")return Xc(t.url);const r=t.data instanceof Uint8Array?t.data:Vo(t.data);return new Blob([r],{type:t.mediaType})}var iu=Pe(()=>Me(T({callId:_(),operation:at("type",[T({type:K("create_file"),path:_(),diff:_()}),T({type:K("delete_file"),path:_()}),T({type:K("update_file"),path:_(),diff:_()})])}))),ou=Pe(()=>Me(T({status:Re(["completed","failed"]),output:_().optional()}))),vm=zn({id:"openai.apply_patch",inputSchema:iu,outputSchema:ou}),Cm=vm,bm=Pe(()=>Me(T({code:_().nullish(),containerId:_()}))),Em=Pe(()=>Me(T({outputs:fe(at("type",[T({type:K("logs"),logs:_()}),T({type:K("image"),url:_()})])).nullish()}))),Am=Pe(()=>Me(T({container:Je([_(),T({fileIds:fe(_()).optional()})]).optional()}))),Im=zn({id:"openai.code_interpreter",inputSchema:bm,outputSchema:Em}),Sm=(t={})=>Im(t),Tm=Pe(()=>Me(T({name:_(),description:_().optional(),format:Je([T({type:K("grammar"),syntax:Re(["regex","lark"]),definition:_()}),T({type:K("text")})]).optional()}))),Nm=Pe(()=>Me(_())),Om=Qg({id:"openai.custom",inputSchema:Nm}),km=t=>Om(t),su=T({key:_(),type:Re(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Je([_(),q(),kt(),fe(_())])}),au=T({type:Re(["and","or"]),filters:fe(Je([su,pc(()=>au)]))}),Rm=Pe(()=>Me(T({vectorStoreIds:fe(_()),maxNumResults:q().optional(),ranking:T({ranker:_().optional(),scoreThreshold:q().optional()}).optional(),filters:Je([su,au]).optional()}))),Mm=Pe(()=>Me(T({queries:fe(_()),results:fe(T({attributes:Rt(_(),qr()),fileId:_(),filename:_(),score:q(),text:_()})).nullable()}))),Dm=zn({id:"openai.file_search",inputSchema:T({}),outputSchema:Mm}),Pm=Pe(()=>Me(T({background:Re(["auto","opaque","transparent"]).optional(),inputFidelity:Re(["low","high"]).optional(),inputImageMask:T({fileId:_().optional(),imageUrl:_().optional()}).optional(),model:_().optional(),moderation:Re(["auto"]).optional(),outputCompression:q().int().min(0).max(100).optional(),outputFormat:Re(["png","jpeg","webp"]).optional(),partialImages:q().int().min(0).max(3).optional(),quality:Re(["auto","low","medium","high"]).optional(),size:Re(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Bm=Pe(()=>Me(T({}))),Lm=Pe(()=>Me(T({result:_()}))),Fm=zn({id:"openai.image_generation",inputSchema:Bm,outputSchema:Lm}),Um=(t={})=>Fm(t),lu=Pe(()=>Me(T({action:T({type:K("exec"),command:fe(_()),timeoutMs:q().optional(),user:_().optional(),workingDirectory:_().optional(),env:Rt(_(),_()).optional()})}))),cu=Pe(()=>Me(T({output:_()}))),zm=zn({id:"openai.local_shell",inputSchema:lu,outputSchema:cu}),uu=Pe(()=>Me(T({action:T({commands:fe(_()),timeoutMs:q().optional(),maxOutputLength:q().optional()})}))),So=Pe(()=>Me(T({output:fe(T({stdout:_(),stderr:_(),outcome:at("type",[T({type:K("timeout")}),T({type:K("exit"),exitCode:q()})])}))}))),Vm=fe(at("type",[T({type:K("skillReference"),skillId:_(),version:_().optional()}),T({type:K("inline"),name:_(),description:_(),source:T({type:K("base64"),mediaType:K("application/zip"),data:_()})})])).optional(),Zm=Pe(()=>Me(T({environment:Je([T({type:K("containerAuto"),fileIds:fe(_()).optional(),memoryLimit:Re(["1g","4g","16g","64g"]).optional(),networkPolicy:at("type",[T({type:K("disabled")}),T({type:K("allowlist"),allowedDomains:fe(_()),domainSecrets:fe(T({domain:_(),name:_(),value:_()})).optional()})]).optional(),skills:Vm}),T({type:K("containerReference"),containerId:_()}),T({type:K("local").optional(),skills:fe(T({name:_(),description:_(),path:_()})).optional()})]).optional()}))),$m=zn({id:"openai.shell",inputSchema:uu,outputSchema:So}),Wm=Pe(()=>Me(T({externalWebAccess:kt().optional(),filters:T({allowedDomains:fe(_()).optional()}).optional(),searchContextSize:Re(["low","medium","high"]).optional(),userLocation:T({type:K("approximate"),country:_().optional(),city:_().optional(),region:_().optional(),timezone:_().optional()}).optional()}))),Hm=Pe(()=>Me(T({}))),jm=Pe(()=>Me(T({action:at("type",[T({type:K("search"),query:_().optional()}),T({type:K("openPage"),url:_().nullish()}),T({type:K("findInPage"),url:_().nullish(),pattern:_().nullish()})]).optional(),sources:fe(at("type",[T({type:K("url"),url:_()}),T({type:K("api"),name:_()})])).optional()}))),Gm=zn({id:"openai.web_search",inputSchema:Hm,outputSchema:jm}),Xm=(t={})=>Gm(t),qm=Pe(()=>Me(T({searchContextSize:Re(["low","medium","high"]).optional(),userLocation:T({type:K("approximate"),country:_().optional(),city:_().optional(),region:_().optional(),timezone:_().optional()}).optional()}))),Ym=Pe(()=>Me(T({}))),Km=Pe(()=>Me(T({action:at("type",[T({type:K("search"),query:_().optional()}),T({type:K("openPage"),url:_().nullish()}),T({type:K("findInPage"),url:_().nullish(),pattern:_().nullish()})]).optional()}))),Jm=zn({id:"openai.web_search_preview",inputSchema:Ym,outputSchema:Km}),To=pc(()=>Je([_(),q(),kt(),oh(),fe(To),Rt(_(),To)])),Qm=Pe(()=>Me(T({serverLabel:_(),allowedTools:Je([fe(_()),T({readOnly:kt().optional(),toolNames:fe(_()).optional()})]).optional(),authorization:_().optional(),connectorId:_().optional(),headers:Rt(_(),_()).optional(),requireApproval:Je([Re(["always","never"]),T({never:T({toolNames:fe(_()).optional()}).optional()})]).optional(),serverDescription:_().optional(),serverUrl:_().optional()}).refine(t=>t.serverUrl!=null||t.connectorId!=null,"One of serverUrl or connectorId must be provided."))),e2=Pe(()=>Me(T({}))),t2=Pe(()=>Me(T({type:K("call"),serverLabel:_(),name:_(),arguments:_(),output:_().nullish(),error:Je([_(),To]).optional()}))),n2=zn({id:"openai.mcp",inputSchema:e2,outputSchema:t2}),r2=t=>n2(t),i2={applyPatch:Cm,customTool:km,codeInterpreter:Sm,fileSearch:Dm,imageGeneration:Um,localShell:zm,shell:$m,webSearchPreview:Jm,webSearch:Xm,mcp:r2};function Na(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,g=t.output_tokens,m=(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-m,cacheRead:m,cacheWrite:void 0},outputTokens:{total:g,text:g-v,reasoning:v},raw:t}}function Oa(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function o2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,store:f,hasConversation:g=!1,hasLocalShellTool:m=!1,hasShellTool:v=!1,hasApplyPatchTool:x=!1,customProviderToolNames:E}){var A,B,O,R,D,P,Y,$,U,W,X,H,z;const V=[],M=[],Ce=new Set;for(const{role:me,content:le}of t)switch(me){case"system":{switch(o){case"system":{V.push({role:"system",content:le});break}case"developer":{V.push({role:"developer",content:le});break}case"remove":{M.push({type:"other",message:"system messages are removed for this model"});break}default:{const ie=o;throw new Error(`Unsupported system message mode: ${ie}`)}}break}case"user":{V.push({role:"user",content:le.map((ie,re)=>{var Z,de,ee;switch(ie.type){case"text":return{type:"input_text",text:ie.text};case"file":if(ie.mediaType.startsWith("image/")){const he=ie.mediaType==="image/*"?"image/jpeg":ie.mediaType;return{type:"input_image",...ie.data instanceof URL?{image_url:ie.data.toString()}:typeof ie.data=="string"&&Oa(ie.data,u)?{file_id:ie.data}:{image_url:`data:${he};base64,${Er(ie.data)}`},detail:(de=(Z=ie.providerOptions)==null?void 0:Z[c])==null?void 0:de.imageDetail}}else{if(ie.mediaType==="application/pdf")return ie.data instanceof URL?{type:"input_file",file_url:ie.data.toString()}:{type:"input_file",...typeof ie.data=="string"&&Oa(ie.data,u)?{file_id:ie.data}:{filename:(ee=ie.filename)!=null?ee:`part-${re}.pdf`,file_data:`data:application/pdf;base64,${Er(ie.data)}`}};throw new Ln({functionality:`file part media type ${ie.mediaType}`})}}})});break}case"assistant":{const ie={};for(const re of le)switch(re.type){case"text":{const Z=(A=re.providerOptions)==null?void 0:A[c],de=Z?.itemId,ee=Z?.phase;if(g&&de!=null)break;if(f&&de!=null){V.push({type:"item_reference",id:de});break}V.push({role:"assistant",content:[{type:"output_text",text:re.text}],id:de,...ee!=null&&{phase:ee}});break}case"tool-call":{const Z=(P=(O=(B=re.providerOptions)==null?void 0:B[c])==null?void 0:O.itemId)!=null?P:(D=(R=re.providerMetadata)==null?void 0:R[c])==null?void 0:D.itemId;if(g&&Z!=null)break;if(re.providerExecuted){f&&Z!=null&&V.push({type:"item_reference",id:Z});break}if(f&&Z!=null){V.push({type:"item_reference",id:Z});break}const de=r.toProviderToolName(re.toolName);if(m&&de==="local_shell"){const ee=await Wt({value:re.input,schema:lu});V.push({type:"local_shell_call",call_id:re.toolCallId,id:Z,action:{type:"exec",command:ee.action.command,timeout_ms:ee.action.timeoutMs,user:ee.action.user,working_directory:ee.action.workingDirectory,env:ee.action.env}});break}if(v&&de==="shell"){const ee=await Wt({value:re.input,schema:uu});V.push({type:"shell_call",call_id:re.toolCallId,id:Z,status:"completed",action:{commands:ee.action.commands,timeout_ms:ee.action.timeoutMs,max_output_length:ee.action.maxOutputLength}});break}if(x&&de==="apply_patch"){const ee=await Wt({value:re.input,schema:iu});V.push({type:"apply_patch_call",call_id:ee.callId,id:Z,status:"completed",operation:ee.operation});break}if(E?.has(de)){V.push({type:"custom_tool_call",call_id:re.toolCallId,name:de,input:typeof re.input=="string"?re.input:JSON.stringify(re.input),id:Z});break}V.push({type:"function_call",call_id:re.toolCallId,name:de,arguments:JSON.stringify(re.input),id:Z});break}case"tool-result":{if(re.output.type==="execution-denied"||re.output.type==="json"&&typeof re.output.value=="object"&&re.output.value!=null&&"type"in re.output.value&&re.output.value.type==="execution-denied"||g)break;const Z=r.toProviderToolName(re.toolName);if(v&&Z==="shell"){if(re.output.type==="json"){const de=await Wt({value:re.output.value,schema:So});V.push({type:"shell_call_output",call_id:re.toolCallId,output:de.output.map(ee=>({stdout:ee.stdout,stderr:ee.stderr,outcome:ee.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ee.outcome.exitCode}}))})}break}if(f){const de=(U=($=(Y=re.providerOptions)==null?void 0:Y[c])==null?void 0:$.itemId)!=null?U:re.toolCallId;V.push({type:"item_reference",id:de})}else M.push({type:"other",message:`Results for OpenAI tool ${re.toolName} are not sent to the API when store is false`});break}case"reasoning":{const Z=await Fn({provider:c,providerOptions:re.providerOptions,schema:s2}),de=Z?.itemId;if(g&&de!=null)break;if(de!=null){const ee=ie[de];if(f)ee===void 0&&(V.push({type:"item_reference",id:de}),ie[de]={type:"reasoning",id:de,summary:[]});else{const he=[];re.text.length>0?he.push({type:"summary_text",text:re.text}):ee!==void 0&&M.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(re)}.`}),ee===void 0?(ie[de]={type:"reasoning",id:de,encrypted_content:Z?.reasoningEncryptedContent,summary:he},V.push(ie[de])):(ee.summary.push(...he),Z?.reasoningEncryptedContent!=null&&(ee.encrypted_content=Z.reasoningEncryptedContent))}}else{const ee=Z?.reasoningEncryptedContent;if(ee!=null){const he=[];re.text.length>0&&he.push({type:"summary_text",text:re.text}),V.push({type:"reasoning",encrypted_content:ee,summary:he})}else M.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(re)}.`})}break}}break}case"tool":{for(const ie of le){if(ie.type==="tool-approval-response"){const ee=ie;if(Ce.has(ee.approvalId))continue;Ce.add(ee.approvalId),f&&V.push({type:"item_reference",id:ee.approvalId}),V.push({type:"mcp_approval_response",approval_request_id:ee.approvalId,approve:ee.approved});continue}const re=ie.output;if(re.type==="execution-denied"&&((X=(W=re.providerOptions)==null?void 0:W.openai)==null?void 0:X.approvalId))continue;const Z=r.toProviderToolName(ie.toolName);if(m&&Z==="local_shell"&&re.type==="json"){const ee=await Wt({value:re.value,schema:cu});V.push({type:"local_shell_call_output",call_id:ie.toolCallId,output:ee.output});continue}if(v&&Z==="shell"&&re.type==="json"){const ee=await Wt({value:re.value,schema:So});V.push({type:"shell_call_output",call_id:ie.toolCallId,output:ee.output.map(he=>({stdout:he.stdout,stderr:he.stderr,outcome:he.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:he.outcome.exitCode}}))});continue}if(x&&ie.toolName==="apply_patch"&&re.type==="json"){const ee=await Wt({value:re.value,schema:ou});V.push({type:"apply_patch_call_output",call_id:ie.toolCallId,status:ee.status,output:ee.output});continue}if(E?.has(Z)){let ee;switch(re.type){case"text":case"error-text":ee=re.value;break;case"execution-denied":ee=(H=re.reason)!=null?H:"Tool execution denied.";break;case"json":case"error-json":ee=JSON.stringify(re.value);break;case"content":ee=re.value.map(he=>{var Ie;switch(he.type){case"text":return{type:"input_text",text:he.text};case"image-data":return{type:"input_image",image_url:`data:${he.mediaType};base64,${he.data}`};case"image-url":return{type:"input_image",image_url:he.url};case"file-data":return{type:"input_file",filename:(Ie=he.filename)!=null?Ie:"data",file_data:`data:${he.mediaType};base64,${he.data}`};default:M.push({type:"other",message:`unsupported custom tool content part type: ${he.type}`});return}}).filter(ma);break;default:ee=""}V.push({type:"custom_tool_call_output",call_id:ie.toolCallId,output:ee});continue}let de;switch(re.type){case"text":case"error-text":de=re.value;break;case"execution-denied":de=(z=re.reason)!=null?z:"Tool execution denied.";break;case"json":case"error-json":de=JSON.stringify(re.value);break;case"content":de=re.value.map(ee=>{var he;switch(ee.type){case"text":return{type:"input_text",text:ee.text};case"image-data":return{type:"input_image",image_url:`data:${ee.mediaType};base64,${ee.data}`};case"image-url":return{type:"input_image",image_url:ee.url};case"file-data":return{type:"input_file",filename:(he=ee.filename)!=null?he:"data",file_data:`data:${ee.mediaType};base64,${ee.data}`};default:{M.push({type:"other",message:`unsupported tool content part type: ${ee.type}`});return}}}).filter(ma);break}V.push({type:"function_call_output",call_id:ie.toolCallId,output:de})}break}default:{const ie=me;throw new Error(`Unsupported role: ${ie}`)}}return{input:V,warnings:M}}var s2=T({itemId:_().nullish(),reasoningEncryptedContent:_().nullish()});function ka({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 a2=Pe(()=>Me(Je([T({type:K("response.output_text.delta"),item_id:_(),delta:_(),logprobs:fe(T({token:_(),logprob:q(),top_logprobs:fe(T({token:_(),logprob:q()}))})).nullish()}),T({type:Re(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:_()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}),service_tier:_().nullish()})}),T({type:K("response.created"),response:T({id:_(),created_at:q(),model:_(),service_tier:_().nullish()})}),T({type:K("response.output_item.added"),output_index:q(),item:at("type",[T({type:K("message"),id:_(),phase:Re(["commentary","final_answer"]).nullish()}),T({type:K("reasoning"),id:_(),encrypted_content:_().nullish()}),T({type:K("function_call"),id:_(),call_id:_(),name:_(),arguments:_()}),T({type:K("web_search_call"),id:_(),status:_()}),T({type:K("computer_call"),id:_(),status:_()}),T({type:K("file_search_call"),id:_()}),T({type:K("image_generation_call"),id:_()}),T({type:K("code_interpreter_call"),id:_(),container_id:_(),code:_().nullable(),outputs:fe(at("type",[T({type:K("logs"),logs:_()}),T({type:K("image"),url:_()})])).nullable(),status:_()}),T({type:K("mcp_call"),id:_(),status:_(),approval_request_id:_().nullish()}),T({type:K("mcp_list_tools"),id:_()}),T({type:K("mcp_approval_request"),id:_()}),T({type:K("apply_patch_call"),id:_(),call_id:_(),status:Re(["in_progress","completed"]),operation:at("type",[T({type:K("create_file"),path:_(),diff:_()}),T({type:K("delete_file"),path:_()}),T({type:K("update_file"),path:_(),diff:_()})])}),T({type:K("custom_tool_call"),id:_(),call_id:_(),name:_(),input:_()}),T({type:K("shell_call"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),action:T({commands:fe(_())})}),T({type:K("shell_call_output"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),output:fe(T({stdout:_(),stderr:_(),outcome:at("type",[T({type:K("timeout")}),T({type:K("exit"),exit_code:q()})])}))})])}),T({type:K("response.output_item.done"),output_index:q(),item:at("type",[T({type:K("message"),id:_(),phase:Re(["commentary","final_answer"]).nullish()}),T({type:K("reasoning"),id:_(),encrypted_content:_().nullish()}),T({type:K("function_call"),id:_(),call_id:_(),name:_(),arguments:_(),status:K("completed")}),T({type:K("custom_tool_call"),id:_(),call_id:_(),name:_(),input:_(),status:K("completed")}),T({type:K("code_interpreter_call"),id:_(),code:_().nullable(),container_id:_(),outputs:fe(at("type",[T({type:K("logs"),logs:_()}),T({type:K("image"),url:_()})])).nullable()}),T({type:K("image_generation_call"),id:_(),result:_()}),T({type:K("web_search_call"),id:_(),status:_(),action:at("type",[T({type:K("search"),query:_().nullish(),sources:fe(at("type",[T({type:K("url"),url:_()}),T({type:K("api"),name:_()})])).nullish()}),T({type:K("open_page"),url:_().nullish()}),T({type:K("find_in_page"),url:_().nullish(),pattern:_().nullish()})]).nullish()}),T({type:K("file_search_call"),id:_(),queries:fe(_()),results:fe(T({attributes:Rt(_(),Je([_(),q(),kt()])),file_id:_(),filename:_(),score:q(),text:_()})).nullish()}),T({type:K("local_shell_call"),id:_(),call_id:_(),action:T({type:K("exec"),command:fe(_()),timeout_ms:q().optional(),user:_().optional(),working_directory:_().optional(),env:Rt(_(),_()).optional()})}),T({type:K("computer_call"),id:_(),status:K("completed")}),T({type:K("mcp_call"),id:_(),status:_(),arguments:_(),name:_(),server_label:_(),output:_().nullish(),error:Je([_(),T({type:_().optional(),code:Je([q(),_()]).optional(),message:_().optional()}).loose()]).nullish(),approval_request_id:_().nullish()}),T({type:K("mcp_list_tools"),id:_(),server_label:_(),tools:fe(T({name:_(),description:_().optional(),input_schema:dr(),annotations:Rt(_(),qr()).optional()})),error:Je([_(),T({type:_().optional(),code:Je([q(),_()]).optional(),message:_().optional()}).loose()]).optional()}),T({type:K("mcp_approval_request"),id:_(),server_label:_(),name:_(),arguments:_(),approval_request_id:_().optional()}),T({type:K("apply_patch_call"),id:_(),call_id:_(),status:Re(["in_progress","completed"]),operation:at("type",[T({type:K("create_file"),path:_(),diff:_()}),T({type:K("delete_file"),path:_()}),T({type:K("update_file"),path:_(),diff:_()})])}),T({type:K("shell_call"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),action:T({commands:fe(_())})}),T({type:K("shell_call_output"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),output:fe(T({stdout:_(),stderr:_(),outcome:at("type",[T({type:K("timeout")}),T({type:K("exit"),exit_code:q()})])}))})])}),T({type:K("response.function_call_arguments.delta"),item_id:_(),output_index:q(),delta:_()}),T({type:K("response.custom_tool_call_input.delta"),item_id:_(),output_index:q(),delta:_()}),T({type:K("response.image_generation_call.partial_image"),item_id:_(),output_index:q(),partial_image_b64:_()}),T({type:K("response.code_interpreter_call_code.delta"),item_id:_(),output_index:q(),delta:_()}),T({type:K("response.code_interpreter_call_code.done"),item_id:_(),output_index:q(),code:_()}),T({type:K("response.output_text.annotation.added"),annotation:at("type",[T({type:K("url_citation"),start_index:q(),end_index:q(),url:_(),title:_()}),T({type:K("file_citation"),file_id:_(),filename:_(),index:q()}),T({type:K("container_file_citation"),container_id:_(),file_id:_(),filename:_(),start_index:q(),end_index:q()}),T({type:K("file_path"),file_id:_(),index:q()})])}),T({type:K("response.reasoning_summary_part.added"),item_id:_(),summary_index:q()}),T({type:K("response.reasoning_summary_text.delta"),item_id:_(),summary_index:q(),delta:_()}),T({type:K("response.reasoning_summary_part.done"),item_id:_(),summary_index:q()}),T({type:K("response.apply_patch_call_operation_diff.delta"),item_id:_(),output_index:q(),delta:_(),obfuscation:_().nullish()}),T({type:K("response.apply_patch_call_operation_diff.done"),item_id:_(),output_index:q(),diff:_()}),T({type:K("error"),sequence_number:q(),error:T({type:_(),code:_(),message:_(),param:_().nullish()})}),T({type:_()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),l2=Pe(()=>Me(T({id:_().optional(),created_at:q().optional(),error:T({message:_(),type:_(),param:_().nullish(),code:_()}).nullish(),model:_().optional(),output:fe(at("type",[T({type:K("message"),role:K("assistant"),id:_(),phase:Re(["commentary","final_answer"]).nullish(),content:fe(T({type:K("output_text"),text:_(),logprobs:fe(T({token:_(),logprob:q(),top_logprobs:fe(T({token:_(),logprob:q()}))})).nullish(),annotations:fe(at("type",[T({type:K("url_citation"),start_index:q(),end_index:q(),url:_(),title:_()}),T({type:K("file_citation"),file_id:_(),filename:_(),index:q()}),T({type:K("container_file_citation"),container_id:_(),file_id:_(),filename:_(),start_index:q(),end_index:q()}),T({type:K("file_path"),file_id:_(),index:q()})]))}))}),T({type:K("web_search_call"),id:_(),status:_(),action:at("type",[T({type:K("search"),query:_().nullish(),sources:fe(at("type",[T({type:K("url"),url:_()}),T({type:K("api"),name:_()})])).nullish()}),T({type:K("open_page"),url:_().nullish()}),T({type:K("find_in_page"),url:_().nullish(),pattern:_().nullish()})]).nullish()}),T({type:K("file_search_call"),id:_(),queries:fe(_()),results:fe(T({attributes:Rt(_(),Je([_(),q(),kt()])),file_id:_(),filename:_(),score:q(),text:_()})).nullish()}),T({type:K("code_interpreter_call"),id:_(),code:_().nullable(),container_id:_(),outputs:fe(at("type",[T({type:K("logs"),logs:_()}),T({type:K("image"),url:_()})])).nullable()}),T({type:K("image_generation_call"),id:_(),result:_()}),T({type:K("local_shell_call"),id:_(),call_id:_(),action:T({type:K("exec"),command:fe(_()),timeout_ms:q().optional(),user:_().optional(),working_directory:_().optional(),env:Rt(_(),_()).optional()})}),T({type:K("function_call"),call_id:_(),name:_(),arguments:_(),id:_()}),T({type:K("custom_tool_call"),call_id:_(),name:_(),input:_(),id:_()}),T({type:K("computer_call"),id:_(),status:_().optional()}),T({type:K("reasoning"),id:_(),encrypted_content:_().nullish(),summary:fe(T({type:K("summary_text"),text:_()}))}),T({type:K("mcp_call"),id:_(),status:_(),arguments:_(),name:_(),server_label:_(),output:_().nullish(),error:Je([_(),T({type:_().optional(),code:Je([q(),_()]).optional(),message:_().optional()}).loose()]).nullish(),approval_request_id:_().nullish()}),T({type:K("mcp_list_tools"),id:_(),server_label:_(),tools:fe(T({name:_(),description:_().optional(),input_schema:dr(),annotations:Rt(_(),qr()).optional()})),error:Je([_(),T({type:_().optional(),code:Je([q(),_()]).optional(),message:_().optional()}).loose()]).optional()}),T({type:K("mcp_approval_request"),id:_(),server_label:_(),name:_(),arguments:_(),approval_request_id:_().optional()}),T({type:K("apply_patch_call"),id:_(),call_id:_(),status:Re(["in_progress","completed"]),operation:at("type",[T({type:K("create_file"),path:_(),diff:_()}),T({type:K("delete_file"),path:_()}),T({type:K("update_file"),path:_(),diff:_()})])}),T({type:K("shell_call"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),action:T({commands:fe(_())})}),T({type:K("shell_call_output"),id:_(),call_id:_(),status:Re(["in_progress","completed","incomplete"]),output:fe(T({stdout:_(),stderr:_(),outcome:at("type",[T({type:K("timeout")}),T({type:K("exit"),exit_code:q()})])}))})])).optional(),service_tier:_().nullish(),incomplete_details:T({reason:_()}).nullish(),usage:T({input_tokens:q(),input_tokens_details:T({cached_tokens:q().nullish()}).nullish(),output_tokens:q(),output_tokens_details:T({reasoning_tokens:q().nullish()}).nullish()}).optional()}))),du=20,Ra=Pe(()=>Me(T({conversation:_().nullish(),include:fe(Re(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:_().nullish(),logprobs:Je([kt(),q().min(1).max(du)]).optional(),maxToolCalls:q().nullish(),metadata:dr().nullish(),parallelToolCalls:kt().nullish(),previousResponseId:_().nullish(),promptCacheKey:_().nullish(),promptCacheRetention:Re(["in_memory","24h"]).nullish(),reasoningEffort:_().nullish(),reasoningSummary:_().nullish(),safetyIdentifier:_().nullish(),serviceTier:Re(["auto","flex","priority","default"]).nullish(),store:kt().nullish(),strictJsonSchema:kt().nullish(),textVerbosity:Re(["low","medium","high"]).nullish(),truncation:Re(["auto","disabled"]).nullish(),user:_().nullish(),systemMessageMode:Re(["system","developer","remove"]).optional(),forceReasoning:kt().optional()})));async function c2({tools:t,toolChoice:r,toolNameMapping:o,customProviderToolNames:c}){var u;t=t?.length?t:void 0;const f=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:f};const g=[],m=c??new Set;for(const x of t)switch(x.type){case"function":g.push({type:"function",name:x.name,description:x.description,parameters:x.inputSchema,...x.strict!=null?{strict:x.strict}:{}});break;case"provider":{switch(x.id){case"openai.file_search":{const E=await Wt({value:x.args,schema:Rm});g.push({type:"file_search",vector_store_ids:E.vectorStoreIds,max_num_results:E.maxNumResults,ranking_options:E.ranking?{ranker:E.ranking.ranker,score_threshold:E.ranking.scoreThreshold}:void 0,filters:E.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const E=await Wt({value:x.args,schema:Zm});g.push({type:"shell",...E.environment&&{environment:u2(E.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const E=await Wt({value:x.args,schema:qm});g.push({type:"web_search_preview",search_context_size:E.searchContextSize,user_location:E.userLocation});break}case"openai.web_search":{const E=await Wt({value:x.args,schema:Wm});g.push({type:"web_search",filters:E.filters!=null?{allowed_domains:E.filters.allowedDomains}:void 0,external_web_access:E.externalWebAccess,search_context_size:E.searchContextSize,user_location:E.userLocation});break}case"openai.code_interpreter":{const E=await Wt({value:x.args,schema:Am});g.push({type:"code_interpreter",container:E.container==null?{type:"auto",file_ids:void 0}:typeof E.container=="string"?E.container:{type:"auto",file_ids:E.container.fileIds}});break}case"openai.image_generation":{const E=await Wt({value:x.args,schema:Pm});g.push({type:"image_generation",background:E.background,input_fidelity:E.inputFidelity,input_image_mask:E.inputImageMask?{file_id:E.inputImageMask.fileId,image_url:E.inputImageMask.imageUrl}:void 0,model:E.model,moderation:E.moderation,partial_images:E.partialImages,quality:E.quality,output_compression:E.outputCompression,output_format:E.outputFormat,size:E.size});break}case"openai.mcp":{const E=await Wt({value:x.args,schema:Qm}),A=R=>({tool_names:R.toolNames}),B=E.requireApproval,O=B==null?void 0:typeof B=="string"?B:B.never!=null?{never:A(B.never)}:void 0;g.push({type:"mcp",server_label:E.serverLabel,allowed_tools:Array.isArray(E.allowedTools)?E.allowedTools:E.allowedTools?{read_only:E.allowedTools.readOnly,tool_names:E.allowedTools.toolNames}:void 0,authorization:E.authorization,connector_id:E.connectorId,headers:E.headers,require_approval:O??"never",server_description:E.serverDescription,server_url:E.serverUrl});break}case"openai.custom":{const E=await Wt({value:x.args,schema:Tm});g.push({type:"custom",name:E.name,description:E.description,format:E.format}),m.add(E.name);break}}break}default:f.push({type:"unsupported",feature:`function tool ${x}`});break}if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:f};const v=r.type;switch(v){case"auto":case"none":case"required":return{tools:g,toolChoice:v,toolWarnings:f};case"tool":{const x=(u=o?.toProviderToolName(r.toolName))!=null?u:r.toolName;return{tools:g,toolChoice:x==="code_interpreter"||x==="file_search"||x==="image_generation"||x==="web_search_preview"||x==="web_search"||x==="mcp"||x==="apply_patch"?{type:x}:m.has(x)?{type:"custom",name:x}:{type:"function",name:x},toolWarnings:f}}default:{const x=v;throw new Ln({functionality:`tool choice type: ${x}`})}}}function u2(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:d2(o.skills)}}return{type:"local",skills:t.skills}}function d2(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 Ma(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 g=(o=(r=f.providerOptions)==null?void 0:r.openai)==null?void 0:o.approvalRequestId;g!=null&&(c[g]=f.toolCallId)}return c}var f2=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:g,seed:m,prompt:v,providerOptions:x,tools:E,toolChoice:A,responseFormat:B}){var O,R,D,P,Y,$,U,W,X;const H=[],z=ru(this.modelId);u!=null&&H.push({type:"unsupported",feature:"topK"}),m!=null&&H.push({type:"unsupported",feature:"seed"}),f!=null&&H.push({type:"unsupported",feature:"presencePenalty"}),g!=null&&H.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&H.push({type:"unsupported",feature:"stopSequences"});const V=this.config.provider.includes("azure")?"azure":"openai";let M=await Fn({provider:V,providerOptions:x,schema:Ra});M==null&&V!=="openai"&&(M=await Fn({provider:"openai",providerOptions:x,schema:Ra}));const Ce=(O=M?.forceReasoning)!=null?O:z.isReasoningModel;M?.conversation&&M?.previousResponseId&&H.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const me=Dp({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"},resolveProviderToolName:Ne=>Ne.id==="openai.custom"?Ne.args.name:void 0}),le=new Set,{tools:ie,toolChoice:re,toolWarnings:Z}=await c2({tools:E,toolChoice:A,toolNameMapping:me,customProviderToolNames:le}),{input:de,warnings:ee}=await o2({prompt:v,toolNameMapping:me,systemMessageMode:(R=M?.systemMessageMode)!=null?R:Ce?"developer":z.systemMessageMode,providerOptionsName:V,fileIdPrefixes:this.config.fileIdPrefixes,store:(D=M?.store)!=null?D:!0,hasConversation:M?.conversation!=null,hasLocalShellTool:ge("openai.local_shell"),hasShellTool:ge("openai.shell"),hasApplyPatchTool:ge("openai.apply_patch"),customProviderToolNames:le.size>0?le:void 0});H.push(...ee);const he=(P=M?.strictJsonSchema)!=null?P:!0;let Ie=M?.include;function Te(Ne){Ie==null?Ie=[Ne]:Ie.includes(Ne)||(Ie=[...Ie,Ne])}function ge(Ne){return E?.find(Fe=>Fe.type==="provider"&&Fe.id===Ne)!=null}const De=typeof M?.logprobs=="number"?M?.logprobs:M?.logprobs===!0?du:void 0;De&&Te("message.output_text.logprobs");const At=(Y=E?.find(Ne=>Ne.type==="provider"&&(Ne.id==="openai.web_search"||Ne.id==="openai.web_search_preview")))==null?void 0:Y.name;At&&Te("web_search_call.action.sources"),ge("openai.code_interpreter")&&Te("code_interpreter_call.outputs");const Ye=M?.store;Ye===!1&&Ce&&Te("reasoning.encrypted_content");const It={model:this.modelId,input:de,temperature:r,top_p:c,max_output_tokens:t,...(B?.type==="json"||M?.textVerbosity)&&{text:{...B?.type==="json"&&{format:B.schema!=null?{type:"json_schema",strict:he,name:($=B.name)!=null?$:"response",description:B.description,schema:B.schema}:{type:"json_object"}},...M?.textVerbosity&&{verbosity:M.textVerbosity}}},conversation:M?.conversation,max_tool_calls:M?.maxToolCalls,metadata:M?.metadata,parallel_tool_calls:M?.parallelToolCalls,previous_response_id:M?.previousResponseId,store:Ye,user:M?.user,instructions:M?.instructions,service_tier:M?.serviceTier,include:Ie,prompt_cache_key:M?.promptCacheKey,prompt_cache_retention:M?.promptCacheRetention,safety_identifier:M?.safetyIdentifier,top_logprobs:De,truncation:M?.truncation,...Ce&&(M?.reasoningEffort!=null||M?.reasoningSummary!=null)&&{reasoning:{...M?.reasoningEffort!=null&&{effort:M.reasoningEffort},...M?.reasoningSummary!=null&&{summary:M.reasoningSummary}}}};Ce?M?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(It.temperature!=null&&(It.temperature=void 0,H.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),It.top_p!=null&&(It.top_p=void 0,H.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(M?.reasoningEffort!=null&&H.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),M?.reasoningSummary!=null&&H.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),M?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(H.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete It.service_tier),M?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(H.push({type:"unsupported",feature:"serviceTier",details:"priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported"}),delete It.service_tier);const te=(X=(W=(U=E?.find(Ne=>Ne.type==="provider"&&Ne.id==="openai.shell"))==null?void 0:U.args)==null?void 0:W.environment)==null?void 0:X.type,Ve=te==="containerAuto"||te==="containerReference";return{webSearchToolName:At,args:{...It,tools:ie,tool_choice:re},warnings:[...H,...Z],store:Ye,toolNameMapping:me,providerOptionsName:V,isShellProviderExecuted:Ve}}async doGenerate(t){var r,o,c,u,f,g,m,v,x,E,A,B,O,R,D,P,Y,$,U,W,X,H,z,V,M;const{args:Ce,warnings:me,webSearchToolName:le,toolNameMapping:ie,providerOptionsName:re,isShellProviderExecuted:Z}=await this.getArgs(t),de=this.config.url({path:"/responses",modelId:this.modelId}),ee=Ma(t.prompt),{responseHeaders:he,value:Ie,rawValue:Te}=await Un({url:de,headers:bn(this.config.headers(),t.headers),body:Ce,failedResponseHandler:En,successfulResponseHandler:cr(l2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(Ie.error)throw new ln({message:Ie.error.message,url:de,requestBodyValues:Ce,statusCode:400,responseHeaders:he,responseBody:Te,isRetryable:!1});const ge=[],De=[];let At=!1;for(const te of Ie.output)switch(te.type){case"reasoning":{te.summary.length===0&&te.summary.push({type:"summary_text",text:""});for(const Ve of te.summary)ge.push({type:"reasoning",text:Ve.text,providerMetadata:{[re]:{itemId:te.id,reasoningEncryptedContent:(r=te.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{ge.push({type:"tool-call",toolCallId:te.id,toolName:ie.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),ge.push({type:"tool-result",toolCallId:te.id,toolName:ie.toCustomToolName("image_generation"),result:{result:te.result}});break}case"local_shell_call":{ge.push({type:"tool-call",toolCallId:te.call_id,toolName:ie.toCustomToolName("local_shell"),input:JSON.stringify({action:te.action}),providerMetadata:{[re]:{itemId:te.id}}});break}case"shell_call":{ge.push({type:"tool-call",toolCallId:te.call_id,toolName:ie.toCustomToolName("shell"),input:JSON.stringify({action:{commands:te.action.commands}}),...Z&&{providerExecuted:!0},providerMetadata:{[re]:{itemId:te.id}}});break}case"shell_call_output":{ge.push({type:"tool-result",toolCallId:te.call_id,toolName:ie.toCustomToolName("shell"),result:{output:te.output.map(Ve=>({stdout:Ve.stdout,stderr:Ve.stderr,outcome:Ve.outcome.type==="exit"?{type:"exit",exitCode:Ve.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const Ve of te.content){(c=(o=t.providerOptions)==null?void 0:o[re])!=null&&c.logprobs&&Ve.logprobs&&De.push(Ve.logprobs);const Ne={itemId:te.id,...te.phase!=null&&{phase:te.phase},...Ve.annotations.length>0&&{annotations:Ve.annotations}};ge.push({type:"text",text:Ve.text,providerMetadata:{[re]:Ne}});for(const Fe of Ve.annotations)Fe.type==="url_citation"?ge.push({type:"source",sourceType:"url",id:(g=(f=(u=this.config).generateId)==null?void 0:f.call(u))!=null?g:Xt(),url:Fe.url,title:Fe.title}):Fe.type==="file_citation"?ge.push({type:"source",sourceType:"document",id:(x=(v=(m=this.config).generateId)==null?void 0:v.call(m))!=null?x:Xt(),mediaType:"text/plain",title:Fe.filename,filename:Fe.filename,providerMetadata:{[re]:{type:Fe.type,fileId:Fe.file_id,index:Fe.index}}}):Fe.type==="container_file_citation"?ge.push({type:"source",sourceType:"document",id:(B=(A=(E=this.config).generateId)==null?void 0:A.call(E))!=null?B:Xt(),mediaType:"text/plain",title:Fe.filename,filename:Fe.filename,providerMetadata:{[re]:{type:Fe.type,fileId:Fe.file_id,containerId:Fe.container_id}}}):Fe.type==="file_path"&&ge.push({type:"source",sourceType:"document",id:(D=(R=(O=this.config).generateId)==null?void 0:R.call(O))!=null?D:Xt(),mediaType:"application/octet-stream",title:Fe.file_id,filename:Fe.file_id,providerMetadata:{[re]:{type:Fe.type,fileId:Fe.file_id,index:Fe.index}}})}break}case"function_call":{At=!0,ge.push({type:"tool-call",toolCallId:te.call_id,toolName:te.name,input:te.arguments,providerMetadata:{[re]:{itemId:te.id}}});break}case"custom_tool_call":{At=!0;const Ve=ie.toCustomToolName(te.name);ge.push({type:"tool-call",toolCallId:te.call_id,toolName:Ve,input:JSON.stringify(te.input),providerMetadata:{[re]:{itemId:te.id}}});break}case"web_search_call":{ge.push({type:"tool-call",toolCallId:te.id,toolName:ie.toCustomToolName(le??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),ge.push({type:"tool-result",toolCallId:te.id,toolName:ie.toCustomToolName(le??"web_search"),result:Pa(te.action)});break}case"mcp_call":{const Ve=te.approval_request_id!=null&&(P=ee[te.approval_request_id])!=null?P:te.id,Ne=`mcp.${te.name}`;ge.push({type:"tool-call",toolCallId:Ve,toolName:Ne,input:te.arguments,providerExecuted:!0,dynamic:!0}),ge.push({type:"tool-result",toolCallId:Ve,toolName:Ne,result:{type:"call",serverLabel:te.server_label,name:te.name,arguments:te.arguments,...te.output!=null?{output:te.output}:{},...te.error!=null?{error:te.error}:{}},providerMetadata:{[re]:{itemId:te.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Ve=(Y=te.approval_request_id)!=null?Y:te.id,Ne=(W=(U=($=this.config).generateId)==null?void 0:U.call($))!=null?W:Xt(),Fe=`mcp.${te.name}`;ge.push({type:"tool-call",toolCallId:Ne,toolName:Fe,input:te.arguments,providerExecuted:!0,dynamic:!0}),ge.push({type:"tool-approval-request",approvalId:Ve,toolCallId:Ne});break}case"computer_call":{ge.push({type:"tool-call",toolCallId:te.id,toolName:ie.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),ge.push({type:"tool-result",toolCallId:te.id,toolName:ie.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:te.status||"completed"}});break}case"file_search_call":{ge.push({type:"tool-call",toolCallId:te.id,toolName:ie.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),ge.push({type:"tool-result",toolCallId:te.id,toolName:ie.toCustomToolName("file_search"),result:{queries:te.queries,results:(H=(X=te.results)==null?void 0:X.map(Ve=>({attributes:Ve.attributes,fileId:Ve.file_id,filename:Ve.filename,score:Ve.score,text:Ve.text})))!=null?H:null}});break}case"code_interpreter_call":{ge.push({type:"tool-call",toolCallId:te.id,toolName:ie.toCustomToolName("code_interpreter"),input:JSON.stringify({code:te.code,containerId:te.container_id}),providerExecuted:!0}),ge.push({type:"tool-result",toolCallId:te.id,toolName:ie.toCustomToolName("code_interpreter"),result:{outputs:te.outputs}});break}case"apply_patch_call":{ge.push({type:"tool-call",toolCallId:te.call_id,toolName:ie.toCustomToolName("apply_patch"),input:JSON.stringify({callId:te.call_id,operation:te.operation}),providerMetadata:{[re]:{itemId:te.id}}});break}}const Ye={[re]:{responseId:Ie.id,...De.length>0?{logprobs:De}:{},...typeof Ie.service_tier=="string"?{serviceTier:Ie.service_tier}:{}}},It=Ie.usage;return{content:ge,finishReason:{unified:ka({finishReason:(z=Ie.incomplete_details)==null?void 0:z.reason,hasFunctionCall:At}),raw:(M=(V=Ie.incomplete_details)==null?void 0:V.reason)!=null?M:void 0},usage:Na(It),request:{body:Ce},response:{id:Ie.id,timestamp:new Date(Ie.created_at*1e3),modelId:Ie.model,headers:he,body:Te},providerMetadata:Ye,warnings:me}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:g,isShellProviderExecuted:m}=await this.getArgs(t),{responseHeaders:v,value:x}=await Un({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:En,successfulResponseHandler:Ho(a2),abortSignal:t.abortSignal,fetch:this.config.fetch}),E=this,A=Ma(t.prompt),B=new Map;let O={unified:"other",raw:void 0},R;const D=[];let P=null;const Y={},$=[];let U,W=!1;const X={};let H;return{stream:x.pipeThrough(new TransformStream({start(z){z.enqueue({type:"stream-start",warnings:o})},transform(z,V){var M,Ce,me,le,ie,re,Z,de,ee,he,Ie,Te,ge,De,At,Ye,It,te,Ve,Ne,Fe,mn,St,nn,Ue,Ht,Vt,An,xt,je,ze,In;if(t.includeRawChunks&&V.enqueue({type:"raw",rawValue:z.rawValue}),!z.success){O={unified:"error",raw:void 0},V.enqueue({type:"error",error:z.error});return}const S=z.value;if(Da(S)){if(S.item.type==="function_call")Y[S.output_index]={toolName:S.item.name,toolCallId:S.item.call_id},V.enqueue({type:"tool-input-start",id:S.item.call_id,toolName:S.item.name});else if(S.item.type==="custom_tool_call"){const ue=u.toCustomToolName(S.item.name);Y[S.output_index]={toolName:ue,toolCallId:S.item.call_id},V.enqueue({type:"tool-input-start",id:S.item.call_id,toolName:ue})}else if(S.item.type==="web_search_call")Y[S.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:S.item.id},V.enqueue({type:"tool-input-start",id:S.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),V.enqueue({type:"tool-input-end",id:S.item.id}),V.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(S.item.type==="computer_call")Y[S.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:S.item.id},V.enqueue({type:"tool-input-start",id:S.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(S.item.type==="code_interpreter_call")Y[S.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:S.item.id,codeInterpreter:{containerId:S.item.container_id}},V.enqueue({type:"tool-input-start",id:S.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),V.enqueue({type:"tool-input-delta",id:S.item.id,delta:`{"containerId":"${S.item.container_id}","code":"`});else if(S.item.type==="file_search_call")V.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(S.item.type==="image_generation_call")V.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(!(S.item.type==="mcp_call"||S.item.type==="mcp_list_tools"||S.item.type==="mcp_approval_request"))if(S.item.type==="apply_patch_call"){const{call_id:ue,operation:dt}=S.item;if(Y[S.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:ue,applyPatch:{hasDiff:dt.type==="delete_file",endEmitted:dt.type==="delete_file"}},V.enqueue({type:"tool-input-start",id:ue,toolName:u.toCustomToolName("apply_patch")}),dt.type==="delete_file"){const pt=JSON.stringify({callId:ue,operation:dt});V.enqueue({type:"tool-input-delta",id:ue,delta:pt}),V.enqueue({type:"tool-input-end",id:ue})}else V.enqueue({type:"tool-input-delta",id:ue,delta:`{"callId":"${sr(ue)}","operation":{"type":"${sr(dt.type)}","path":"${sr(dt.path)}","diff":"`})}else S.item.type==="shell_call"?Y[S.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:S.item.call_id}:S.item.type==="shell_call_output"||(S.item.type==="message"?($.splice(0,$.length),U=(M=S.item.phase)!=null?M:void 0,V.enqueue({type:"text-start",id:S.item.id,providerMetadata:{[g]:{itemId:S.item.id,...S.item.phase!=null&&{phase:S.item.phase}}}})):Da(S)&&S.item.type==="reasoning"&&(X[S.item.id]={encryptedContent:S.item.encrypted_content,summaryParts:{0:"active"}},V.enqueue({type:"reasoning-start",id:`${S.item.id}:0`,providerMetadata:{[g]:{itemId:S.item.id,reasoningEncryptedContent:(Ce=S.item.encrypted_content)!=null?Ce:null}}})))}else if(p2(S)){if(S.item.type==="message"){const ue=(me=S.item.phase)!=null?me:U;U=void 0,V.enqueue({type:"text-end",id:S.item.id,providerMetadata:{[g]:{itemId:S.item.id,...ue!=null&&{phase:ue},...$.length>0&&{annotations:$}}}})}else if(S.item.type==="function_call")Y[S.output_index]=void 0,W=!0,V.enqueue({type:"tool-input-end",id:S.item.call_id}),V.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:S.item.name,input:S.item.arguments,providerMetadata:{[g]:{itemId:S.item.id}}});else if(S.item.type==="custom_tool_call"){Y[S.output_index]=void 0,W=!0;const ue=u.toCustomToolName(S.item.name);V.enqueue({type:"tool-input-end",id:S.item.call_id}),V.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:ue,input:JSON.stringify(S.item.input),providerMetadata:{[g]:{itemId:S.item.id}}})}else if(S.item.type==="web_search_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Pa(S.item.action)});else if(S.item.type==="computer_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-input-end",id:S.item.id}),V.enqueue({type:"tool-call",toolCallId:S.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),V.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:S.item.status||"completed"}});else if(S.item.type==="file_search_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:S.item.queries,results:(ie=(le=S.item.results)==null?void 0:le.map(ue=>({attributes:ue.attributes,fileId:ue.file_id,filename:ue.filename,score:ue.score,text:ue.text})))!=null?ie:null}});else if(S.item.type==="code_interpreter_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:S.item.outputs}});else if(S.item.type==="image_generation_call")V.enqueue({type:"tool-result",toolCallId:S.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:S.item.result}});else if(S.item.type==="mcp_call"){Y[S.output_index]=void 0;const ue=(re=S.item.approval_request_id)!=null?re:void 0,dt=ue!=null&&(de=(Z=B.get(ue))!=null?Z:A[ue])!=null?de:S.item.id,pt=`mcp.${S.item.name}`;V.enqueue({type:"tool-call",toolCallId:dt,toolName:pt,input:S.item.arguments,providerExecuted:!0,dynamic:!0}),V.enqueue({type:"tool-result",toolCallId:dt,toolName:pt,result:{type:"call",serverLabel:S.item.server_label,name:S.item.name,arguments:S.item.arguments,...S.item.output!=null?{output:S.item.output}:{},...S.item.error!=null?{error:S.item.error}:{}},providerMetadata:{[g]:{itemId:S.item.id}}})}else if(S.item.type==="mcp_list_tools")Y[S.output_index]=void 0;else if(S.item.type==="apply_patch_call"){const ue=Y[S.output_index];ue?.applyPatch&&!ue.applyPatch.endEmitted&&S.item.operation.type!=="delete_file"&&(ue.applyPatch.hasDiff||V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:sr(S.item.operation.diff)}),V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:'"}}'}),V.enqueue({type:"tool-input-end",id:ue.toolCallId}),ue.applyPatch.endEmitted=!0),ue&&S.item.status==="completed"&&V.enqueue({type:"tool-call",toolCallId:ue.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:S.item.call_id,operation:S.item.operation}),providerMetadata:{[g]:{itemId:S.item.id}}}),Y[S.output_index]=void 0}else if(S.item.type==="mcp_approval_request"){Y[S.output_index]=void 0;const ue=(Ie=(he=(ee=E.config).generateId)==null?void 0:he.call(ee))!=null?Ie:Xt(),dt=(Te=S.item.approval_request_id)!=null?Te:S.item.id;B.set(dt,ue);const pt=`mcp.${S.item.name}`;V.enqueue({type:"tool-call",toolCallId:ue,toolName:pt,input:S.item.arguments,providerExecuted:!0,dynamic:!0}),V.enqueue({type:"tool-approval-request",approvalId:dt,toolCallId:ue})}else if(S.item.type==="local_shell_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:S.item.action.command,timeoutMs:S.item.action.timeout_ms,user:S.item.action.user,workingDirectory:S.item.action.working_directory,env:S.item.action.env}}),providerMetadata:{[g]:{itemId:S.item.id}}});else if(S.item.type==="shell_call")Y[S.output_index]=void 0,V.enqueue({type:"tool-call",toolCallId:S.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:S.item.action.commands}}),...m&&{providerExecuted:!0},providerMetadata:{[g]:{itemId:S.item.id}}});else if(S.item.type==="shell_call_output")V.enqueue({type:"tool-result",toolCallId:S.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:S.item.output.map(ue=>({stdout:ue.stdout,stderr:ue.stderr,outcome:ue.outcome.type==="exit"?{type:"exit",exitCode:ue.outcome.exit_code}:{type:"timeout"}}))}});else if(S.item.type==="reasoning"){const ue=X[S.item.id],dt=Object.entries(ue.summaryParts).filter(([pt,Sn])=>Sn==="active"||Sn==="can-conclude").map(([pt])=>pt);for(const pt of dt)V.enqueue({type:"reasoning-end",id:`${S.item.id}:${pt}`,providerMetadata:{[g]:{itemId:S.item.id,reasoningEncryptedContent:(ge=S.item.encrypted_content)!=null?ge:null}}});delete X[S.item.id]}}else if(x2(S)){const ue=Y[S.output_index];ue!=null&&V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:S.delta})}else if(w2(S)){const ue=Y[S.output_index];ue!=null&&V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:S.delta})}else if(C2(S)){const ue=Y[S.output_index];ue?.applyPatch&&(V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:sr(S.delta)}),ue.applyPatch.hasDiff=!0)}else if(b2(S)){const ue=Y[S.output_index];ue?.applyPatch&&!ue.applyPatch.endEmitted&&(ue.applyPatch.hasDiff||(V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:sr(S.diff)}),ue.applyPatch.hasDiff=!0),V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:'"}}'}),V.enqueue({type:"tool-input-end",id:ue.toolCallId}),ue.applyPatch.endEmitted=!0)}else if(y2(S))V.enqueue({type:"tool-result",toolCallId:S.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:S.partial_image_b64},preliminary:!0});else if(_2(S)){const ue=Y[S.output_index];ue!=null&&V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:sr(S.delta)})}else if(v2(S)){const ue=Y[S.output_index];ue!=null&&(V.enqueue({type:"tool-input-delta",id:ue.toolCallId,delta:'"}'}),V.enqueue({type:"tool-input-end",id:ue.toolCallId}),V.enqueue({type:"tool-call",toolCallId:ue.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:S.code,containerId:ue.codeInterpreter.containerId}),providerExecuted:!0}))}else if(m2(S))P=S.response.id,V.enqueue({type:"response-metadata",id:S.response.id,timestamp:new Date(S.response.created_at*1e3),modelId:S.response.model});else if(h2(S))V.enqueue({type:"text-delta",id:S.item_id,delta:S.delta}),(At=(De=t.providerOptions)==null?void 0:De[g])!=null&&At.logprobs&&S.logprobs&&D.push(S.logprobs);else if(S.type==="response.reasoning_summary_part.added"){if(S.summary_index>0){const ue=X[S.item_id];ue.summaryParts[S.summary_index]="active";for(const dt of Object.keys(ue.summaryParts))ue.summaryParts[dt]==="can-conclude"&&(V.enqueue({type:"reasoning-end",id:`${S.item_id}:${dt}`,providerMetadata:{[g]:{itemId:S.item_id}}}),ue.summaryParts[dt]="concluded");V.enqueue({type:"reasoning-start",id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[g]:{itemId:S.item_id,reasoningEncryptedContent:(It=(Ye=X[S.item_id])==null?void 0:Ye.encryptedContent)!=null?It:null}}})}}else S.type==="response.reasoning_summary_text.delta"?V.enqueue({type:"reasoning-delta",id:`${S.item_id}:${S.summary_index}`,delta:S.delta,providerMetadata:{[g]:{itemId:S.item_id}}}):S.type==="response.reasoning_summary_part.done"?f?(V.enqueue({type:"reasoning-end",id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[g]:{itemId:S.item_id}}}),X[S.item_id].summaryParts[S.summary_index]="concluded"):X[S.item_id].summaryParts[S.summary_index]="can-conclude":g2(S)?(O={unified:ka({finishReason:(te=S.response.incomplete_details)==null?void 0:te.reason,hasFunctionCall:W}),raw:(Ne=(Ve=S.response.incomplete_details)==null?void 0:Ve.reason)!=null?Ne:void 0},R=S.response.usage,typeof S.response.service_tier=="string"&&(H=S.response.service_tier)):E2(S)?($.push(S.annotation),S.annotation.type==="url_citation"?V.enqueue({type:"source",sourceType:"url",id:(St=(mn=(Fe=E.config).generateId)==null?void 0:mn.call(Fe))!=null?St:Xt(),url:S.annotation.url,title:S.annotation.title}):S.annotation.type==="file_citation"?V.enqueue({type:"source",sourceType:"document",id:(Ht=(Ue=(nn=E.config).generateId)==null?void 0:Ue.call(nn))!=null?Ht:Xt(),mediaType:"text/plain",title:S.annotation.filename,filename:S.annotation.filename,providerMetadata:{[g]:{type:S.annotation.type,fileId:S.annotation.file_id,index:S.annotation.index}}}):S.annotation.type==="container_file_citation"?V.enqueue({type:"source",sourceType:"document",id:(xt=(An=(Vt=E.config).generateId)==null?void 0:An.call(Vt))!=null?xt:Xt(),mediaType:"text/plain",title:S.annotation.filename,filename:S.annotation.filename,providerMetadata:{[g]:{type:S.annotation.type,fileId:S.annotation.file_id,containerId:S.annotation.container_id}}}):S.annotation.type==="file_path"&&V.enqueue({type:"source",sourceType:"document",id:(In=(ze=(je=E.config).generateId)==null?void 0:ze.call(je))!=null?In:Xt(),mediaType:"application/octet-stream",title:S.annotation.file_id,filename:S.annotation.file_id,providerMetadata:{[g]:{type:S.annotation.type,fileId:S.annotation.file_id,index:S.annotation.index}}})):A2(S)&&V.enqueue({type:"error",error:S})},flush(z){const V={[g]:{responseId:P,...D.length>0?{logprobs:D}:{},...H!==void 0?{serviceTier:H}:{}}};z.enqueue({type:"finish",finishReason:O,usage:Na(R),providerMetadata:V})}})),request:{body:r},response:{headers:v}}}};function h2(t){return t.type==="response.output_text.delta"}function p2(t){return t.type==="response.output_item.done"}function g2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function m2(t){return t.type==="response.created"}function x2(t){return t.type==="response.function_call_arguments.delta"}function w2(t){return t.type==="response.custom_tool_call_input.delta"}function y2(t){return t.type==="response.image_generation_call.partial_image"}function _2(t){return t.type==="response.code_interpreter_call_code.delta"}function v2(t){return t.type==="response.code_interpreter_call_code.done"}function C2(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function b2(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Da(t){return t.type==="response.output_item.added"}function E2(t){return t.type==="response.output_text.annotation.added"}function A2(t){return t.type==="error"}function Pa(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function sr(t){return JSON.stringify(t).slice(1,-1)}var I2=Pe(()=>Me(T({instructions:_().nullish(),speed:q().min(.25).max(4).default(1).nullish()}))),S2=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:g}){const m=[],v=await Fn({provider:"openai",providerOptions:g,schema:I2}),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:m.push({type:"unsupported",feature:"outputFormat",details:`Unsupported output format: ${o}. Using mp3 instead.`})),v){const E={};for(const A in E){const B=E[A];B!==void 0&&(x[A]=B)}}return f&&m.push({type:"unsupported",feature:"language",details:`OpenAI speech models do not support language selection. Language parameter "${f}" was ignored.`}),{requestBody:x,warnings:m}}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:g}=await this.getArgs(t),{value:m,responseHeaders:v,rawValue:x}=await Un({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),body:f,failedResponseHandler:En,successfulResponseHandler:tm(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:m,warnings:g,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:v,body:x}}}},T2=Pe(()=>Me(T({text:_(),language:_().nullish(),duration:q().nullish(),words:fe(T({word:_(),start:q(),end:q()})).nullish(),segments:fe(T({id:q(),seek:q(),start:q(),end:q(),text:_(),tokens:fe(q()),temperature:q(),avg_logprob:q(),compression_ratio:q(),no_speech_prob:q()})).nullish()}))),N2=Pe(()=>Me(T({include:fe(_()).optional(),language:_().optional(),prompt:_().optional(),temperature:q().min(0).max(1).default(0).optional(),timestampGranularities:fe(Re(["word","segment"])).default(["segment"]).optional()}))),Ba={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"},O2=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 Fn({provider:"openai",providerOptions:o,schema:N2}),f=new FormData,g=t instanceof Uint8Array?new Blob([t]):new Blob([Vo(t)]);f.append("model",this.modelId);const m=eg(r);if(f.append("file",new File([g],"audio",{type:r}),`audio.${m}`),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,g,m,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:B,responseHeaders:O,rawValue:R}=await tu({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:bn(this.config.headers(),t.headers),formData:E,failedResponseHandler:En,successfulResponseHandler:cr(T2),abortSignal:t.abortSignal,fetch:this.config.fetch}),D=B.language!=null&&B.language in Ba?Ba[B.language]:void 0;return{text:B.text,segments:(m=(g=(u=B.segments)==null?void 0:u.map(P=>({text:P.text,startSecond:P.start,endSecond:P.end})))!=null?g:(f=B.words)==null?void 0:f.map(P=>({text:P.word,startSecond:P.start,endSecond:P.end})))!=null?m:[],language:D,durationInSeconds:(v=B.duration)!=null?v:void 0,warnings:A,response:{timestamp:x,modelId:this.modelId,headers:O,body:R}}}},k2="3.0.41";function fu(t={}){var r,o;const c=(r=nm(Qp({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>qc({Authorization:`Bearer ${Jp({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${k2}`),g=D=>new lm(D,{provider:`${u}.chat`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),m=D=>new fm(D,{provider:`${u}.completion`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),v=D=>new gm(D,{provider:`${u}.embedding`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),x=D=>new ym(D,{provider:`${u}.image`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),E=D=>new O2(D,{provider:`${u}.transcription`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),A=D=>new S2(D,{provider:`${u}.speech`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch}),B=D=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return O(D)},O=D=>new f2(D,{provider:`${u}.responses`,url:({path:P})=>`${c}${P}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),R=function(D){return B(D)};return R.specificationVersion="v3",R.languageModel=B,R.chat=g,R.completion=m,R.responses=O,R.embedding=v,R.embeddingModel=v,R.textEmbedding=v,R.textEmbeddingModel=v,R.image=x,R.imageModel=x,R.transcription=E,R.transcriptionModel=E,R.speech=A,R.speechModel=A,R.tools=i2,R}fu();const R2={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 M2{constructor(r={}){this.option=r}async traverse(r){const o=y.ref();return this.option.debug&&console.log("【stream-debug】 响应对象体:",o),(async()=>{let u,f,g,m,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=y.reactive({running:!0,steps:[]}),o.value=u,this.option.onStart?.(u);break;case"start-step":f=y.reactive({running:!0,contents:[],request:x.request}),u.steps.push(f),this.option.onStep?.(f);break;case"reasoning-start":g=y.reactive({type:"reasoning",id:x.id,running:!0,text:""}),f.contents.push(g),this.option.onReasoning?.(g);break;case"reasoning-delta":g.text+=x.text;break;case"reasoning-end":g.running=!1;break;case"text-start":m=y.reactive({type:"text",id:x.id,running:!0,text:""}),f.contents.push(m),this.option.onText?.(m);break;case"text-delta":m.text+=x.text;break;case"text-end":m.running=!1;break;case"tool-input-start":v=y.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 D2(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 g=t.slice(o,u).trim();g&&r.push({type:"markdown",content:g});const m=t.indexOf("```",u+f);let v;m===-1?(v=t.slice(u+f).trim(),o=t.length):(v=t.slice(u+f,m).trim(),o=m+3),r.push({type:"schema-card",content:v})}return r}class P2{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
|
|
50
|
+
${r}:`]}}function Na({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 Oa(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 lg=Be(()=>Pe(T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w(),logprobs:T({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(ht(w(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}))),cg=Be(()=>Pe(Qe([T({id:w().nullish(),created:j().nullish(),model:w().nullish(),choices:ue(T({text:w(),finish_reason:w().nullish(),index:j(),logprobs:T({tokens:ue(w()),token_logprobs:ue(j()),top_logprobs:ue(ht(w(),j())).nullish()}).nullish()})),usage:T({prompt_tokens:j(),completion_tokens:j(),total_tokens:j()}).nullish()}),Yo]))),ka=Be(()=>Pe(T({echo:Rt().optional(),logitBias:ht(w(),j()).optional(),suffix:w().optional(),user:w().optional(),logprobs:Qe([Rt(),j()]).optional()}))),ug=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:C,tools:x,toolChoice:A,seed:v,providerOptions:P}){const O=[],M={...await Vn({provider:"openai",providerOptions:P,schema:ka}),...await Vn({provider:this.providerOptionsName,providerOptions:P,schema:ka})};u!=null&&O.push({type:"unsupported",feature:"topK"}),x?.length&&O.push({type:"unsupported",feature:"tools"}),A!=null&&O.push({type:"unsupported",feature:"toolChoice"}),C!=null&&C.type!=="text"&&O.push({type:"unsupported",feature:"responseFormat",details:"JSON response format is not supported."});const{prompt:D,stopSequences:B}=ag({prompt:t}),G=[...B??[],...g??[]];return{args:{model:this.modelId,echo:M.echo,logit_bias:M.logitBias,logprobs:M?.logprobs===!0?0:M?.logprobs===!1?void 0:M?.logprobs,suffix:M.suffix,user:M.user,max_tokens:r,temperature:o,top_p:c,frequency_penalty:f,presence_penalty:m,seed:v,prompt:D,stop:G.length>0?G:void 0},warnings:O}}async doGenerate(t){var r;const{args:o,warnings:c}=await this.getArgs(t),{responseHeaders:u,value:f,rawValue:m}=await Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:o,failedResponseHandler:An,successfulResponseHandler:hr(lg),abortSignal:t.abortSignal,fetch:this.config.fetch}),g=f.choices[0],C={openai:{}};return g.logprobs!=null&&(C.openai.logprobs=g.logprobs),{content:[{type:"text",text:g.text}],usage:Ta(f.usage),finishReason:{unified:Oa(g.finish_reason),raw:(r=g.finish_reason)!=null?r:void 0},request:{body:o},response:{...Na(f),headers:u,body:m},providerMetadata:C,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 Zn({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:c,failedResponseHandler:An,successfulResponseHandler:qo(cg),abortSignal:t.abortSignal,fetch:this.config.fetch});let m={unified:"other",raw:void 0};const g={openai:{}};let C,x=!0;return{stream:f.pipeThrough(new TransformStream({start(A){A.enqueue({type:"stream-start",warnings:o})},transform(A,v){if(t.includeRawChunks&&v.enqueue({type:"raw",rawValue:A.rawValue}),!A.success){m={unified:"error",raw:void 0},v.enqueue({type:"error",error:A.error});return}const P=A.value;if("error"in P){m={unified:"error",raw:void 0},v.enqueue({type:"error",error:P.error});return}x&&(x=!1,v.enqueue({type:"response-metadata",...Na(P)}),v.enqueue({type:"text-start",id:"0"})),P.usage!=null&&(C=P.usage);const O=P.choices[0];O?.finish_reason!=null&&(m={unified:Oa(O.finish_reason),raw:O.finish_reason}),O?.logprobs!=null&&(g.openai.logprobs=O.logprobs),O?.text!=null&&O.text.length>0&&v.enqueue({type:"text-delta",id:"0",delta:O.text})},flush(A){x||A.enqueue({type:"text-end",id:"0"}),A.enqueue({type:"finish",finishReason:m,providerMetadata:g,usage:Ta(C)})}})),request:{body:c},response:{headers:u}}}},dg=Be(()=>Pe(T({dimensions:j().optional(),user:w().optional()}))),fg=Be(()=>Pe(T({data:ue(T({embedding:ue(j())})),usage:T({prompt_tokens:j()}).nullish()}))),hg=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 kp({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});const f=(u=await Vn({provider:"openai",providerOptions:c,schema:dg}))!=null?u:{},{responseHeaders:m,value:g,rawValue:C}=await Zn({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:An,successfulResponseHandler:hr(fg),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:C}}}},Ra=Be(()=>Pe(T({created:j().nullish(),data:ue(T({b64_json:w(),revised_prompt:w().nullish()})),background:w().nullish(),output_format:w().nullish(),size:w().nullish(),quality:w().nullish(),usage:T({input_tokens:j().nullish(),output_tokens:j().nullish(),total_tokens:j().nullish(),input_tokens_details:T({image_tokens:j().nullish(),text_tokens:j().nullish()}).nullish()}).nullish()}))),pg={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"chatgpt-image-latest":10},mg=["chatgpt-image-","gpt-image-1-mini","gpt-image-1.5","gpt-image-1"];function gg(t){return mg.some(r=>t.startsWith(r))}var xg=class{constructor(t,r){this.modelId=t,this.config=r,this.specificationVersion="v3"}get maxImagesPerCall(){var t;return(t=pg[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:C,abortSignal:x}){var A,v,P,O,M,D,B,G,Z,U,Q;const K=[];f!=null&&K.push({type:"unsupported",feature:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),m!=null&&K.push({type:"unsupported",feature:"seed"});const V=(P=(v=(A=this.config._internal)==null?void 0:A.currentDate)==null?void 0:v.call(A))!=null?P:new Date;if(r!=null){const{value:S,responseHeaders:Te}=await su({url:this.config.url({path:"/images/edits",modelId:this.modelId}),headers:En(this.config.headers(),C),formData:Up({model:this.modelId,prompt:t,image:await Promise.all(r.map(ye=>ye.type==="file"?new Blob([ye.data instanceof Uint8Array?new Blob([ye.data],{type:ye.mediaType}):new Blob([Wo(ye.data)],{type:ye.mediaType})],{type:ye.mediaType}):Jc(ye.url))),mask:o!=null?await yg(o):void 0,n:c,size:u,...(O=g.openai)!=null?O:{}}),failedResponseHandler:An,successfulResponseHandler:hr(Ra),abortSignal:x,fetch:this.config.fetch});return{images:S.data.map(ye=>ye.b64_json),warnings:K,usage:S.usage!=null?{inputTokens:(M=S.usage.input_tokens)!=null?M:void 0,outputTokens:(D=S.usage.output_tokens)!=null?D:void 0,totalTokens:(B=S.usage.total_tokens)!=null?B:void 0}:void 0,response:{timestamp:V,modelId:this.modelId,headers:Te},providerMetadata:{openai:{images:S.data.map((ye,re)=>{var xe,Me,$,ge,ne,J;return{...ye.revised_prompt?{revisedPrompt:ye.revised_prompt}:{},created:(xe=S.created)!=null?xe:void 0,size:(Me=S.size)!=null?Me:void 0,quality:($=S.quality)!=null?$:void 0,background:(ge=S.background)!=null?ge:void 0,outputFormat:(ne=S.output_format)!=null?ne:void 0,...Ma((J=S.usage)==null?void 0:J.input_tokens_details,re,S.data.length)}})}}}}const{value:z,responseHeaders:te}=await Zn({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:En(this.config.headers(),C),body:{model:this.modelId,prompt:t,n:c,size:u,...(G=g.openai)!=null?G:{},...gg(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:An,successfulResponseHandler:hr(Ra),abortSignal:x,fetch:this.config.fetch});return{images:z.data.map(S=>S.b64_json),warnings:K,usage:z.usage!=null?{inputTokens:(Z=z.usage.input_tokens)!=null?Z:void 0,outputTokens:(U=z.usage.output_tokens)!=null?U:void 0,totalTokens:(Q=z.usage.total_tokens)!=null?Q:void 0}:void 0,response:{timestamp:V,modelId:this.modelId,headers:te},providerMetadata:{openai:{images:z.data.map((S,Te)=>{var ye,re,xe,Me,$,ge;return{...S.revised_prompt?{revisedPrompt:S.revised_prompt}:{},created:(ye=z.created)!=null?ye:void 0,size:(re=z.size)!=null?re:void 0,quality:(xe=z.quality)!=null?xe:void 0,background:(Me=z.background)!=null?Me:void 0,outputFormat:($=z.output_format)!=null?$:void 0,...Ma((ge=z.usage)==null?void 0:ge.input_tokens_details,Te,z.data.length)}})}}}}};function Ma(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 yg(t){if(!t)return;if(t.type==="url")return Jc(t.url);const r=t.data instanceof Uint8Array?t.data:Wo(t.data);return new Blob([r],{type:t.mediaType})}var cu=Be(()=>Pe(T({callId:w(),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}))),uu=Be(()=>Pe(T({status:Se(["completed","failed"]),output:w().optional()}))),wg=Dn({id:"openai.apply_patch",inputSchema:cu,outputSchema:uu}),_g=wg,vg=Be(()=>Pe(T({code:w().nullish(),containerId:w()}))),Cg=Be(()=>Pe(T({outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullish()}))),bg=Be(()=>Pe(T({container:Qe([w(),T({fileIds:ue(w()).optional()})]).optional()}))),Eg=Dn({id:"openai.code_interpreter",inputSchema:vg,outputSchema:Cg}),Ag=(t={})=>Eg(t),Ig=Be(()=>Pe(T({name:w(),description:w().optional(),format:Qe([T({type:X("grammar"),syntax:Se(["regex","lark"]),definition:w()}),T({type:X("text")})]).optional()}))),Sg=Be(()=>Pe(w())),Tg=Km({id:"openai.custom",inputSchema:Sg}),Ng=t=>Tg(t),du=T({key:w(),type:Se(["eq","ne","gt","gte","lt","lte","in","nin"]),value:Qe([w(),j(),Rt(),ue(w())])}),fu=T({type:Se(["and","or"]),filters:ue(Qe([du,$o(()=>fu)]))}),Og=Be(()=>Pe(T({vectorStoreIds:ue(w()),maxNumResults:j().optional(),ranking:T({ranker:w().optional(),scoreThreshold:j().optional()}).optional(),filters:Qe([du,fu]).optional()}))),kg=Be(()=>Pe(T({queries:ue(w()),results:ue(T({attributes:ht(w(),bn()),fileId:w(),filename:w(),score:j(),text:w()})).nullable()}))),Rg=Dn({id:"openai.file_search",inputSchema:T({}),outputSchema:kg}),Mg=Be(()=>Pe(T({background:Se(["auto","opaque","transparent"]).optional(),inputFidelity:Se(["low","high"]).optional(),inputImageMask:T({fileId:w().optional(),imageUrl:w().optional()}).optional(),model:w().optional(),moderation:Se(["auto"]).optional(),outputCompression:j().int().min(0).max(100).optional(),outputFormat:Se(["png","jpeg","webp"]).optional(),partialImages:j().int().min(0).max(3).optional(),quality:Se(["auto","low","medium","high"]).optional(),size:Se(["1024x1024","1024x1536","1536x1024","auto"]).optional()}).strict())),Dg=Be(()=>Pe(T({}))),Pg=Be(()=>Pe(T({result:w()}))),Bg=Dn({id:"openai.image_generation",inputSchema:Dg,outputSchema:Pg}),Lg=(t={})=>Bg(t),hu=Be(()=>Pe(T({action:T({type:X("exec"),command:ue(w()),timeoutMs:j().optional(),user:w().optional(),workingDirectory:w().optional(),env:ht(w(),w()).optional()})}))),pu=Be(()=>Pe(T({output:w()}))),Fg=Dn({id:"openai.local_shell",inputSchema:hu,outputSchema:pu}),mu=Be(()=>Pe(T({action:T({commands:ue(w()),timeoutMs:j().optional(),maxOutputLength:j().optional()})}))),To=Be(()=>Pe(T({output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exitCode:j()})])}))}))),Ug=ue(ut("type",[T({type:X("skillReference"),skillId:w(),version:w().optional()}),T({type:X("inline"),name:w(),description:w(),source:T({type:X("base64"),mediaType:X("application/zip"),data:w()})})])).optional(),zg=Be(()=>Pe(T({environment:Qe([T({type:X("containerAuto"),fileIds:ue(w()).optional(),memoryLimit:Se(["1g","4g","16g","64g"]).optional(),networkPolicy:ut("type",[T({type:X("disabled")}),T({type:X("allowlist"),allowedDomains:ue(w()),domainSecrets:ue(T({domain:w(),name:w(),value:w()})).optional()})]).optional(),skills:Ug}),T({type:X("containerReference"),containerId:w()}),T({type:X("local").optional(),skills:ue(T({name:w(),description:w(),path:w()})).optional()})]).optional()}))),Vg=Dn({id:"openai.shell",inputSchema:mu,outputSchema:To}),Zg=Be(()=>Pe(T({execution:Se(["server","client"]).optional(),description:w().optional(),parameters:ht(w(),bn()).optional()}))),No=Be(()=>Pe(T({arguments:bn().optional(),call_id:w().nullish()}))),Oo=Be(()=>Pe(T({tools:ue(ht(w(),bn()))}))),$g=Dn({id:"openai.tool_search",inputSchema:No,outputSchema:Oo}),Hg=(t={})=>$g(t),Wg=Be(()=>Pe(T({externalWebAccess:Rt().optional(),filters:T({allowedDomains:ue(w()).optional()}).optional(),searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:X("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),jg=Be(()=>Pe(T({}))),Gg=Be(()=>Pe(T({action:ut("type",[T({type:X("search"),query:w().optional()}),T({type:X("openPage"),url:w().nullish()}),T({type:X("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).optional()}))),Xg=Dn({id:"openai.web_search",inputSchema:jg,outputSchema:Gg}),qg=(t={})=>Xg(t),Yg=Be(()=>Pe(T({searchContextSize:Se(["low","medium","high"]).optional(),userLocation:T({type:X("approximate"),country:w().optional(),city:w().optional(),region:w().optional(),timezone:w().optional()}).optional()}))),Kg=Be(()=>Pe(T({}))),Jg=Be(()=>Pe(T({action:ut("type",[T({type:X("search"),query:w().optional()}),T({type:X("openPage"),url:w().nullish()}),T({type:X("findInPage"),url:w().nullish(),pattern:w().nullish()})]).optional()}))),Qg=Dn({id:"openai.web_search_preview",inputSchema:Kg,outputSchema:Jg}),ko=$o(()=>Qe([w(),j(),Rt(),mc(),ue(ko),ht(w(),ko)])),e2=Be(()=>Pe(T({serverLabel:w(),allowedTools:Qe([ue(w()),T({readOnly:Rt().optional(),toolNames:ue(w()).optional()})]).optional(),authorization:w().optional(),connectorId:w().optional(),headers:ht(w(),w()).optional(),requireApproval:Qe([Se(["always","never"]),T({never:T({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."))),t2=Be(()=>Pe(T({}))),n2=Be(()=>Pe(T({type:X("call"),serverLabel:w(),name:w(),arguments:w(),output:w().nullish(),error:Qe([w(),ko]).optional()}))),r2=Dn({id:"openai.mcp",inputSchema:t2,outputSchema:n2}),i2=t=>r2(t),o2={applyPatch:_g,customTool:Ng,codeInterpreter:Ag,fileSearch:Rg,imageGeneration:Lg,localShell:Fg,shell:Vg,webSearchPreview:Qg,webSearch:qg,mcp:i2,toolSearch:Hg};function Da(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,C=(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-C,reasoning:C},raw:t}}function Pa(t,r){return r?r.some(o=>t.startsWith(o)):!1}async function s2({prompt:t,toolNameMapping:r,systemMessageMode:o,providerOptionsName:c,fileIdPrefixes:u,store:f,hasConversation:m=!1,hasLocalShellTool:g=!1,hasShellTool:C=!1,hasApplyPatchTool:x=!1,customProviderToolNames:A}){var v,P,O,M,D,B,G,Z,U,Q,K,V,z,te,S,Te,ye;let re=[];const xe=[],Me=new Set;for(const{role:$,content:ge}of t)switch($){case"system":{switch(o){case"system":{re.push({role:"system",content:ge});break}case"developer":{re.push({role:"developer",content:ge});break}case"remove":{xe.push({type:"other",message:"system messages are removed for this model"});break}default:{const ne=o;throw new Error(`Unsupported system message mode: ${ne}`)}}break}case"user":{re.push({role:"user",content:ge.map((ne,J)=>{var me,fe,ie;switch(ne.type){case"text":return{type:"input_text",text:ne.text};case"file":if(ne.mediaType.startsWith("image/")){const pe=ne.mediaType==="image/*"?"image/jpeg":ne.mediaType;return{type:"input_image",...ne.data instanceof URL?{image_url:ne.data.toString()}:typeof ne.data=="string"&&Pa(ne.data,u)?{file_id:ne.data}:{image_url:`data:${pe};base64,${Tr(ne.data)}`},detail:(fe=(me=ne.providerOptions)==null?void 0:me[c])==null?void 0:fe.imageDetail}}else{if(ne.mediaType==="application/pdf")return ne.data instanceof URL?{type:"input_file",file_url:ne.data.toString()}:{type:"input_file",...typeof ne.data=="string"&&Pa(ne.data,u)?{file_id:ne.data}:{filename:(ie=ne.filename)!=null?ie:`part-${J}.pdf`,file_data:`data:application/pdf;base64,${Tr(ne.data)}`}};throw new zn({functionality:`file part media type ${ne.mediaType}`})}}})});break}case"assistant":{const ne={};for(const J of ge)switch(J.type){case"text":{const me=(v=J.providerOptions)==null?void 0:v[c],fe=me?.itemId,ie=me?.phase;if(m&&fe!=null)break;if(f&&fe!=null){re.push({type:"item_reference",id:fe});break}re.push({role:"assistant",content:[{type:"output_text",text:J.text}],id:fe,...ie!=null&&{phase:ie}});break}case"tool-call":{const me=(B=(O=(P=J.providerOptions)==null?void 0:P[c])==null?void 0:O.itemId)!=null?B:(D=(M=J.providerMetadata)==null?void 0:M[c])==null?void 0:D.itemId;if(m&&me!=null)break;const fe=r.toProviderToolName(J.toolName);if(fe==="tool_search"){if(f&&me!=null){re.push({type:"item_reference",id:me});break}const ie=typeof J.input=="string"?await iu({text:J.input,schema:No}):await kt({value:J.input,schema:No}),pe=ie.call_id!=null?"client":"server";re.push({type:"tool_search_call",id:me??J.toolCallId,execution:pe,call_id:(G=ie.call_id)!=null?G:null,status:"completed",arguments:ie.arguments});break}if(J.providerExecuted){f&&me!=null&&re.push({type:"item_reference",id:me});break}if(f&&me!=null){re.push({type:"item_reference",id:me});break}if(g&&fe==="local_shell"){const ie=await kt({value:J.input,schema:hu});re.push({type:"local_shell_call",call_id:J.toolCallId,id:me,action:{type:"exec",command:ie.action.command,timeout_ms:ie.action.timeoutMs,user:ie.action.user,working_directory:ie.action.workingDirectory,env:ie.action.env}});break}if(C&&fe==="shell"){const ie=await kt({value:J.input,schema:mu});re.push({type:"shell_call",call_id:J.toolCallId,id:me,status:"completed",action:{commands:ie.action.commands,timeout_ms:ie.action.timeoutMs,max_output_length:ie.action.maxOutputLength}});break}if(x&&fe==="apply_patch"){const ie=await kt({value:J.input,schema:cu});re.push({type:"apply_patch_call",call_id:ie.callId,id:me,status:"completed",operation:ie.operation});break}if(A?.has(fe)){re.push({type:"custom_tool_call",call_id:J.toolCallId,name:fe,input:typeof J.input=="string"?J.input:JSON.stringify(J.input),id:me});break}re.push({type:"function_call",call_id:J.toolCallId,name:fe,arguments:JSON.stringify(J.input),id:me});break}case"tool-result":{if(J.output.type==="execution-denied"||J.output.type==="json"&&typeof J.output.value=="object"&&J.output.value!=null&&"type"in J.output.value&&J.output.value.type==="execution-denied"||m)break;const me=r.toProviderToolName(J.toolName);if(me==="tool_search"){const fe=(Q=(U=(Z=J.providerOptions)==null?void 0:Z[c])==null?void 0:U.itemId)!=null?Q:J.toolCallId;if(f)re.push({type:"item_reference",id:fe});else if(J.output.type==="json"){const ie=await kt({value:J.output.value,schema:Oo});re.push({type:"tool_search_output",id:fe,execution:"server",call_id:null,status:"completed",tools:ie.tools})}break}if(C&&me==="shell"){if(J.output.type==="json"){const fe=await kt({value:J.output.value,schema:To});re.push({type:"shell_call_output",call_id:J.toolCallId,output:fe.output.map(ie=>({stdout:ie.stdout,stderr:ie.stderr,outcome:ie.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:ie.outcome.exitCode}}))})}break}if(f){const fe=(z=(V=(K=J.providerOptions)==null?void 0:K[c])==null?void 0:V.itemId)!=null?z:J.toolCallId;re.push({type:"item_reference",id:fe})}else xe.push({type:"other",message:`Results for OpenAI tool ${J.toolName} are not sent to the API when store is false`});break}case"reasoning":{const me=await Vn({provider:c,providerOptions:J.providerOptions,schema:a2}),fe=me?.itemId;if(m&&fe!=null)break;if(fe!=null){const ie=ne[fe];if(f)ie===void 0&&(re.push({type:"item_reference",id:fe}),ne[fe]={type:"reasoning",id:fe,summary:[]});else{const pe=[];J.text.length>0?pe.push({type:"summary_text",text:J.text}):ie!==void 0&&xe.push({type:"other",message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(J)}.`}),ie===void 0?(ne[fe]={type:"reasoning",id:fe,encrypted_content:me?.reasoningEncryptedContent,summary:pe},re.push(ne[fe])):(ie.summary.push(...pe),me?.reasoningEncryptedContent!=null&&(ie.encrypted_content=me.reasoningEncryptedContent))}}else{const ie=me?.reasoningEncryptedContent;if(ie!=null){const pe=[];J.text.length>0&&pe.push({type:"summary_text",text:J.text}),re.push({type:"reasoning",encrypted_content:ie,summary:pe})}else xe.push({type:"other",message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(J)}.`})}break}}break}case"tool":{for(const ne of ge){if(ne.type==="tool-approval-response"){const ie=ne;if(Me.has(ie.approvalId))continue;Me.add(ie.approvalId),f&&re.push({type:"item_reference",id:ie.approvalId}),re.push({type:"mcp_approval_response",approval_request_id:ie.approvalId,approve:ie.approved});continue}const J=ne.output;if(J.type==="execution-denied"&&((S=(te=J.providerOptions)==null?void 0:te.openai)==null?void 0:S.approvalId))continue;const me=r.toProviderToolName(ne.toolName);if(me==="tool_search"&&J.type==="json"){const ie=await kt({value:J.value,schema:Oo});re.push({type:"tool_search_output",execution:"client",call_id:ne.toolCallId,status:"completed",tools:ie.tools});continue}if(g&&me==="local_shell"&&J.type==="json"){const ie=await kt({value:J.value,schema:pu});re.push({type:"local_shell_call_output",call_id:ne.toolCallId,output:ie.output});continue}if(C&&me==="shell"&&J.type==="json"){const ie=await kt({value:J.value,schema:To});re.push({type:"shell_call_output",call_id:ne.toolCallId,output:ie.output.map(pe=>({stdout:pe.stdout,stderr:pe.stderr,outcome:pe.outcome.type==="timeout"?{type:"timeout"}:{type:"exit",exit_code:pe.outcome.exitCode}}))});continue}if(x&&ne.toolName==="apply_patch"&&J.type==="json"){const ie=await kt({value:J.value,schema:uu});re.push({type:"apply_patch_call_output",call_id:ne.toolCallId,status:ie.status,output:ie.output});continue}if(A?.has(me)){let ie;switch(J.type){case"text":case"error-text":ie=J.value;break;case"execution-denied":ie=(Te=J.reason)!=null?Te:"Tool execution denied.";break;case"json":case"error-json":ie=JSON.stringify(J.value);break;case"content":ie=J.value.map(pe=>{var vt;switch(pe.type){case"text":return{type:"input_text",text:pe.text};case"image-data":return{type:"input_image",image_url:`data:${pe.mediaType};base64,${pe.data}`};case"image-url":return{type:"input_image",image_url:pe.url};case"file-data":return{type:"input_file",filename:(vt=pe.filename)!=null?vt:"data",file_data:`data:${pe.mediaType};base64,${pe.data}`};case"file-url":return{type:"input_file",file_url:pe.url};default:xe.push({type:"other",message:`unsupported custom tool content part type: ${pe.type}`});return}}).filter(va);break;default:ie=""}re.push({type:"custom_tool_call_output",call_id:ne.toolCallId,output:ie});continue}let fe;switch(J.type){case"text":case"error-text":fe=J.value;break;case"execution-denied":fe=(ye=J.reason)!=null?ye:"Tool execution denied.";break;case"json":case"error-json":fe=JSON.stringify(J.value);break;case"content":fe=J.value.map(ie=>{var pe;switch(ie.type){case"text":return{type:"input_text",text:ie.text};case"image-data":return{type:"input_image",image_url:`data:${ie.mediaType};base64,${ie.data}`};case"image-url":return{type:"input_image",image_url:ie.url};case"file-data":return{type:"input_file",filename:(pe=ie.filename)!=null?pe:"data",file_data:`data:${ie.mediaType};base64,${ie.data}`};case"file-url":return{type:"input_file",file_url:ie.url};default:{xe.push({type:"other",message:`unsupported tool content part type: ${ie.type}`});return}}}).filter(va);break}re.push({type:"function_call_output",call_id:ne.toolCallId,output:fe})}break}default:{const ne=$;throw new Error(`Unsupported role: ${ne}`)}}return!f&&re.some($=>"type"in $&&$.type==="reasoning"&&$.encrypted_content==null)&&(xe.push({type:"other",message:"Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts."}),re=re.filter($=>!("type"in $)||$.type!=="reasoning"||$.encrypted_content!=null)),{input:re,warnings:xe}}var a2=T({itemId:w().nullish(),reasoningEncryptedContent:w().nullish()});function fo({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(()=>Qe([w(),j(),Rt(),mc(),ue(ei),ht(w(),ei.optional())])),l2=Be(()=>Pe(Qe([T({type:X("response.output_text.delta"),item_id:w(),delta:w(),logprobs:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish()}),T({type:Se(["response.completed","response.incomplete"]),response:T({incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}),service_tier:w().nullish()})}),T({type:X("response.failed"),response:T({error:T({code:w().nullish(),message:w()}).nullish(),incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).nullish(),service_tier:w().nullish()})}),T({type:X("response.created"),response:T({id:w(),created_at:j(),model:w(),service_tier:w().nullish()})}),T({type:X("response.output_item.added"),output_index:j(),item:ut("type",[T({type:X("message"),id:w(),phase:Se(["commentary","final_answer"]).nullish()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish()}),T({type:X("function_call"),id:w(),call_id:w(),name:w(),arguments:w()}),T({type:X("web_search_call"),id:w(),status:w()}),T({type:X("computer_call"),id:w(),status:w()}),T({type:X("file_search_call"),id:w()}),T({type:X("image_generation_call"),id:w()}),T({type:X("code_interpreter_call"),id:w(),container_id:w(),code:w().nullable(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable(),status:w()}),T({type:X("mcp_call"),id:w(),status:w(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w()}),T({type:X("mcp_approval_request"),id:w()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w()}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),ei.optional()))})])}),T({type:X("response.output_item.done"),output_index:j(),item:ut("type",[T({type:X("message"),id:w(),phase:Se(["commentary","final_answer"]).nullish()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish()}),T({type:X("function_call"),id:w(),call_id:w(),name:w(),arguments:w(),status:X("completed")}),T({type:X("custom_tool_call"),id:w(),call_id:w(),name:w(),input:w(),status:X("completed")}),T({type:X("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable()}),T({type:X("image_generation_call"),id:w(),result:w()}),T({type:X("web_search_call"),id:w(),status:w(),action:ut("type",[T({type:X("search"),query:w().nullish(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).nullish()}),T({type:X("open_page"),url:w().nullish()}),T({type:X("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),T({type:X("file_search_call"),id:w(),queries:ue(w()),results:ue(T({attributes:ht(w(),Qe([w(),j(),Rt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),T({type:X("local_shell_call"),id:w(),call_id:w(),action:T({type:X("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:ht(w(),w()).optional()})}),T({type:X("computer_call"),id:w(),status:X("completed")}),T({type:X("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w(),server_label:w(),tools:ue(T({name:w(),description:w().optional(),input_schema:mr(),annotations:ht(w(),bn()).optional()})),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),T({type:X("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),ei.optional()))})])}),T({type:X("response.function_call_arguments.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.custom_tool_call_input.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.image_generation_call.partial_image"),item_id:w(),output_index:j(),partial_image_b64:w()}),T({type:X("response.code_interpreter_call_code.delta"),item_id:w(),output_index:j(),delta:w()}),T({type:X("response.code_interpreter_call_code.done"),item_id:w(),output_index:j(),code:w()}),T({type:X("response.output_text.annotation.added"),annotation:ut("type",[T({type:X("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),T({type:X("file_citation"),file_id:w(),filename:w(),index:j()}),T({type:X("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),T({type:X("file_path"),file_id:w(),index:j()})])}),T({type:X("response.reasoning_summary_part.added"),item_id:w(),summary_index:j()}),T({type:X("response.reasoning_summary_text.delta"),item_id:w(),summary_index:j(),delta:w()}),T({type:X("response.reasoning_summary_part.done"),item_id:w(),summary_index:j()}),T({type:X("response.apply_patch_call_operation_diff.delta"),item_id:w(),output_index:j(),delta:w(),obfuscation:w().nullish()}),T({type:X("response.apply_patch_call_operation_diff.done"),item_id:w(),output_index:j(),diff:w()}),T({type:X("error"),sequence_number:j(),error:T({type:w(),code:w(),message:w(),param:w().nullish()})}),T({type:w()}).loose().transform(t=>({type:"unknown_chunk",message:t.type}))]))),c2=Be(()=>Pe(T({id:w().optional(),created_at:j().optional(),error:T({message:w(),type:w(),param:w().nullish(),code:w()}).nullish(),model:w().optional(),output:ue(ut("type",[T({type:X("message"),role:X("assistant"),id:w(),phase:Se(["commentary","final_answer"]).nullish(),content:ue(T({type:X("output_text"),text:w(),logprobs:ue(T({token:w(),logprob:j(),top_logprobs:ue(T({token:w(),logprob:j()}))})).nullish(),annotations:ue(ut("type",[T({type:X("url_citation"),start_index:j(),end_index:j(),url:w(),title:w()}),T({type:X("file_citation"),file_id:w(),filename:w(),index:j()}),T({type:X("container_file_citation"),container_id:w(),file_id:w(),filename:w(),start_index:j(),end_index:j()}),T({type:X("file_path"),file_id:w(),index:j()})]))}))}),T({type:X("web_search_call"),id:w(),status:w(),action:ut("type",[T({type:X("search"),query:w().nullish(),sources:ue(ut("type",[T({type:X("url"),url:w()}),T({type:X("api"),name:w()})])).nullish()}),T({type:X("open_page"),url:w().nullish()}),T({type:X("find_in_page"),url:w().nullish(),pattern:w().nullish()})]).nullish()}),T({type:X("file_search_call"),id:w(),queries:ue(w()),results:ue(T({attributes:ht(w(),Qe([w(),j(),Rt()])),file_id:w(),filename:w(),score:j(),text:w()})).nullish()}),T({type:X("code_interpreter_call"),id:w(),code:w().nullable(),container_id:w(),outputs:ue(ut("type",[T({type:X("logs"),logs:w()}),T({type:X("image"),url:w()})])).nullable()}),T({type:X("image_generation_call"),id:w(),result:w()}),T({type:X("local_shell_call"),id:w(),call_id:w(),action:T({type:X("exec"),command:ue(w()),timeout_ms:j().optional(),user:w().optional(),working_directory:w().optional(),env:ht(w(),w()).optional()})}),T({type:X("function_call"),call_id:w(),name:w(),arguments:w(),id:w()}),T({type:X("custom_tool_call"),call_id:w(),name:w(),input:w(),id:w()}),T({type:X("computer_call"),id:w(),status:w().optional()}),T({type:X("reasoning"),id:w(),encrypted_content:w().nullish(),summary:ue(T({type:X("summary_text"),text:w()}))}),T({type:X("mcp_call"),id:w(),status:w(),arguments:w(),name:w(),server_label:w(),output:w().nullish(),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).nullish(),approval_request_id:w().nullish()}),T({type:X("mcp_list_tools"),id:w(),server_label:w(),tools:ue(T({name:w(),description:w().optional(),input_schema:mr(),annotations:ht(w(),bn()).optional()})),error:Qe([w(),T({type:w().optional(),code:Qe([j(),w()]).optional(),message:w().optional()}).loose()]).optional()}),T({type:X("mcp_approval_request"),id:w(),server_label:w(),name:w(),arguments:w(),approval_request_id:w().optional()}),T({type:X("apply_patch_call"),id:w(),call_id:w(),status:Se(["in_progress","completed"]),operation:ut("type",[T({type:X("create_file"),path:w(),diff:w()}),T({type:X("delete_file"),path:w()}),T({type:X("update_file"),path:w(),diff:w()})])}),T({type:X("shell_call"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),action:T({commands:ue(w())})}),T({type:X("shell_call_output"),id:w(),call_id:w(),status:Se(["in_progress","completed","incomplete"]),output:ue(T({stdout:w(),stderr:w(),outcome:ut("type",[T({type:X("timeout")}),T({type:X("exit"),exit_code:j()})])}))}),T({type:X("tool_search_call"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),arguments:bn()}),T({type:X("tool_search_output"),id:w(),execution:Se(["server","client"]),call_id:w().nullable(),status:Se(["in_progress","completed","incomplete"]),tools:ue(ht(w(),ei.optional()))})])).optional(),service_tier:w().nullish(),incomplete_details:T({reason:w()}).nullish(),usage:T({input_tokens:j(),input_tokens_details:T({cached_tokens:j().nullish()}).nullish(),output_tokens:j(),output_tokens_details:T({reasoning_tokens:j().nullish()}).nullish()}).optional()}))),gu=20,Ba=Be(()=>Pe(T({conversation:w().nullish(),include:ue(Se(["reasoning.encrypted_content","file_search_call.results","message.output_text.logprobs"])).nullish(),instructions:w().nullish(),logprobs:Qe([Rt(),j().min(1).max(gu)]).optional(),maxToolCalls:j().nullish(),metadata:mr().nullish(),parallelToolCalls:Rt().nullish(),previousResponseId:w().nullish(),promptCacheKey:w().nullish(),promptCacheRetention:Se(["in_memory","24h"]).nullish(),reasoningEffort:w().nullish(),reasoningSummary:w().nullish(),safetyIdentifier:w().nullish(),serviceTier:Se(["auto","flex","priority","default"]).nullish(),store:Rt().nullish(),strictJsonSchema:Rt().nullish(),textVerbosity:Se(["low","medium","high"]).nullish(),truncation:Se(["auto","disabled"]).nullish(),user:w().nullish(),systemMessageMode:Se(["system","developer","remove"]).optional(),forceReasoning:Rt().optional()})));async function u2({tools:t,toolChoice:r,toolNameMapping:o,customProviderToolNames:c}){var u,f;t=t?.length?t:void 0;const m=[];if(t==null)return{tools:void 0,toolChoice:void 0,toolWarnings:m};const g=[],C=c??new Set;for(const A of t)switch(A.type){case"function":{const v=(u=A.providerOptions)==null?void 0:u.openai,P=v?.deferLoading;g.push({type:"function",name:A.name,description:A.description,parameters:A.inputSchema,...A.strict!=null?{strict:A.strict}:{},...P!=null?{defer_loading:P}:{}});break}case"provider":{switch(A.id){case"openai.file_search":{const v=await kt({value:A.args,schema:Og});g.push({type:"file_search",vector_store_ids:v.vectorStoreIds,max_num_results:v.maxNumResults,ranking_options:v.ranking?{ranker:v.ranking.ranker,score_threshold:v.ranking.scoreThreshold}:void 0,filters:v.filters});break}case"openai.local_shell":{g.push({type:"local_shell"});break}case"openai.shell":{const v=await kt({value:A.args,schema:zg});g.push({type:"shell",...v.environment&&{environment:d2(v.environment)}});break}case"openai.apply_patch":{g.push({type:"apply_patch"});break}case"openai.web_search_preview":{const v=await kt({value:A.args,schema:Yg});g.push({type:"web_search_preview",search_context_size:v.searchContextSize,user_location:v.userLocation});break}case"openai.web_search":{const v=await kt({value:A.args,schema:Wg});g.push({type:"web_search",filters:v.filters!=null?{allowed_domains:v.filters.allowedDomains}:void 0,external_web_access:v.externalWebAccess,search_context_size:v.searchContextSize,user_location:v.userLocation});break}case"openai.code_interpreter":{const v=await kt({value:A.args,schema:bg});g.push({type:"code_interpreter",container:v.container==null?{type:"auto",file_ids:void 0}:typeof v.container=="string"?v.container:{type:"auto",file_ids:v.container.fileIds}});break}case"openai.image_generation":{const v=await kt({value:A.args,schema:Mg});g.push({type:"image_generation",background:v.background,input_fidelity:v.inputFidelity,input_image_mask:v.inputImageMask?{file_id:v.inputImageMask.fileId,image_url:v.inputImageMask.imageUrl}:void 0,model:v.model,moderation:v.moderation,partial_images:v.partialImages,quality:v.quality,output_compression:v.outputCompression,output_format:v.outputFormat,size:v.size});break}case"openai.mcp":{const v=await kt({value:A.args,schema:e2}),P=D=>({tool_names:D.toolNames}),O=v.requireApproval,M=O==null?void 0:typeof O=="string"?O:O.never!=null?{never:P(O.never)}:void 0;g.push({type:"mcp",server_label:v.serverLabel,allowed_tools:Array.isArray(v.allowedTools)?v.allowedTools:v.allowedTools?{read_only:v.allowedTools.readOnly,tool_names:v.allowedTools.toolNames}:void 0,authorization:v.authorization,connector_id:v.connectorId,headers:v.headers,require_approval:M??"never",server_description:v.serverDescription,server_url:v.serverUrl});break}case"openai.custom":{const v=await kt({value:A.args,schema:Ig});g.push({type:"custom",name:v.name,description:v.description,format:v.format}),C.add(v.name);break}case"openai.tool_search":{const v=await kt({value:A.args,schema:Zg});g.push({type:"tool_search",...v.execution!=null?{execution:v.execution}:{},...v.description!=null?{description:v.description}:{},...v.parameters!=null?{parameters:v.parameters}:{}});break}}break}default:m.push({type:"unsupported",feature:`function tool ${A}`});break}if(r==null)return{tools:g,toolChoice:void 0,toolWarnings:m};const x=r.type;switch(x){case"auto":case"none":case"required":return{tools:g,toolChoice:x,toolWarnings:m};case"tool":{const A=(f=o?.toProviderToolName(r.toolName))!=null?f:r.toolName;return{tools:g,toolChoice:A==="code_interpreter"||A==="file_search"||A==="image_generation"||A==="web_search_preview"||A==="web_search"||A==="mcp"||A==="apply_patch"?{type:A}:C.has(A)?{type:"custom",name:A}:{type:"function",name:A},toolWarnings:m}}default:{const A=x;throw new zn({functionality:`tool choice type: ${A}`})}}}function d2(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:f2(o.skills)}}return{type:"local",skills:t.skills}}function f2(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 La(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 h2=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:C,providerOptions:x,tools:A,toolChoice:v,responseFormat:P}){var O,M,D,B,G,Z,U,Q,K;const V=[],z=lu(this.modelId);u!=null&&V.push({type:"unsupported",feature:"topK"}),g!=null&&V.push({type:"unsupported",feature:"seed"}),f!=null&&V.push({type:"unsupported",feature:"presencePenalty"}),m!=null&&V.push({type:"unsupported",feature:"frequencyPenalty"}),o!=null&&V.push({type:"unsupported",feature:"stopSequences"});const te=this.config.provider.includes("azure")?"azure":"openai";let S=await Vn({provider:te,providerOptions:x,schema:Ba});S==null&&te!=="openai"&&(S=await Vn({provider:"openai",providerOptions:x,schema:Ba}));const Te=(O=S?.forceReasoning)!=null?O:z.isReasoningModel;S?.conversation&&S?.previousResponseId&&V.push({type:"unsupported",feature:"conversation",details:"conversation and previousResponseId cannot be used together"});const ye=Dp({tools:A,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:Ue=>Ue.id==="openai.custom"?Ue.args.name:void 0}),re=new Set,{tools:xe,toolChoice:Me,toolWarnings:$}=await u2({tools:A,toolChoice:v,toolNameMapping:ye,customProviderToolNames:re}),{input:ge,warnings:ne}=await s2({prompt:C,toolNameMapping:ye,systemMessageMode:(M=S?.systemMessageMode)!=null?M:Te?"developer":z.systemMessageMode,providerOptionsName:te,fileIdPrefixes:this.config.fileIdPrefixes,store:(D=S?.store)!=null?D:!0,hasConversation:S?.conversation!=null,hasLocalShellTool:ie("openai.local_shell"),hasShellTool:ie("openai.shell"),hasApplyPatchTool:ie("openai.apply_patch"),customProviderToolNames:re.size>0?re:void 0});V.push(...ne);const J=(B=S?.strictJsonSchema)!=null?B:!0;let me=S?.include;function fe(Ue){me==null?me=[Ue]:me.includes(Ue)||(me=[...me,Ue])}function ie(Ue){return A?.find(Ht=>Ht.type==="provider"&&Ht.id===Ue)!=null}const pe=typeof S?.logprobs=="number"?S?.logprobs:S?.logprobs===!0?gu:void 0;pe&&fe("message.output_text.logprobs");const vt=(G=A?.find(Ue=>Ue.type==="provider"&&(Ue.id==="openai.web_search"||Ue.id==="openai.web_search_preview")))==null?void 0:G.name;vt&&fe("web_search_call.action.sources"),ie("openai.code_interpreter")&&fe("code_interpreter_call.outputs");const Ee=S?.store;Ee===!1&&Te&&fe("reasoning.encrypted_content");const Tt={model:this.modelId,input:ge,temperature:r,top_p:c,max_output_tokens:t,...(P?.type==="json"||S?.textVerbosity)&&{text:{...P?.type==="json"&&{format:P.schema!=null?{type:"json_schema",strict:J,name:(Z=P.name)!=null?Z:"response",description:P.description,schema:P.schema}:{type:"json_object"}},...S?.textVerbosity&&{verbosity:S.textVerbosity}}},conversation:S?.conversation,max_tool_calls:S?.maxToolCalls,metadata:S?.metadata,parallel_tool_calls:S?.parallelToolCalls,previous_response_id:S?.previousResponseId,store:Ee,user:S?.user,instructions:S?.instructions,service_tier:S?.serviceTier,include:me,prompt_cache_key:S?.promptCacheKey,prompt_cache_retention:S?.promptCacheRetention,safety_identifier:S?.safetyIdentifier,top_logprobs:pe,truncation:S?.truncation,...Te&&(S?.reasoningEffort!=null||S?.reasoningSummary!=null)&&{reasoning:{...S?.reasoningEffort!=null&&{effort:S.reasoningEffort},...S?.reasoningSummary!=null&&{summary:S.reasoningSummary}}}};Te?S?.reasoningEffort==="none"&&z.supportsNonReasoningParameters||(Tt.temperature!=null&&(Tt.temperature=void 0,V.push({type:"unsupported",feature:"temperature",details:"temperature is not supported for reasoning models"})),Tt.top_p!=null&&(Tt.top_p=void 0,V.push({type:"unsupported",feature:"topP",details:"topP is not supported for reasoning models"}))):(S?.reasoningEffort!=null&&V.push({type:"unsupported",feature:"reasoningEffort",details:"reasoningEffort is not supported for non-reasoning models"}),S?.reasoningSummary!=null&&V.push({type:"unsupported",feature:"reasoningSummary",details:"reasoningSummary is not supported for non-reasoning models"})),S?.serviceTier==="flex"&&!z.supportsFlexProcessing&&(V.push({type:"unsupported",feature:"serviceTier",details:"flex processing is only available for o3, o4-mini, and gpt-5 models"}),delete Tt.service_tier),S?.serviceTier==="priority"&&!z.supportsPriorityProcessing&&(V.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 Tt.service_tier);const Ce=(K=(Q=(U=A?.find(Ue=>Ue.type==="provider"&&Ue.id==="openai.shell"))==null?void 0:U.args)==null?void 0:Q.environment)==null?void 0:K.type,sn=Ce==="containerAuto"||Ce==="containerReference";return{webSearchToolName:vt,args:{...Tt,tools:xe,tool_choice:Me},warnings:[...V,...$],store:Ee,toolNameMapping:ye,providerOptionsName:te,isShellProviderExecuted:sn}}async doGenerate(t){var r,o,c,u,f,m,g,C,x,A,v,P,O,M,D,B,G,Z,U,Q,K,V,z,te,S,Te,ye,re;const{args:xe,warnings:Me,webSearchToolName:$,toolNameMapping:ge,providerOptionsName:ne,isShellProviderExecuted:J}=await this.getArgs(t),me=this.config.url({path:"/responses",modelId:this.modelId}),fe=La(t.prompt),{responseHeaders:ie,value:pe,rawValue:vt}=await Zn({url:me,headers:En(this.config.headers(),t.headers),body:xe,failedResponseHandler:An,successfulResponseHandler:hr(c2),abortSignal:t.abortSignal,fetch:this.config.fetch});if(pe.error)throw new cn({message:pe.error.message,url:me,requestBodyValues:xe,statusCode:400,responseHeaders:ie,responseBody:vt,isRetryable:!1});const Ee=[],Tt=[];let Ce=!1;const sn=[];for(const de of pe.output)switch(de.type){case"reasoning":{de.summary.length===0&&de.summary.push({type:"summary_text",text:""});for(const Oe of de.summary)Ee.push({type:"reasoning",text:Oe.text,providerMetadata:{[ne]:{itemId:de.id,reasoningEncryptedContent:(r=de.encrypted_content)!=null?r:null}}});break}case"image_generation_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("image_generation"),result:{result:de.result}});break}case"tool_search_call":{const Oe=(o=de.call_id)!=null?o:de.id,yt=de.execution==="server";yt&&sn.push(Oe),Ee.push({type:"tool-call",toolCallId:Oe,toolName:ge.toCustomToolName("tool_search"),input:JSON.stringify({arguments:de.arguments,call_id:de.call_id}),...yt?{providerExecuted:!0}:{},providerMetadata:{[ne]:{itemId:de.id}}});break}case"tool_search_output":{const Oe=(u=(c=de.call_id)!=null?c:sn.shift())!=null?u:de.id;Ee.push({type:"tool-result",toolCallId:Oe,toolName:ge.toCustomToolName("tool_search"),result:{tools:de.tools},providerMetadata:{[ne]:{itemId:de.id}}});break}case"local_shell_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("local_shell"),input:JSON.stringify({action:de.action}),providerMetadata:{[ne]:{itemId:de.id}}});break}case"shell_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("shell"),input:JSON.stringify({action:{commands:de.action.commands}}),...J&&{providerExecuted:!0},providerMetadata:{[ne]:{itemId:de.id}}});break}case"shell_call_output":{Ee.push({type:"tool-result",toolCallId:de.call_id,toolName:ge.toCustomToolName("shell"),result:{output:de.output.map(Oe=>({stdout:Oe.stdout,stderr:Oe.stderr,outcome:Oe.outcome.type==="exit"?{type:"exit",exitCode:Oe.outcome.exit_code}:{type:"timeout"}}))}});break}case"message":{for(const Oe of de.content){(m=(f=t.providerOptions)==null?void 0:f[ne])!=null&&m.logprobs&&Oe.logprobs&&Tt.push(Oe.logprobs);const yt={itemId:de.id,...de.phase!=null&&{phase:de.phase},...Oe.annotations.length>0&&{annotations:Oe.annotations}};Ee.push({type:"text",text:Oe.text,providerMetadata:{[ne]:yt}});for(const be of Oe.annotations)be.type==="url_citation"?Ee.push({type:"source",sourceType:"url",id:(x=(C=(g=this.config).generateId)==null?void 0:C.call(g))!=null?x:Kt(),url:be.url,title:be.title}):be.type==="file_citation"?Ee.push({type:"source",sourceType:"document",id:(P=(v=(A=this.config).generateId)==null?void 0:v.call(A))!=null?P:Kt(),mediaType:"text/plain",title:be.filename,filename:be.filename,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,index:be.index}}}):be.type==="container_file_citation"?Ee.push({type:"source",sourceType:"document",id:(D=(M=(O=this.config).generateId)==null?void 0:M.call(O))!=null?D:Kt(),mediaType:"text/plain",title:be.filename,filename:be.filename,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,containerId:be.container_id}}}):be.type==="file_path"&&Ee.push({type:"source",sourceType:"document",id:(Z=(G=(B=this.config).generateId)==null?void 0:G.call(B))!=null?Z:Kt(),mediaType:"application/octet-stream",title:be.file_id,filename:be.file_id,providerMetadata:{[ne]:{type:be.type,fileId:be.file_id,index:be.index}}})}break}case"function_call":{Ce=!0,Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:de.name,input:de.arguments,providerMetadata:{[ne]:{itemId:de.id}}});break}case"custom_tool_call":{Ce=!0;const Oe=ge.toCustomToolName(de.name);Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:Oe,input:JSON.stringify(de.input),providerMetadata:{[ne]:{itemId:de.id}}});break}case"web_search_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName($??"web_search"),input:JSON.stringify({}),providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName($??"web_search"),result:Ua(de.action)});break}case"mcp_call":{const Oe=de.approval_request_id!=null&&(U=fe[de.approval_request_id])!=null?U:de.id,yt=`mcp.${de.name}`;Ee.push({type:"tool-call",toolCallId:Oe,toolName:yt,input:de.arguments,providerExecuted:!0,dynamic:!0}),Ee.push({type:"tool-result",toolCallId:Oe,toolName:yt,result:{type:"call",serverLabel:de.server_label,name:de.name,arguments:de.arguments,...de.output!=null?{output:de.output}:{},...de.error!=null?{error:de.error}:{}},providerMetadata:{[ne]:{itemId:de.id}}});break}case"mcp_list_tools":break;case"mcp_approval_request":{const Oe=(Q=de.approval_request_id)!=null?Q:de.id,yt=(z=(V=(K=this.config).generateId)==null?void 0:V.call(K))!=null?z:Kt(),be=`mcp.${de.name}`;Ee.push({type:"tool-call",toolCallId:yt,toolName:be,input:de.arguments,providerExecuted:!0,dynamic:!0}),Ee.push({type:"tool-approval-request",approvalId:Oe,toolCallId:yt});break}case"computer_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:de.status||"completed"}});break}case"file_search_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("file_search"),input:"{}",providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("file_search"),result:{queries:de.queries,results:(S=(te=de.results)==null?void 0:te.map(Oe=>({attributes:Oe.attributes,fileId:Oe.file_id,filename:Oe.filename,score:Oe.score,text:Oe.text})))!=null?S:null}});break}case"code_interpreter_call":{Ee.push({type:"tool-call",toolCallId:de.id,toolName:ge.toCustomToolName("code_interpreter"),input:JSON.stringify({code:de.code,containerId:de.container_id}),providerExecuted:!0}),Ee.push({type:"tool-result",toolCallId:de.id,toolName:ge.toCustomToolName("code_interpreter"),result:{outputs:de.outputs}});break}case"apply_patch_call":{Ee.push({type:"tool-call",toolCallId:de.call_id,toolName:ge.toCustomToolName("apply_patch"),input:JSON.stringify({callId:de.call_id,operation:de.operation}),providerMetadata:{[ne]:{itemId:de.id}}});break}}const Ue={[ne]:{responseId:pe.id,...Tt.length>0?{logprobs:Tt}:{},...typeof pe.service_tier=="string"?{serviceTier:pe.service_tier}:{}}},Ht=pe.usage;return{content:Ee,finishReason:{unified:fo({finishReason:(Te=pe.incomplete_details)==null?void 0:Te.reason,hasFunctionCall:Ce}),raw:(re=(ye=pe.incomplete_details)==null?void 0:ye.reason)!=null?re:void 0},usage:Da(Ht),request:{body:xe},response:{id:pe.id,timestamp:new Date(pe.created_at*1e3),modelId:pe.model,headers:ie,body:vt},providerMetadata:Ue,warnings:Me}}async doStream(t){const{args:r,warnings:o,webSearchToolName:c,toolNameMapping:u,store:f,providerOptionsName:m,isShellProviderExecuted:g}=await this.getArgs(t),{responseHeaders:C,value:x}=await Zn({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:{...r,stream:!0},failedResponseHandler:An,successfulResponseHandler:qo(l2),abortSignal:t.abortSignal,fetch:this.config.fetch}),A=this,v=La(t.prompt),P=new Map;let O={unified:"other",raw:void 0},M;const D=[];let B=null;const G={},Z=[];let U,Q=!1;const K={};let V;const z=[];return{stream:x.pipeThrough(new TransformStream({start(te){te.enqueue({type:"stream-start",warnings:o})},transform(te,S){var Te,ye,re,xe,Me,$,ge,ne,J,me,fe,ie,pe,vt,Ee,Tt,Ce,sn,Ue,Ht,de,Oe,yt,be,Xt,Wt,In,Ct,Xe,Ze,Sn,ve,Bn,$n,Jt,Hn,Bt,rr;if(t.includeRawChunks&&S.enqueue({type:"raw",rawValue:te.rawValue}),!te.success){O={unified:"error",raw:void 0},S.enqueue({type:"error",error:te.error});return}const R=te.value;if(Fa(R)){if(R.item.type==="function_call")G[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},S.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:R.item.name});else if(R.item.type==="custom_tool_call"){const oe=u.toCustomToolName(R.item.name);G[R.output_index]={toolName:oe,toolCallId:R.item.call_id},S.enqueue({type:"tool-input-start",id:R.item.call_id,toolName:oe})}else if(R.item.type==="web_search_call")G[R.output_index]={toolName:u.toCustomToolName(c??"web_search"),toolCallId:R.item.id},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName(c??"web_search"),providerExecuted:!0}),S.enqueue({type:"tool-input-end",id:R.item.id}),S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName(c??"web_search"),input:JSON.stringify({}),providerExecuted:!0});else if(R.item.type==="computer_call")G[R.output_index]={toolName:u.toCustomToolName("computer_use"),toolCallId:R.item.id},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName("computer_use"),providerExecuted:!0});else if(R.item.type==="code_interpreter_call")G[R.output_index]={toolName:u.toCustomToolName("code_interpreter"),toolCallId:R.item.id,codeInterpreter:{containerId:R.item.container_id}},S.enqueue({type:"tool-input-start",id:R.item.id,toolName:u.toCustomToolName("code_interpreter"),providerExecuted:!0}),S.enqueue({type:"tool-input-delta",id:R.item.id,delta:`{"containerId":"${R.item.container_id}","code":"`});else if(R.item.type==="file_search_call")S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("file_search"),input:"{}",providerExecuted:!0});else if(R.item.type==="image_generation_call")S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("image_generation"),input:"{}",providerExecuted:!0});else if(R.item.type==="tool_search_call"){const oe=R.item.id,qe=u.toCustomToolName("tool_search"),lt=R.item.execution==="server";G[R.output_index]={toolName:qe,toolCallId:oe,toolSearchExecution:(Te=R.item.execution)!=null?Te:"server"},lt&&S.enqueue({type:"tool-input-start",id:oe,toolName:qe,providerExecuted:!0})}else if(R.item.type!=="tool_search_output"){if(!(R.item.type==="mcp_call"||R.item.type==="mcp_list_tools"||R.item.type==="mcp_approval_request"))if(R.item.type==="apply_patch_call"){const{call_id:oe,operation:qe}=R.item;if(G[R.output_index]={toolName:u.toCustomToolName("apply_patch"),toolCallId:oe,applyPatch:{hasDiff:qe.type==="delete_file",endEmitted:qe.type==="delete_file"}},S.enqueue({type:"tool-input-start",id:oe,toolName:u.toCustomToolName("apply_patch")}),qe.type==="delete_file"){const lt=JSON.stringify({callId:oe,operation:qe});S.enqueue({type:"tool-input-delta",id:oe,delta:lt}),S.enqueue({type:"tool-input-end",id:oe})}else S.enqueue({type:"tool-input-delta",id:oe,delta:`{"callId":"${ur(oe)}","operation":{"type":"${ur(qe.type)}","path":"${ur(qe.path)}","diff":"`})}else R.item.type==="shell_call"?G[R.output_index]={toolName:u.toCustomToolName("shell"),toolCallId:R.item.call_id}:R.item.type==="shell_call_output"||(R.item.type==="message"?(Z.splice(0,Z.length),U=(ye=R.item.phase)!=null?ye:void 0,S.enqueue({type:"text-start",id:R.item.id,providerMetadata:{[m]:{itemId:R.item.id,...R.item.phase!=null&&{phase:R.item.phase}}}})):Fa(R)&&R.item.type==="reasoning"&&(K[R.item.id]={encryptedContent:R.item.encrypted_content,summaryParts:{0:"active"}},S.enqueue({type:"reasoning-start",id:`${R.item.id}:0`,providerMetadata:{[m]:{itemId:R.item.id,reasoningEncryptedContent:(re=R.item.encrypted_content)!=null?re:null}}})))}}else if(m2(R)){if(R.item.type==="message"){const oe=(xe=R.item.phase)!=null?xe:U;U=void 0,S.enqueue({type:"text-end",id:R.item.id,providerMetadata:{[m]:{itemId:R.item.id,...oe!=null&&{phase:oe},...Z.length>0&&{annotations:Z}}}})}else if(R.item.type==="function_call")G[R.output_index]=void 0,Q=!0,S.enqueue({type:"tool-input-end",id:R.item.call_id}),S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:R.item.name,input:R.item.arguments,providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="custom_tool_call"){G[R.output_index]=void 0,Q=!0;const oe=u.toCustomToolName(R.item.name);S.enqueue({type:"tool-input-end",id:R.item.call_id}),S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:oe,input:JSON.stringify(R.item.input),providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="web_search_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName(c??"web_search"),result:Ua(R.item.action)});else if(R.item.type==="computer_call")G[R.output_index]=void 0,S.enqueue({type:"tool-input-end",id:R.item.id}),S.enqueue({type:"tool-call",toolCallId:R.item.id,toolName:u.toCustomToolName("computer_use"),input:"",providerExecuted:!0}),S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("computer_use"),result:{type:"computer_use_tool_result",status:R.item.status||"completed"}});else if(R.item.type==="file_search_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("file_search"),result:{queries:R.item.queries,results:($=(Me=R.item.results)==null?void 0:Me.map(oe=>({attributes:oe.attributes,fileId:oe.file_id,filename:oe.filename,score:oe.score,text:oe.text})))!=null?$:null}});else if(R.item.type==="code_interpreter_call")G[R.output_index]=void 0,S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("code_interpreter"),result:{outputs:R.item.outputs}});else if(R.item.type==="image_generation_call")S.enqueue({type:"tool-result",toolCallId:R.item.id,toolName:u.toCustomToolName("image_generation"),result:{result:R.item.result}});else if(R.item.type==="tool_search_call"){const oe=G[R.output_index],qe=R.item.execution==="server";if(oe!=null){const lt=qe?oe.toolCallId:(ge=R.item.call_id)!=null?ge:R.item.id;qe?z.push(lt):S.enqueue({type:"tool-input-start",id:lt,toolName:oe.toolName}),S.enqueue({type:"tool-input-end",id:lt}),S.enqueue({type:"tool-call",toolCallId:lt,toolName:oe.toolName,input:JSON.stringify({arguments:R.item.arguments,call_id:qe?null:lt}),...qe?{providerExecuted:!0}:{},providerMetadata:{[m]:{itemId:R.item.id}}})}G[R.output_index]=void 0}else if(R.item.type==="tool_search_output"){const oe=(J=(ne=R.item.call_id)!=null?ne:z.shift())!=null?J:R.item.id;S.enqueue({type:"tool-result",toolCallId:oe,toolName:u.toCustomToolName("tool_search"),result:{tools:R.item.tools},providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_call"){G[R.output_index]=void 0;const oe=(me=R.item.approval_request_id)!=null?me:void 0,qe=oe!=null&&(ie=(fe=P.get(oe))!=null?fe:v[oe])!=null?ie:R.item.id,lt=`mcp.${R.item.name}`;S.enqueue({type:"tool-call",toolCallId:qe,toolName:lt,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-result",toolCallId:qe,toolName:lt,result:{type:"call",serverLabel:R.item.server_label,name:R.item.name,arguments:R.item.arguments,...R.item.output!=null?{output:R.item.output}:{},...R.item.error!=null?{error:R.item.error}:{}},providerMetadata:{[m]:{itemId:R.item.id}}})}else if(R.item.type==="mcp_list_tools")G[R.output_index]=void 0;else if(R.item.type==="apply_patch_call"){const oe=G[R.output_index];oe?.applyPatch&&!oe.applyPatch.endEmitted&&R.item.operation.type!=="delete_file"&&(oe.applyPatch.hasDiff||S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.item.operation.diff)}),S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),oe.applyPatch.endEmitted=!0),oe&&R.item.status==="completed"&&S.enqueue({type:"tool-call",toolCallId:oe.toolCallId,toolName:u.toCustomToolName("apply_patch"),input:JSON.stringify({callId:R.item.call_id,operation:R.item.operation}),providerMetadata:{[m]:{itemId:R.item.id}}}),G[R.output_index]=void 0}else if(R.item.type==="mcp_approval_request"){G[R.output_index]=void 0;const oe=(Ee=(vt=(pe=A.config).generateId)==null?void 0:vt.call(pe))!=null?Ee:Kt(),qe=(Tt=R.item.approval_request_id)!=null?Tt:R.item.id;P.set(qe,oe);const lt=`mcp.${R.item.name}`;S.enqueue({type:"tool-call",toolCallId:oe,toolName:lt,input:R.item.arguments,providerExecuted:!0,dynamic:!0}),S.enqueue({type:"tool-approval-request",approvalId:qe,toolCallId:oe})}else if(R.item.type==="local_shell_call")G[R.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:u.toCustomToolName("local_shell"),input:JSON.stringify({action:{type:"exec",command:R.item.action.command,timeoutMs:R.item.action.timeout_ms,user:R.item.action.user,workingDirectory:R.item.action.working_directory,env:R.item.action.env}}),providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="shell_call")G[R.output_index]=void 0,S.enqueue({type:"tool-call",toolCallId:R.item.call_id,toolName:u.toCustomToolName("shell"),input:JSON.stringify({action:{commands:R.item.action.commands}}),...g&&{providerExecuted:!0},providerMetadata:{[m]:{itemId:R.item.id}}});else if(R.item.type==="shell_call_output")S.enqueue({type:"tool-result",toolCallId:R.item.call_id,toolName:u.toCustomToolName("shell"),result:{output:R.item.output.map(oe=>({stdout:oe.stdout,stderr:oe.stderr,outcome:oe.outcome.type==="exit"?{type:"exit",exitCode:oe.outcome.exit_code}:{type:"timeout"}}))}});else if(R.item.type==="reasoning"){const oe=K[R.item.id],qe=Object.entries(oe.summaryParts).filter(([lt,xr])=>xr==="active"||xr==="can-conclude").map(([lt])=>lt);for(const lt of qe)S.enqueue({type:"reasoning-end",id:`${R.item.id}:${lt}`,providerMetadata:{[m]:{itemId:R.item.id,reasoningEncryptedContent:(Ce=R.item.encrypted_content)!=null?Ce:null}}});delete K[R.item.id]}}else if(w2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:R.delta})}else if(_2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:R.delta})}else if(E2(R)){const oe=G[R.output_index];oe?.applyPatch&&(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.delta)}),oe.applyPatch.hasDiff=!0)}else if(A2(R)){const oe=G[R.output_index];oe?.applyPatch&&!oe.applyPatch.endEmitted&&(oe.applyPatch.hasDiff||(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.diff)}),oe.applyPatch.hasDiff=!0),S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),oe.applyPatch.endEmitted=!0)}else if(v2(R))S.enqueue({type:"tool-result",toolCallId:R.item_id,toolName:u.toCustomToolName("image_generation"),result:{result:R.partial_image_b64},preliminary:!0});else if(C2(R)){const oe=G[R.output_index];oe!=null&&S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:ur(R.delta)})}else if(b2(R)){const oe=G[R.output_index];oe!=null&&(S.enqueue({type:"tool-input-delta",id:oe.toolCallId,delta:'"}'}),S.enqueue({type:"tool-input-end",id:oe.toolCallId}),S.enqueue({type:"tool-call",toolCallId:oe.toolCallId,toolName:u.toCustomToolName("code_interpreter"),input:JSON.stringify({code:R.code,containerId:oe.codeInterpreter.containerId}),providerExecuted:!0}))}else if(y2(R))B=R.response.id,S.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model});else if(p2(R))S.enqueue({type:"text-delta",id:R.item_id,delta:R.delta}),(Ue=(sn=t.providerOptions)==null?void 0:sn[m])!=null&&Ue.logprobs&&R.logprobs&&D.push(R.logprobs);else if(R.type==="response.reasoning_summary_part.added"){if(R.summary_index>0){const oe=K[R.item_id];oe.summaryParts[R.summary_index]="active";for(const qe of Object.keys(oe.summaryParts))oe.summaryParts[qe]==="can-conclude"&&(S.enqueue({type:"reasoning-end",id:`${R.item_id}:${qe}`,providerMetadata:{[m]:{itemId:R.item_id}}}),oe.summaryParts[qe]="concluded");S.enqueue({type:"reasoning-start",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[m]:{itemId:R.item_id,reasoningEncryptedContent:(de=(Ht=K[R.item_id])==null?void 0:Ht.encryptedContent)!=null?de:null}}})}}else if(R.type==="response.reasoning_summary_text.delta")S.enqueue({type:"reasoning-delta",id:`${R.item_id}:${R.summary_index}`,delta:R.delta,providerMetadata:{[m]:{itemId:R.item_id}}});else if(R.type==="response.reasoning_summary_part.done")f?(S.enqueue({type:"reasoning-end",id:`${R.item_id}:${R.summary_index}`,providerMetadata:{[m]:{itemId:R.item_id}}}),K[R.item_id].summaryParts[R.summary_index]="concluded"):K[R.item_id].summaryParts[R.summary_index]="can-conclude";else if(g2(R))O={unified:fo({finishReason:(Oe=R.response.incomplete_details)==null?void 0:Oe.reason,hasFunctionCall:Q}),raw:(be=(yt=R.response.incomplete_details)==null?void 0:yt.reason)!=null?be:void 0},M=R.response.usage,typeof R.response.service_tier=="string"&&(V=R.response.service_tier);else if(x2(R)){const oe=(Xt=R.response.incomplete_details)==null?void 0:Xt.reason;O={unified:oe?fo({finishReason:oe,hasFunctionCall:Q}):"error",raw:oe??"error"},M=(Wt=R.response.usage)!=null?Wt:void 0}else I2(R)?(Z.push(R.annotation),R.annotation.type==="url_citation"?S.enqueue({type:"source",sourceType:"url",id:(Xe=(Ct=(In=A.config).generateId)==null?void 0:Ct.call(In))!=null?Xe:Kt(),url:R.annotation.url,title:R.annotation.title}):R.annotation.type==="file_citation"?S.enqueue({type:"source",sourceType:"document",id:(ve=(Sn=(Ze=A.config).generateId)==null?void 0:Sn.call(Ze))!=null?ve:Kt(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}}):R.annotation.type==="container_file_citation"?S.enqueue({type:"source",sourceType:"document",id:(Jt=($n=(Bn=A.config).generateId)==null?void 0:$n.call(Bn))!=null?Jt:Kt(),mediaType:"text/plain",title:R.annotation.filename,filename:R.annotation.filename,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,containerId:R.annotation.container_id}}}):R.annotation.type==="file_path"&&S.enqueue({type:"source",sourceType:"document",id:(rr=(Bt=(Hn=A.config).generateId)==null?void 0:Bt.call(Hn))!=null?rr:Kt(),mediaType:"application/octet-stream",title:R.annotation.file_id,filename:R.annotation.file_id,providerMetadata:{[m]:{type:R.annotation.type,fileId:R.annotation.file_id,index:R.annotation.index}}})):S2(R)&&S.enqueue({type:"error",error:R})},flush(te){const S={[m]:{responseId:B,...D.length>0?{logprobs:D}:{},...V!==void 0?{serviceTier:V}:{}}};te.enqueue({type:"finish",finishReason:O,usage:Da(M),providerMetadata:S})}})),request:{body:r},response:{headers:C}}}};function p2(t){return t.type==="response.output_text.delta"}function m2(t){return t.type==="response.output_item.done"}function g2(t){return t.type==="response.completed"||t.type==="response.incomplete"}function x2(t){return t.type==="response.failed"}function y2(t){return t.type==="response.created"}function w2(t){return t.type==="response.function_call_arguments.delta"}function _2(t){return t.type==="response.custom_tool_call_input.delta"}function v2(t){return t.type==="response.image_generation_call.partial_image"}function C2(t){return t.type==="response.code_interpreter_call_code.delta"}function b2(t){return t.type==="response.code_interpreter_call_code.done"}function E2(t){return t.type==="response.apply_patch_call_operation_diff.delta"}function A2(t){return t.type==="response.apply_patch_call_operation_diff.done"}function Fa(t){return t.type==="response.output_item.added"}function I2(t){return t.type==="response.output_text.annotation.added"}function S2(t){return t.type==="error"}function Ua(t){var r;if(t==null)return{};switch(t.type){case"search":return{action:{type:"search",query:(r=t.query)!=null?r:void 0},...t.sources!=null&&{sources:t.sources}};case"open_page":return{action:{type:"openPage",url:t.url}};case"find_in_page":return{action:{type:"findInPage",url:t.url,pattern:t.pattern}}}}function ur(t){return JSON.stringify(t).slice(1,-1)}var T2=Be(()=>Pe(T({instructions:w().nullish(),speed:j().min(.25).max(4).default(1).nullish()}))),N2=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=[],C=await Vn({provider:"openai",providerOptions:m,schema:T2}),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.`})),C){const A={};for(const v in A){const P=A[v];P!==void 0&&(x[v]=P)}}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:C,rawValue:x}=await Zn({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),body:f,failedResponseHandler:An,successfulResponseHandler:Qm(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:g,warnings:m,request:{body:JSON.stringify(f)},response:{timestamp:u,modelId:this.modelId,headers:C,body:x}}}},O2=Be(()=>Pe(T({text:w(),language:w().nullish(),duration:j().nullish(),words:ue(T({word:w(),start:j(),end:j()})).nullish(),segments:ue(T({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()}))),k2=Be(()=>Pe(T({include:ue(w()).optional(),language:w().optional(),prompt:w().optional(),temperature:j().min(0).max(1).default(0).optional(),timestampGranularities:ue(Se(["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"},R2=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 Vn({provider:"openai",providerOptions:o,schema:k2}),f=new FormData,m=t instanceof Uint8Array?new Blob([t]):new Blob([Wo(t)]);f.append("model",this.modelId);const g=Qp(r);if(f.append("file",new File([m],"audio",{type:r}),`audio.${g}`),u){const C={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,A]of Object.entries(C))if(A!=null)if(Array.isArray(A))for(const v of A)f.append(`${x}[]`,String(v));else f.append(x,String(A))}return{formData:f,warnings:c}}async doGenerate(t){var r,o,c,u,f,m,g,C;const x=(c=(o=(r=this.config._internal)==null?void 0:r.currentDate)==null?void 0:o.call(r))!=null?c:new Date,{formData:A,warnings:v}=await this.getArgs(t),{value:P,responseHeaders:O,rawValue:M}=await su({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:En(this.config.headers(),t.headers),formData:A,failedResponseHandler:An,successfulResponseHandler:hr(O2),abortSignal:t.abortSignal,fetch:this.config.fetch}),D=P.language!=null&&P.language in za?za[P.language]:void 0;return{text:P.text,segments:(g=(m=(u=P.segments)==null?void 0:u.map(B=>({text:B.text,startSecond:B.start,endSecond:B.end})))!=null?m:(f=P.words)==null?void 0:f.map(B=>({text:B.word,startSecond:B.start,endSecond:B.end})))!=null?g:[],language:D,durationInSeconds:(C=P.duration)!=null?C:void 0,warnings:v,response:{timestamp:x,modelId:this.modelId,headers:O,body:M}}}},M2="3.0.49";function xu(t={}){var r,o;const c=(r=eg(Jp({settingValue:t.baseURL,environmentVariableName:"OPENAI_BASE_URL"})))!=null?r:"https://api.openai.com/v1",u=(o=t.name)!=null?o:"openai",f=()=>Qc({Authorization:`Bearer ${Kp({apiKey:t.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":t.organization,"OpenAI-Project":t.project,...t.headers},`ai-sdk/openai/${M2}`),m=D=>new sg(D,{provider:`${u}.chat`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),g=D=>new ug(D,{provider:`${u}.completion`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),C=D=>new hg(D,{provider:`${u}.embedding`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),x=D=>new xg(D,{provider:`${u}.image`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),A=D=>new R2(D,{provider:`${u}.transcription`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),v=D=>new N2(D,{provider:`${u}.speech`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch}),P=D=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return O(D)},O=D=>new h2(D,{provider:`${u}.responses`,url:({path:B})=>`${c}${B}`,headers:f,fetch:t.fetch,fileIdPrefixes:["file-"]}),M=function(D){return P(D)};return M.specificationVersion="v3",M.languageModel=P,M.chat=m,M.completion=g,M.responses=O,M.embedding=C,M.embeddingModel=C,M.textEmbedding=C,M.textEmbeddingModel=C,M.image=x,M.imageModel=x,M.transcription=A,M.transcriptionModel=A,M.speech=v,M.speechModel=v,M.tools=o2,M}xu();const D2={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 P2{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,C;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":C=_.reactive({type:"tool",running:!0,id:x.id,toolCallId:x.id,title:"",toolName:x.toolName,dynamic:x.dynamic,inputStr:"",input:{},output:{}}),f.contents.push(C),this.option.onTool?.(C);break;case"tool-input-delta":C.inputStr+=x.delta;break;case"tool-input-end":break;case"tool-call":C.input=x.input;break;case"tool-result":C.output=x.output,C.running=!1;break;case"tool-error":C.error=x.error,C.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 B2(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 C;g===-1?(C=t.slice(u+f).trim(),o=t.length):(C=t.slice(u+f,g).trim(),o=g+3),r.push({type:"schema-card",content:C})}return r}class L2{staticPrompt="";skillMetaPrompt="";tempPrompt="";getSystemPrompt(){return`
|
|
51
51
|
当前时间:${new Date().toLocaleString()}。
|
|
52
52
|
${this.staticPrompt}
|
|
53
53
|
${this.skillMetaPrompt}
|
|
54
54
|
${this.tempPrompt}
|
|
55
|
-
`}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const fo={model:"deepseek-ai/DeepSeek-V3",maxSteps:15,extraTools:{}},La={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function B2(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 L2 extends Gn.BaseModelProvider{transport;agent;promptManager;llmConfig={...fo,...La};isGenuiEnabled;debugStream=!1;pageToolsOnDemand=!1;_getRouteState=null;setRouteStateGetter(r){this._getRouteState=r}constructor(r,o,c){super(r);let u;c&&"llm"in c?u={...fo,...c}:u={...fo,...La,...c||{}},this.llmConfig=u;const g={llmConfig:u.llm?{llm:u.llm}:{...u}};this.agent=new en.AgentModelProvider(g),this.promptManager=new P2,this.promptManager.setStatic(o)}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:g,llm:m,providerOptions:v,headers:x}){if(m)this.agent.llm=m,this.llmConfig.model=r,this.llmConfig.useReActMode=g||!1,this.agent.useReActMode=g||!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=g||!1,this.agent.useReActMode=g||!1;let A;if(f==="deepseek")A=yc;else if(f==="openai")A=fu;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 g=f.length-2;g>=0;g--){const m=f[g];m.role===c&&this.isSnapshotContent(m.content)&&this.replaceSnapshotWithPlaceholder(m)}return f}removeSnapshotData(r){if(!r)return r;const o=["无障碍树快照:","无障碍树快照:","快照内容:","快照内容:","页面无障碍树快照:","页面无障碍树快照:","操作后的页面快照:","操作后的页面快照:"];let c=-1;for(const f of o){const g=r.indexOf(f);if(g!==-1){c=g;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:B2(this.llmConfig.providerOptions,R2),prepareStep:({messages:O})=>{this.cleanGetSkillContentToolResult(O);const R=this.cleanupOldSnapshotsInMessages(O),D=Object.keys(this.llmConfig.extraTools||{}),P=new Set;Object.values(this.agent.mcpTools||{}).forEach($=>{Object.keys($||{}).forEach(U=>P.add(U)),D.push(...Object.keys($||{}))});const Y=Array.from(new Set(D)).filter($=>{if(this.agent.ignoreToolnames.includes($))return!1;if(!this.pageToolsOnDemand)return!0;const U=this._getRouteState?.()??hd(),W=U?.toolRouteMap??en.getToolRouteMap(),X=U?.activeRoutes??en.getActiveRoutes(),H=V=>V.replace(/\/+$/,"")||"/";if(U&&U.initialized===!1)return!P.has($);const z=W.get($);if(z){const V=H(z);return X.has(V)||X.has(z)}return!0});return{system:this.promptManager.getSystemPrompt(),messages:R,activeTools:Y}},onStepFinish:O=>{if(O.finishReason==="tool-calls"&&O.content.length>0){const R=O.content[O.content.length-1];if(R.toolName==="get_skill_content"&&R.type==="tool-result"){const D=R.output.content;this.promptManager.appendTemp(D)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp("")}},f={role:"user",content:c.content},m=[...(O=>O.map(R=>({role:R.role,content:R.content})))(this.agent.responseMessages),f];u.messages=m;const v=await this.agent.chatStream(u),x=new Pp,A=await new M2({debug:this.debugStream,onFinish:()=>{y.nextTick(()=>{x.resolve(),o.onDone()})}}).traverse(v),B={role:"assistant",content:"",uiContent:[]};return y.watch(A,O=>{if(!O)o.onData(B);else{const D=O.steps.map(P=>P.contents).flat().map(P=>{if(P.type==="text")return D2(P.text);if(P.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:P.text,thinkId:P.id};if(P.type==="tool")return{type:"tool",id:P.id,name:P.toolName,content:JSON.stringify({input:P.inputStr,output:P.output}),status:P.error?"failed":P.running?"running":"success"}});if(O?.error){const P={type:"markdown",content:`**错误**:${O.error.responseBody||O.error.message||"未知错误"}`};D.push(P)}(O.steps.length>=1||O?.error)&&o.onData({...B,uiContent:D.flat(),usage:O.totalUsage||null})}},{deep:!0}),x.promise}chat(r){throw new Error("Method not implemented.")}}const F2=({systemPrompt:t,llmConfig:r,emit:o})=>{const c=new L2({provider:"custom"},t,r),u=new Gn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:g,getCurrentConversation:m,switchConversation:v,deleteConversation:x,updateTitle:E,state:A}=Gn.useConversation({client:u,autoSave:!1,events:{onLoaded(){},onReceiveData(X,H,z){z(),H.value[H.value.length-1].role==="assistant"&&H.value.pop(),o("before-ai-render",X),H.value.push(X)}}}),{messageState:B,inputMessage:O,sendMessage:R,abortRequest:D,messages:P,addMessage:Y,send:$}=f,U=y.ref(),W=async(X,H,z)=>{if(z){const{shouldBlock:M}=await z(X);if(M)return!1}O.value=X;const V=m();if(V&&V.title==="新会话"&&E(V.id,O.value.slice(0,15)),H&&H.length>0){const M=[{type:"text",text:O.value},...H],Ce=[];O.value&&Ce.push({type:"text",content:O.value});for(const le of H)le.type==="image"&&le.image&&Ce.push({type:"image",content:le.image});const me={role:"user",content:M,uiContent:Ce};P.value.push(me),O.value="",$()}else{const M={role:"user",content:O.value,uiContent:[{type:"text",content:O.value}]};P.value.push(M),O.value="",$()}return!0};return y.onMounted(()=>{U.value?.focus()}),y.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:u,messageManager:f,addMessage:Y,send:$,conversationState:A,messages:P,messageState:B,inputMessage:O,sendMessage:R,abortRequest:D,senderRef:U,handleSendMessage:W,createConversation:g,switchConversation:v,deleteConversation:x,getCurrentConversation:m}};function U2(){}const Dn=Object.assign,Go=typeof window<"u",Li=t=>t!==null&&typeof t=="object",Yn=t=>t!=null,No=t=>typeof t=="function",z2=t=>Li(t)&&No(t.then)&&No(t.catch),hu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),V2=()=>Go?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Fa(t,r){const o=r.split(".");let c=t;return o.forEach(u=>{var f;c=Li(c)&&(f=c[u])!=null?f:""}),c}function Z2(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const Oi=null,cn=[Number,String],lr={type:Boolean,default:!0},$2=t=>({type:Number,default:t}),un=t=>({type:String,default:t});var Xo=typeof window<"u";function pu(t){let r;y.onMounted(()=>{t(),y.nextTick(()=>{r=!0})}),y.onActivated(()=>{r&&t()})}function gu(t,r,o={}){if(!Xo)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let g=!1,m;const v=A=>{if(g)return;const B=y.unref(A);B&&!m&&(B.addEventListener(t,r,{capture:f,passive:u}),m=!0)},x=A=>{if(g)return;const B=y.unref(A);B&&m&&(B.removeEventListener(t,r,f),m=!1)};y.onUnmounted(()=>x(c)),y.onDeactivated(()=>x(c)),pu(()=>v(c));let E;return y.isRef(c)&&(E=y.watch(c,(A,B)=>{x(B),v(A)})),()=>{E?.(),x(c),g=!0}}var _i,ho;function W2(){if(!_i&&(_i=y.ref(0),ho=y.ref(0),Xo)){const t=()=>{_i.value=window.innerWidth,ho.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:_i,height:ho}}var H2=/scroll|auto|overlay/i,j2=Xo?window:void 0;function G2(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function X2(t,r=j2){let o=t;for(;o&&o!==r&&G2(o);){const{overflowY:c}=window.getComputedStyle(o);if(H2.test(c))return o;o=o.parentNode}return r}V2();const q2=t=>t.stopPropagation();function mu(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),q2(t)}W2();function Cn(t){if(Yn(t))return hu(t)?`${t}px`:String(t)}function Y2(t){if(Yn(t)){if(Array.isArray(t))return{width:Cn(t[0]),height:Cn(t[1])};const r=Cn(t);return{width:r,height:r}}}function K2(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const J2=/-(\w)/g,xu=t=>t.replace(J2,(r,o)=>o.toUpperCase()),Q2=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:ex}=Object.prototype;function tx(t,r,o){const c=r[o];Yn(c)&&(!ex.call(t,o)||!Li(c)?t[o]=c:t[o]=wu(Object(t[o]),c))}function wu(t,r){return Object.keys(r).forEach(o=>{tx(t,r,o)}),t}var nx={name:"姓名",tel:"电话",save:"保存",clear:"清空",cancel:"取消",confirm:"确认",delete:"删除",loading:"加载中...",noCoupon:"暂无优惠券",nameEmpty:"请填写姓名",addContact:"添加联系人",telInvalid:"请填写正确的电话",vanCalendar:{end:"结束",start:"开始",title:"日期选择",weekdays:["日","一","二","三","四","五","六"],monthTitle:(t,r)=>`${t}年${r}月`,rangePrompt:t=>`最多选择 ${t} 天`},vanCascader:{select:"请选择"},vanPagination:{prev:"上一页",next:"下一页"},vanPullRefresh:{pulling:"下拉即可刷新...",loosing:"释放即可刷新..."},vanSubmitBar:{label:"合计:"},vanCoupon:{unlimited:"无门槛",discount:t=>`${t}折`,condition:t=>`满${t}元可用`},vanCouponCell:{title:"优惠券",count:t=>`${t}张可用`},vanCouponList:{exchange:"兑换",close:"不使用",enable:"可用",disabled:"不可用",placeholder:"输入优惠码"},vanAddressEdit:{area:"地区",areaEmpty:"请选择地区",addressEmpty:"请填写详细地址",addressDetail:"详细地址",defaultAddress:"设为默认收货地址"},vanAddressList:{add:"新增地址"}};const Ua=y.ref("zh-CN"),za=y.reactive({"zh-CN":nx}),rx={messages(){return za[Ua.value]},use(t,r){Ua.value=t,this.add({[t]:r})},add(t={}){wu(za,t)}};var ix=rx;function ox(t){const r=xu(t)+".";return(o,...c)=>{const u=ix.messages(),f=Fa(u,r+o)||Fa(u,o);return No(f)?f(...c):f}}function Oo(t,r){return r?typeof r=="string"?` ${t}--${r}`:Array.isArray(r)?r.reduce((o,c)=>o+Oo(t,c),""):Object.keys(r).reduce((o,c)=>o+(r[c]?Oo(t,c):""),""):""}function sx(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Oo(r,o)}`)}function fr(t){const r=`van-${t}`;return[r,sx(r),ox(r)]}const ax="van-haptics-feedback",Va=5;function lx(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);z2(f)?f.then(g=>{g?o():c&&c()}).catch(u||U2):f?o():c&&c()}else o()}function ni(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(xu(`-${o}`),t))},t}const cx=Symbol();function yu(t){const r=y.getCurrentInstance();r&&Dn(r.proxy,t)}const[ux,Za]=fr("badge"),dx={dot:Boolean,max:cn,tag:un("div"),color:String,offset:Array,content:cn,showZero:lr,position:un("top-right")};var fx=y.defineComponent({name:ux,props:dx,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:m,showZero:v}=t;return Yn(m)&&m!==""&&(v||m!==0&&m!=="0")},c=()=>{const{dot:m,max:v,content:x}=t;if(!m&&o())return r.content?r.content():Yn(v)&&hu(x)&&+x>+v?`${v}+`:x},u=m=>m.startsWith("-")?m.replace("-",""):`-${m}`,f=y.computed(()=>{const m={background:t.color};if(t.offset){const[v,x]=t.offset,{position:E}=t,[A,B]=E.split("-");r.default?(typeof x=="number"?m[A]=Cn(A==="top"?x:-x):m[A]=A==="top"?Cn(x):u(x),typeof v=="number"?m[B]=Cn(B==="left"?v:-v):m[B]=B==="left"?Cn(v):u(v)):(m.marginTop=Cn(x),m.marginLeft=Cn(v))}return m}),g=()=>{if(o()||t.dot)return y.createVNode("div",{class:Za([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:m}=t;return y.createVNode(m,{class:Za("wrapper")},{default:()=>[r.default(),g()]})}return g()}}});const hx=ni(fx);let _u=2e3;const px=()=>++_u,gx=t=>{_u=t},[vu,mx]=fr("config-provider"),Cu=Symbol(vu),xx={tag:un("div"),theme:un("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:un("local"),iconPrefix:String};function wx(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function yx(t){const r={};return Object.keys(t).forEach(o=>{const c=wx(Q2(o));r[`--van-${c}`]=t[o]}),r}function vi(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)})}y.defineComponent({name:vu,props:xx,setup(t,{slots:r}){const o=y.computed(()=>yx(Dn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(Go){const c=()=>{document.documentElement.classList.add(`van-theme-${t.theme}`)},u=(f=t.theme)=>{document.documentElement.classList.remove(`van-theme-${f}`)};y.watch(()=>t.theme,(f,g)=>{g&&u(g),c()},{immediate:!0}),y.onActivated(c),y.onDeactivated(u),y.onBeforeUnmount(u),y.watch(o,(f,g)=>{t.themeVarsScope==="global"&&vi(f,g)}),y.watch(()=>t.themeVarsScope,(f,g)=>{g==="global"&&vi({},o.value),f==="global"&&vi(o.value,{})}),t.themeVarsScope==="global"&&vi(o.value,{})}return y.provide(Cu,t),y.watchEffect(()=>{t.zIndex!==void 0&&gx(t.zIndex)}),()=>y.createVNode(t.tag,{class:mx(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[_x,$a]=fr("icon"),vx=t=>t?.includes("/"),Cx={dot:Boolean,tag:un("i"),name:String,size:cn,badge:cn,color:String,badgeProps:Object,classPrefix:String};var bx=y.defineComponent({name:_x,props:Cx,setup(t,{slots:r}){const o=y.inject(Cu,null),c=y.computed(()=>t.classPrefix||o?.iconPrefix||$a());return()=>{const{tag:u,dot:f,name:g,size:m,badge:v,color:x}=t,E=vx(g);return y.createVNode(hx,y.mergeProps({dot:f,tag:u,class:[c.value,E?"":`${c.value}-${g}`],style:{color:x,fontSize:Cn(m)},content:v},t.badgeProps),{default:()=>{var A;return[(A=r.default)==null?void 0:A.call(r),E&&y.createVNode("img",{class:$a("image"),src:g},null)]}})}}});const qo=ni(bx),[Ex,Hr]=fr("loading"),Ax=Array(12).fill(null).map((t,r)=>y.createVNode("i",{class:Hr("line",String(r+1))},null)),Ix=y.createVNode("svg",{class:Hr("circular"),viewBox:"25 25 50 50"},[y.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),Sx={size:cn,type:un("circular"),color:String,vertical:Boolean,textSize:cn,textColor:String};var Tx=y.defineComponent({name:Ex,props:Sx,setup(t,{slots:r}){const o=y.computed(()=>Dn({color:t.color},Y2(t.size))),c=()=>{const f=t.type==="spinner"?Ax:Ix;return y.createVNode("span",{class:Hr("spinner",t.type),style:o.value},[r.icon?r.icon():f])},u=()=>{var f;if(r.default)return y.createVNode("span",{class:Hr("text"),style:{fontSize:Cn(t.textSize),color:(f=t.textColor)!=null?f:t.color}},[r.default()])};return()=>{const{type:f,vertical:g}=t;return y.createVNode("div",{class:Hr([f,{vertical:g}]),"aria-live":"polite","aria-busy":!0},[c(),u()])}}});const Nx=ni(Tx),Ox={show:Boolean,zIndex:cn,overlay:lr,duration:cn,teleport:[String,Object],lockScroll:lr,lazyRender:lr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:Oi,transitionAppear:Boolean,closeOnClickOverlay:lr};function kx(t,r){return t>r?"horizontal":r>t?"vertical":""}function Rx(){const t=y.ref(0),r=y.ref(0),o=y.ref(0),c=y.ref(0),u=y.ref(0),f=y.ref(0),g=y.ref(""),m=y.ref(!0),v=()=>g.value==="vertical",x=()=>g.value==="horizontal",E=()=>{o.value=0,c.value=0,u.value=0,f.value=0,g.value="",m.value=!0};return{move:(O=>{const R=O.touches[0];o.value=(R.clientX<0?0:R.clientX)-t.value,c.value=R.clientY-r.value,u.value=Math.abs(o.value),f.value=Math.abs(c.value);const D=10;(!g.value||u.value<D&&f.value<D)&&(g.value=kx(u.value,f.value)),m.value&&(u.value>Va||f.value>Va)&&(m.value=!1)}),start:(O=>{E(),t.value=O.touches[0].clientX,r.value=O.touches[0].clientY}),reset:E,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:g,isVertical:v,isHorizontal:x,isTap:m}}let Lr=0;const Wa="van-overflow-hidden";function Mx(t,r){const o=Rx(),c="01",u="10",f=E=>{o.move(E);const A=o.deltaY.value>0?u:c,B=X2(E.target,t.value),{scrollHeight:O,offsetHeight:R,scrollTop:D}=B;let P="11";D===0?P=R>=O?"00":"01":D+R>=O&&(P="10"),P!=="11"&&o.isVertical()&&!(parseInt(P,2)&parseInt(A,2))&&mu(E)},g=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),Lr||document.body.classList.add(Wa),Lr++},m=()=>{Lr&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),Lr--,Lr||document.body.classList.remove(Wa))},v=()=>r()&&g(),x=()=>r()&&m();pu(v),y.onDeactivated(x),y.onBeforeUnmount(x),y.watch(r,E=>{E?g():m()})}function bu(t){const r=y.ref(!1);return y.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const Ha=()=>{var t;const{scopeId:r}=((t=y.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[Dx,Px]=fr("overlay"),Bx={show:Boolean,zIndex:cn,duration:cn,className:Oi,lockScroll:lr,lazyRender:lr,customStyle:Object,teleport:[String,Object]};var Lx=y.defineComponent({name:Dx,inheritAttrs:!1,props:Bx,setup(t,{attrs:r,slots:o}){const c=y.ref(),u=bu(()=>t.show||!t.lazyRender),f=m=>{t.lockScroll&&mu(m)},g=u(()=>{var m;const v=Dn(K2(t.zIndex),t.customStyle);return Yn(t.duration)&&(v.animationDuration=`${t.duration}s`),y.withDirectives(y.createVNode("div",y.mergeProps({ref:c,style:v,class:[Px(),t.className]},r),[(m=o.default)==null?void 0:m.call(o)]),[[y.vShow,t.show]])});return gu("touchmove",f,{target:c}),()=>{const m=y.createVNode(y.Transition,{name:"van-fade",appear:!0},{default:g});return t.teleport?y.createVNode(y.Teleport,{to:t.teleport},{default:()=>[m]}):m}}});const Fx=ni(Lx),Ux=Dn({},Ox,{round:Boolean,position:un("center"),closeIcon:un("cross"),closeable:Boolean,transition:String,iconPrefix:String,closeOnPopstate:Boolean,closeIconPosition:un("top-right"),destroyOnClose:Boolean,safeAreaInsetTop:Boolean,safeAreaInsetBottom:Boolean}),[zx,ja]=fr("popup");var Vx=y.defineComponent({name:zx,inheritAttrs:!1,props:Ux,emits:["open","close","opened","closed","keydown","update:show","clickOverlay","clickCloseIcon"],setup(t,{emit:r,attrs:o,slots:c}){let u,f;const g=y.ref(),m=y.ref(),v=bu(()=>t.show||!t.lazyRender),x=y.computed(()=>{const H={zIndex:g.value};if(Yn(t.duration)){const z=t.position==="center"?"animationDuration":"transitionDuration";H[z]=`${t.duration}s`}return H}),E=()=>{u||(u=!0,g.value=t.zIndex!==void 0?+t.zIndex:px(),r("open"))},A=()=>{u&&lx(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},B=H=>{r("clickOverlay",H),t.closeOnClickOverlay&&A()},O=()=>{if(t.overlay){const H=Dn({show:t.show,class:t.overlayClass,zIndex:g.value,duration:t.duration,customStyle:t.overlayStyle,role:t.closeOnClickOverlay?"button":void 0,tabindex:t.closeOnClickOverlay?0:void 0},t.overlayProps);return y.createVNode(Fx,y.mergeProps(H,Ha(),{onClick:B}),{default:c["overlay-content"]})}},R=H=>{r("clickCloseIcon",H),A()},D=()=>{if(t.closeable)return y.createVNode(qo,{role:"button",tabindex:0,name:t.closeIcon,class:[ja("close-icon",t.closeIconPosition),ax],classPrefix:t.iconPrefix,onClick:R},null)};let P;const Y=()=>{P&&clearTimeout(P),P=setTimeout(()=>{r("opened")})},$=()=>r("closed"),U=H=>r("keydown",H),W=v(()=>{var H;const{destroyOnClose:z,round:V,position:M,safeAreaInsetTop:Ce,safeAreaInsetBottom:me,show:le}=t;if(!(!le&&z))return y.withDirectives(y.createVNode("div",y.mergeProps({ref:m,style:x.value,role:"dialog",tabindex:0,class:[ja({round:V,[M]:M}),{"van-safe-area-top":Ce,"van-safe-area-bottom":me}],onKeydown:U},o,Ha()),[(H=c.default)==null?void 0:H.call(c),D()]),[[y.vShow,le]])}),X=()=>{const{position:H,transition:z,transitionAppear:V}=t,M=H==="center"?"van-fade":`van-popup-slide-${H}`;return y.createVNode(y.Transition,{name:z||M,appear:V,onAfterEnter:Y,onAfterLeave:$},{default:W})};return y.watch(()=>t.show,H=>{H&&!u&&(E(),o.tabindex===0&&y.nextTick(()=>{var z;(z=m.value)==null||z.focus()})),!H&&u&&(u=!1,r("close"))}),yu({popupRef:m}),Mx(m,()=>t.show&&t.lockScroll),gu("popstate",()=>{t.closeOnPopstate&&(A(),f=!1)}),y.onMounted(()=>{t.show&&E()}),y.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),y.onDeactivated(()=>{t.show&&t.teleport&&(A(),f=!0)}),y.provide(cx,()=>t.show),()=>t.teleport?y.createVNode(y.Teleport,{to:t.teleport},{default:()=>[O(),X()]}):y.createVNode(y.Fragment,null,[O(),X()])}});const Zx=ni(Vx);let Fr=0;function $x(t){t?(Fr||document.body.classList.add("van-toast--unclickable"),Fr++):Fr&&(Fr--,Fr||document.body.classList.remove("van-toast--unclickable"))}const[Wx,br]=fr("toast"),Hx=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],jx={icon:String,show:Boolean,type:un("text"),overlay:Boolean,message:cn,iconSize:cn,duration:$2(2e3),position:un("middle"),teleport:[String,Object],wordBreak:String,className:Oi,iconPrefix:String,transition:un("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:Oi,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:cn};var Gx=y.defineComponent({name:Wx,props:jx,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,$x(u))},g=A=>r("update:show",A),m=()=>{t.closeOnClick&&g(!1)},v=()=>clearTimeout(c),x=()=>{const{icon:A,type:B,iconSize:O,iconPrefix:R,loadingType:D}=t;if(A||B==="success"||B==="fail")return y.createVNode(qo,{name:A||B,size:O,class:br("icon"),classPrefix:R},null);if(B==="loading")return y.createVNode(Nx,{class:br("loading"),size:O,type:D},null)},E=()=>{const{type:A,message:B}=t;if(o.message)return y.createVNode("div",{class:br("text")},[o.message()]);if(Yn(B)&&B!=="")return A==="html"?y.createVNode("div",{key:0,class:br("text"),innerHTML:String(B)},null):y.createVNode("div",{class:br("text")},[B])};return y.watch(()=>[t.show,t.forbidClick],f),y.watch(()=>[t.show,t.type,t.message,t.duration],()=>{v(),t.show&&t.duration>0&&(c=setTimeout(()=>{g(!1)},t.duration))}),y.onMounted(f),y.onUnmounted(f),()=>y.createVNode(Zx,y.mergeProps({class:[br([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:m,onClosed:v,"onUpdate:show":g},Z2(t,Hx)),{default:()=>[x(),E()]})}});function Xx(){const t=y.reactive({show:!1}),r=u=>{t.show=u},o=u=>{Dn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return yu({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function qx(t){const r=y.createApp(t),o=document.createElement("div");return document.body.appendChild(o),{instance:r.mount(o),unmount(){r.unmount(),document.body.removeChild(o)}}}const Yx={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 Ci=[],Kx=!1,Ga=Dn({},Yx);const Jx=new Map;function Eu(t){return Li(t)?t:{message:t}}function Qx(){const{instance:t}=qx({setup(){const r=y.ref(""),{open:o,state:c,close:u,toggle:f}=Xx(),g=()=>{},m=()=>{const v={onClosed:g,"onUpdate:show":f};return y.createVNode(Gx,y.mergeProps(c,v),null)};return y.watch(r,v=>{c.message=v}),y.getCurrentInstance().render=m,{open:o,close:u,message:r}}});return t}function ew(){if(!Ci.length||Kx){const t=Qx();Ci.push(t)}return Ci[Ci.length-1]}function qe(t={}){if(!Go)return{};const r=ew(),o=Eu(t);return r.open(Dn({},Ga,Jx.get(o.type||Ga.type),o)),r}const tw=t=>r=>qe(Dn({type:t},Eu(r))),Au=tw("loading"),nw=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=rw(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},rw=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}},iw=(t,r,o)=>{const c=async(f,g,m,v,x)=>{if(await t.insertMcpServer(f,g)){const A=t.mcpTools[f];if(A){const O={id:`plugin-${f.replace("mcp-server-","")}`,name:m,icon:x||o,description:v||(typeof g=="object"&&"url"in g?g.url:""),enabled:!0,expanded:!0,tools:Object.keys(A).map(R=>({id:R,name:R,description:A[R].description,enabled:!0})),originMcpConfig:y.markRaw(g)};return r.value.push(O),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,g)=>{Au("添加工具中...");try{if(f==="code"){if(typeof g!="string"){qe("添加工具失败:code 类型需要 JSON 字符串格式");return}const $=nw(g);if($.length===0){qe("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let U=0,W=0;for(const{name:X,config:H}of $){const z=`mcp-server-${X}`;await c(z,H,X)?U++:W++}await t.closeAll(),W===0?qe(`成功添加 ${U} 个工具`):U>0?qe(`成功添加 ${U} 个工具,${W} 个失败`):qe("添加工具失败:所有服务器都无法连接");return}if(typeof g=="string"){qe("添加工具失败:数据格式不正确");return}const{description:m,headers:v,name:x,thumbnail:E,type:A,url:B}=g;if(!x||!B||!A){qe("添加工具失败:缺少必要参数(名称、URL或类型)");return}const R=`mcp-server-${`custom-${x}-${Date.now()}`}`;let D;if(typeof v=="string"&&v.trim())try{D=JSON.parse(v)}catch($){console.warn("Failed to parse headers JSON:",$)}else typeof v=="object"&&(D=v);await c(R,{type:A,url:B,headers:D,useAISdkClient:!0},x,m,E)?(await t.closeAll(),qe("添加工具完成")):qe("重复添加工具或无法获取工具列表")}catch(m){console.error("handleCustomAdd error:",m),qe(`添加工具失败:${m instanceof Error?m.message:"未知错误"}`)}}}};function ow(t,r,o){const c=y.ref([]),u=y.ref([]),f=y.ref(!1),g=W=>W==="mcp-server-localhost",m=(W,X)=>{X?t.ignoreToolnames=t.ignoreToolnames.filter(H=>H!==W):t.ignoreToolnames.includes(W)||t.ignoreToolnames.push(W)},v=(W,X)=>{r.value||(r.value={});const H={...r.value};W===null?Object.keys(H).forEach(z=>{H[z]=X}):H[W]=X,r.value=H},x=W=>{const X=u.value.find(H=>H.id===W);X&&(X.addState="idle")},E=W=>{const X=t.mcpTools[W];if(!X)return[];const H=g(W),z=r.value||{};return Object.keys(X).map(V=>{const M=H?!!z[V]:!0;return m(V,M),{id:V,name:V,description:X[V].description,enabled:M}})},A=async W=>{const X=W.pluginId;if(!await t.insertMcpServer(X,W.mcpServer))return!1;if(!t.mcpTools[X])return await t.removeMcpServer(X),!1;const V=E(X);if(V.length===0)return await t.removeMcpServer(X),!1;const M=c.value.find(me=>me.id===W.pluginId);if(M)return M.tools=V,M.originMcpConfig=y.markRaw(W.mcpServer),!0;const Ce={id:W.pluginId,name:W.name,icon:W.icon||o,description:W.description,enabled:!0,expanded:!1,tools:V,originMcpConfig:y.markRaw(W.mcpServer)};return c.value.push(Ce),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async(W,X)=>{let H,z;if("type"in X&&X.type==="local")H="本地工具",z="本地工具列表";else{const V=new URL(X.url);H=V.origin,z=V.searchParams.get("sessionId")||("sessionId"in X?X.sessionId:"")||""}await A({pluginId:W,name:H,description:z,mcpServer:X})},togglePlugin:(W,X)=>{const H=g(W.id);W.tools.forEach(z=>{z.enabled=X,m(z.id,X),H&&v(z.id,X)})},toggleTool:(W,X,H)=>{const z=g(W.id);W.tools.forEach(V=>{V.id===X&&(V.enabled=H)}),m(X,H),z&&v(X,H)},deletePlugin:async W=>{const X=c.value.find(z=>z.id===W.id);if(!X)return;c.value=c.value.filter(z=>z.id!==X.id),x(X.id);const H=W.id;await t.removeMcpServer(H)},addPluginCore:A,addPluginFromMarket:async W=>{W.addState="loading";const X={type:W.type,url:W.url,headers:W.headers,useAISdkClient:!0},H=await A({pluginId:W.id,name:W.name,description:W.description||"",icon:W.icon,mcpServer:X});W.addState=H?"added":"idle"},addPluginFromScan:async(W,X)=>{const H={type:"streamableHttp",url:`${X}mcp?sessionId=${W}`},z=new URL(`${X}mcp?sessionId=${W}`);return await A({pluginId:`plugin-${W}`,name:z.origin,description:W,mcpServer:H})},handleClientDisconnected:async W=>{const X=W,H=c.value.find(z=>z.id===X);return await t.removeMcpServer(W),H?(c.value=c.value.filter(z=>z.id!==X),x(X),H):null},searchPlugin:(W,X)=>W.trim()===""||X.name.toLowerCase().includes(W.toLowerCase())}}function sw(t){const{skillsRef:r,customAgentProvider:o}=t,c=y.computed(()=>{const m=r?.value;return m?en.getSkillOverviews(m):[]}),u=y.computed(()=>{const m=c.value;return m.length>0?en.formatSkillsForSystemPrompt(m):""}),f=y.computed(()=>{const m=r?.value;return m?en.createSkillTools(m):{}});return y.watchEffect(()=>{if(o.promptManager.setSkillMeta(u.value),o.llmConfig){const m=o.llmConfig.extraTools??{};o.llmConfig.extraTools={...m,...f.value}}}),{processSkillMentions:async()=>({shouldBlock:!1,skillItems:[]}),skillPromptPart:u,skillTools:f,skillOverviews:c}}const aw=["title"],lw=y.defineComponent({__name:"TokenUsage",props:{usage:{type:Object,default:""}},setup(t){const r=t,o=y.computed(()=>r.usage.totalTokens===0||typeof r.usage.totalTokens>"u"),c=y.computed(()=>{const{inputTokens:f=0,outputTokens:g=0,totalTokens:m=0,inputTokenDetails:v,outputTokenDetails:x}=r.usage,E=v?.cacheReadTokens||0,A=x?.reasoningTokens||0;return{cachedInputTokens:[E/m*100+"%",E],inputTokens:[(f-E)/m*100+"%",f],reasoningTokens:[A/m*100+"%",A],outputTokens:[(g-A)/m*100+"%",g]}}),u=y.computed(()=>{const{inputTokens:f=0,outputTokens:g=0,totalTokens:m=0,inputTokenDetails:v,outputTokenDetails:x}=r.usage,E=v?.cacheReadTokens||0,A=x?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${g}`,`totalTokens: ${m}`,`cachedInputTokens: ${E}`,`reasoningTokens: ${A}`].join(`
|
|
56
|
-
`)});return(f,g)=>o.value?y.createCommentVNode("",!0):(y.openBlock(),y.createElementBlock("div",{key:0,class:"token-usage-wrap",title:u.value},[(y.openBlock(!0),y.createElementBlock(y.Fragment,null,y.renderList(c.value,(m,v)=>(y.openBlock(),y.createElementBlock("div",{key:v,class:y.normalizeClass(v),style:y.normalizeStyle({width:m[0]})},null,6))),128))],8,aw))}}),Kn=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},cw=Kn(lw,[["__scopeId","data-v-000098b4"]]),uw={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 dw(t,r){return y.openBlock(),y.createElementBlock("svg",uw,[...r[0]||(r[0]=[y.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),y.createElementVNode("mask",{id:"mask9_3088","mask-type":"alpha",maskUnits:"userSpaceOnUse",x:"0.000061",y:"0.000061",width:"99.999939",height:"99.999939"},[y.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),y.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 Iu={render:dw};function fw(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=y.h(Iu,{style:{width:"48px",height:"48px"}}),g=y.ref({}),m=y.computed(()=>Gn.GeneratingStatus.includes(o.status)),v=y.computed(()=>r.value.findLastIndex(O=>O.role==="assistant")),x=O=>O===void 0?"复制":g.value[O]?"复制成功":"复制",E=async O=>{const R=r.value[O],D=typeof R.content=="string"?R.content:JSON.stringify(R.content);try{await navigator.clipboard.writeText(D),O!==void 0&&(g.value[O]=!0,setTimeout(()=>{g.value[O]=!1},3e3))}catch(P){console.error("复制失败:",P),qe("复制失败,请重试")}},A=async O=>{const R=r.value.findLastIndex((P,Y)=>P.role==="user"&&Y<=O);if(R===-1){console.warn("未找到可重新生成的用户消息"),qe("无法重新生成消息");return}const D=r.value[R];if(r.value=r.value.slice(0,R),Array.isArray(D.content)){const Y=D.content.find(U=>U.type==="text")?.text||"",$=D.content.filter(U=>U.type!=="text");c.value=Y,await u(Y,$.length>0?$:void 0)}else c.value=D.content,await u(D.content)},B={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:O})=>{const R=v.value===O;return m.value&&R?"":y.h("div",{class:["assistant-actions",{"latest-assistant":R,"historical-assistant":!R}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[y.h(Pt.IconButton,{icon:Ir.IconRefresh,size:24,onClick:()=>A(O)}),y.h(ld,{effect:"light",content:x(O),placement:"right",visibleArrow:!1},()=>y.h(Pt.IconButton,{icon:Ir.IconCopy,size:24,onClick:()=>E(O)})),r.value[O].usage?y.h(cw,{usage:r.value[O].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:B,copyingStates:g,isProcessing:m,latestAssistantMessageIndex:v,copyTooltipContent:x,copyMessageToClipboard:E,regenerateMessage:A}}function hw(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:g,customAgentProvider:m}=t,v=y.ref(!1),x=()=>{y.nextTick(()=>{const R=document.querySelector("div.tr-bubble-list");R&&R.scrollTo({top:R.scrollHeight,behavior:"smooth"})})};return{showHistory:v,handleCreateConversation:()=>{f();const R=[];m.agent.responseMessages=R,r();const D=u();D.aiSdkMessages=R},handleHistorySelect:R=>{f(),o(R.id);const D=u();m.agent.responseMessages=D.aiSdkMessages,v.value=!1,x()},handleHistoryUpdateTitle:(R,D)=>{D.title=R},handleHistoryDelete:(R,D)=>{if(R.id==="delete"){if(g.currentId===D.id){qe("不允许删除当前会话");return}c(D.id)}},scrollToBottom:x}}function pw(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:g,AILogoUrl:m,show:v,addPluginFromScan:x,inputMessage:E}=t;let A=null,B=!1;const O=async $=>{if(Au("添加工具中..."),$){const U=await x($,o);qe(U?"添加工具完成":"重复添加工具或添加失败")}else qe("添加工具失败")},R=async $=>{if(/^\/[A-Za-z0-9-]{6,}$/.test($)){try{const U=await fetch(`${o}client?sessionId=${$.slice(1)}`);if(!U.ok)throw new Error(`HTTP ${U.status}`);const X=(await U.json())?.data?.sessionId;X?await O(X):qe("添加工具失败,请检查识别码是否正确"),E.value=""}catch(U){console.error("识别码处理失败:",U),qe("添加工具失败,请检查识别码是否正确"),E.value=""}return!0}return!1},D=()=>{const $=U=>{A&&(A.destroy(),A=null),A=en.createRemoter({sessionId:U||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:g?.value,logoUrl:m,onShowAIChat:()=>v.value=!0}),v.value&&A.hide()};y.watch(r,U=>{if(c!=="remoter")return;const W=!!U;A?!B&&W&&($(U),B=!0):($(U),B=W)},{immediate:!0}),g&&y.watch(g,()=>{c==="remoter"&&A&&$(r.value)},{deep:!0}),y.watch(v,U=>{A&&(U?A.hide():A.show())},{immediate:!0})},P=()=>{y.watch(r,$=>{$&&O($)})};return{handleScanSuccess:O,handleSessionIdInput:R,initialize:()=>{r.value&&O(r.value),c==="remoter"&&D(),P()},initializeRemoter:D,watchSessionIdChanges:P}}function gw(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function mw(t){return t.type.startsWith("image/")}function xw(t,r){const o=r*1024*1024;return t.size<=o}async function ww(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await gw(o.rawFile);mw(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),qe({type:"fail",message:"文件处理失败"})}return r}function yw(t={}){const r=y.ref([]),o=async u=>{if(!u||u.length===0)return;c();const f=y.unref(t.maxFileSize)||10,g=y.unref(t.supportedTypes)||["image/"];for(const m of u){if(!g.some(x=>m.type.startsWith(x))){qe({type:"fail",message:`不支持的文件类型: ${m.type}`});continue}if(!xw(m,f)){qe({type:"fail",message:`文件大小超过 ${f}MB 限制`});continue}r.value.push({rawFile:m,url:URL.createObjectURL(m)})}},c=()=>{r.value.forEach(u=>{u.url&&URL.revokeObjectURL(u.url)}),r.value=[]};return{attachments:r,handleFilesSelected:o,clearAttachments:c}}function _w(t){const{selectedModel:r,selectedModelId:o}=t,c=y.computed(()=>r.value?.multimodal?.supportImages??!1),u=y.computed(()=>r.value?.multimodal?.maxFileSize||10),f=y.computed(()=>r.value?.multimodal?.supportedMimeTypes||["image/"]),{attachments:g,handleFilesSelected:m,clearAttachments:v}=yw({maxFileSize:u,supportedTypes:f});return y.watch(o,()=>{if(g.value.length>0&&r.value){const O=r.value.multimodal?.maxFileSize||10,R=r.value.multimodal?.supportedMimeTypes||["image/"];g.value.filter(P=>{if(!P.rawFile||!R.some(U=>P.rawFile.type.startsWith(U)))return!0;const $=O*1024*1024;return P.rawFile.size>$}).length>0&&(v(),qe("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:g,onFilesSelected:O=>{m(O)},checkCanSendAttachments:()=>g.value.length>0&&!c.value?(qe("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>g.value.length===0?[]:await ww(g.value),cleanupAttachments:()=>{g.value.length>0&&v()},clearAttachments:v}}var we;(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"})(we||(we={}));var Xa=new Map([[we.QR_CODE,"QR_CODE"],[we.AZTEC,"AZTEC"],[we.CODABAR,"CODABAR"],[we.CODE_39,"CODE_39"],[we.CODE_93,"CODE_93"],[we.CODE_128,"CODE_128"],[we.DATA_MATRIX,"DATA_MATRIX"],[we.MAXICODE,"MAXICODE"],[we.ITF,"ITF"],[we.EAN_13,"EAN_13"],[we.EAN_8,"EAN_8"],[we.PDF_417,"PDF_417"],[we.RSS_14,"RSS_14"],[we.RSS_EXPANDED,"RSS_EXPANDED"],[we.UPC_A,"UPC_A"],[we.UPC_E,"UPC_E"],[we.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),qa;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(qa||(qa={}));function vw(t){return Object.values(we).includes(t)}var Jr;(function(t){t[t.SCAN_TYPE_CAMERA=0]="SCAN_TYPE_CAMERA",t[t.SCAN_TYPE_FILE=1]="SCAN_TYPE_FILE"})(Jr||(Jr={}));var Cw=(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=[Jr.SCAN_TYPE_CAMERA,Jr.SCAN_TYPE_FILE],t})(),Su=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!Xa.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,Xa.get(r))},t})(),Ya=(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})(),ko;(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"})(ko||(ko={}));var bw=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:ko.UNKWOWN_ERROR}},t})(),Ew=(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 Pn(t){return typeof t>"u"||t===null}var Ar=(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})(),Tu=(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),g=Object.keys(r),m=0,v=g;m<v.length;m++){var x=v[m];if(f.has(x))return o.logError("".concat(x," is not supported videoConstaints."),!0),!1}return!0},t})(),bi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Aw(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Zr={exports:{}},Iw=Zr.exports,Ka;function Sw(){return Ka||(Ka=1,(function(t,r){(function(o,c){c(r)})(Iw,(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 g(C,e){var n=Object.setPrototypeOf;n?n(C,e):C.__proto__=e}function m(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}),g(s,i.prototype),m(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 B{constructor(e){if(this.binarizer=e,e===null)throw new A("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,i,s){const a=this.binarizer.getLuminanceSource().crop(e,n,i,s);return new B(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new B(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new B(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class O extends x{static getChecksumInstance(){return new O}}O.kind="ChecksumException";class R{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class D{static arraycopy(e,n,i,s,a){for(;a--;)i[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class P extends x{}P.kind="IndexOutOfBoundsException";class Y extends P{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}Y.kind="ArrayIndexOutOfBoundsException";class ${static fill(e,n){for(let i=0,s=e.length;i<s;i++)e[i]=n}static fillWithin(e,n,i,s){$.rangeCheck(e.length,n,i);for(let a=n;a<i;a++)e[a]=s}static rangeCheck(e,n,i){if(n>i)throw new A("fromIndex("+n+") > toIndex("+i+")");if(n<0)throw new Y(n);if(i>e)throw new Y(i)}static asList(...e){return e}static create(e,n,i){return Array.from({length:e}).map(a=>Array.from({length:n}).fill(i))}static createInt32Array(e,n,i){return Array.from({length:e}).map(a=>Int32Array.from({length:n}).fill(i))}static equals(e,n){if(!e||!n||!e.length||!n.length||e.length!==n.length)return!1;for(let i=0,s=e.length;i<s;i++)if(e[i]!==n[i])return!1;return!0}static hashCode(e){if(e===null)return 0;let n=1;for(const i of e)n=31*n+i;return n}static fillUint8Array(e,n){for(let i=0;i!==e.length;i++)e[i]=n}static copyOf(e,n){return e.slice(0,n)}static copyOfUint8Array(e,n){if(e.length<=n){const i=new Uint8Array(n);return i.set(e),i}return e.slice(0,n)}static copyOfRange(e,n,i){const s=i-n,a=new Int32Array(s);return D.arraycopy(e,n,a,0,s),a}static binarySearch(e,n,i){i===void 0&&(i=$.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 U{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)}}U.MIN_VALUE_32_BITS=-2147483648,U.MAX_VALUE=Number.MAX_SAFE_INTEGER;class W{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=W.makeArray(e):this.bits=n)}getSize(){return this.size}getSizeInBytes(){return Math.floor((this.size+7)/8)}ensureCapacity(e){if(e>this.bits.length*32){const n=W.makeArray(e);D.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+U.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+U.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,w=(2<<(d<a?31:n&31))-(1<<h)&4294967295;if((l[d]&w)!==(i?w:0))return!1}return!0}appendBit(e){this.ensureCapacity(this.size+1),e&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++}appendBits(e,n){if(n<0||n>32)throw new A("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(let i=n;i>0;i--)this.appendBit((e>>i-1&1)===1)}appendBitArray(e){const n=e.size;this.ensureCapacity(this.size+n);for(let i=0;i<n;i++)this.appendBit(e.get(i))}xor(e){if(this.size!==e.size)throw new A("Sizes don't match");const n=this.bits;for(let i=0,s=n.length;i<s;i++)n[i]^=e.bits[i]}toBytes(e,n,i,s){for(let a=0;a<s;a++){let l=0;for(let d=0;d<8;d++)this.get(e)&&(l|=1<<7-d),e++;n[i+a]=l}}getBitArray(){return this.bits}reverse(){const e=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),i=n+1,s=this.bits;for(let a=0;a<i;a++){let l=s[a];l=l>>1&1431655765|(l&1431655765)<<1,l=l>>2&858993459|(l&858993459)<<2,l=l>>4&252645135|(l&252645135)<<4,l=l>>8&16711935|(l&16711935)<<8,l=l>>16&65535|(l&65535)<<16,e[n-a]=l}if(this.size!==i*32){const a=i*32-this.size;let l=e[0]>>>a;for(let d=1;d<i;d++){const h=e[d];l|=h<<32-a,e[d-1]=l,l=h>>>a}e[i-1]=l}this.bits=e}static makeArray(e){return new Int32Array(Math.floor((e+31)/32))}equals(e){if(!(e instanceof W))return!1;const n=e;return this.size===n.size&&$.equals(this.bits,n.bits)}hashCode(){return 31*this.size+$.hashCode(this.bits)}toString(){let e="";for(let n=0,i=this.size;n<i;n++)(n&7)===0&&(e+=" "),e+=this.get(n)?"X":".";return e}clone(){return new W(this.size,this.bits.slice())}}var X;(function(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"})(X||(X={}));var H=X;class z extends x{static getFormatInstance(){return new z}}z.kind="FormatException";var V;(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"})(V||(V={}));class M{constructor(e,n,i,...s){this.valueIdentifier=e,this.name=i,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=s,M.VALUE_IDENTIFIER_TO_ECI.set(e,this),M.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];M.VALUES_TO_ECI.set(h,this)}for(const l of s)M.NAME_TO_ECI.set(l,this)}getValueIdentifier(){return this.valueIdentifier}getName(){return this.name}getValue(){return this.values[0]}static getCharacterSetECIByValue(e){if(e<0||e>=900)throw new z("incorect value");const n=M.VALUES_TO_ECI.get(e);if(n===void 0)throw new z("incorect value");return n}static getCharacterSetECIByName(e){const n=M.NAME_TO_ECI.get(e);if(n===void 0)throw new z("incorect value");return n}equals(e){if(!(e instanceof M))return!1;const n=e;return this.getName()===n.getName()}}M.VALUE_IDENTIFIER_TO_ECI=new Map,M.VALUES_TO_ECI=new Map,M.NAME_TO_ECI=new Map,M.Cp437=new M(V.Cp437,Int32Array.from([0,2]),"Cp437"),M.ISO8859_1=new M(V.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),M.ISO8859_2=new M(V.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),M.ISO8859_3=new M(V.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),M.ISO8859_4=new M(V.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),M.ISO8859_5=new M(V.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),M.ISO8859_6=new M(V.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),M.ISO8859_7=new M(V.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),M.ISO8859_8=new M(V.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),M.ISO8859_9=new M(V.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),M.ISO8859_10=new M(V.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),M.ISO8859_11=new M(V.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),M.ISO8859_13=new M(V.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),M.ISO8859_14=new M(V.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),M.ISO8859_15=new M(V.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),M.ISO8859_16=new M(V.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),M.SJIS=new M(V.SJIS,20,"SJIS","Shift_JIS"),M.Cp1250=new M(V.Cp1250,21,"Cp1250","windows-1250"),M.Cp1251=new M(V.Cp1251,22,"Cp1251","windows-1251"),M.Cp1252=new M(V.Cp1252,23,"Cp1252","windows-1252"),M.Cp1256=new M(V.Cp1256,24,"Cp1256","windows-1256"),M.UnicodeBigUnmarked=new M(V.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),M.UTF8=new M(V.UTF8,26,"UTF8","UTF-8"),M.ASCII=new M(V.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),M.Big5=new M(V.Big5,28,"Big5"),M.GB18030=new M(V.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),M.EUC_KR=new M(V.EUC_KR,30,"EUC_KR","EUC-KR");class Ce extends x{}Ce.kind="UnsupportedOperationException";class me{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!me.isBrowser()&&e==="ISO-8859-1"}static encode(e,n){const i=this.encodingName(n);return this.customEncoder?this.customEncoder(e,i):typeof TextEncoder>"u"?this.encodeFallback(e):new TextEncoder().encode(e)}static isBrowser(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"}static encodingName(e){return typeof e=="string"?e:e.getName()}static encodingCharacterSet(e){return e instanceof M?e:M.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(me.isDecodeFallbackSupported(i)){let s="";for(let a=0,l=e.length;a<l;a++){let d=e[a].toString(16);d.length<2&&(d="0"+d),s+="%"+d}return decodeURIComponent(s)}if(i.equals(M.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new Ce(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(M.UTF8)||e.equals(M.ISO8859_1)||e.equals(M.ASCII)}static encodeFallback(e){const i=btoa(unescape(encodeURIComponent(e))).split(""),s=[];for(let a=0;a<i.length;a++)s.push(i[a].charCodeAt(0));return new Uint8Array(s)}}class le{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return me.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(H.CHARACTER_SET)!==void 0)return n.get(H.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,p=0,w=0,b=0,I=0,k=0,L=0,F=0,j=0,Q=0;const ae=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let ce=0;ce<i&&(s||a||l);ce++){const se=e[ce]&255;l&&(d>0?(se&128)===0?l=!1:d--:(se&128)!==0&&((se&64)===0?l=!1:(d++,(se&32)===0?h++:(d++,(se&16)===0?p++:(d++,(se&8)===0?w++:l=!1))))),s&&(se>127&&se<160?s=!1:se>159&&(se<192||se===215||se===247)&&Q++),a&&(b>0?se<64||se===127||se>252?a=!1:b--:se===128||se===160||se>239?a=!1:se>160&&se<224?(I++,L=0,k++,k>F&&(F=k)):se>127?(b++,k=0,L++,L>j&&(j=L)):(k=0,L=0))}return l&&d>0&&(l=!1),a&&b>0&&(a=!1),l&&(ae||h+p+w>0)?le.UTF8:a&&(le.ASSUME_SHIFT_JIS||F>=3||j>=3)?le.SHIFT_JIS:s&&a?F===2&&I===2||Q*10>=i?le.SHIFT_JIS:le.ISO88591:s?le.ISO88591:a?le.SHIFT_JIS:l?le.UTF8:le.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,p,w,b){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=w?parseInt(w.substr(1)):void 0,k;switch(b){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return me.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}le.SHIFT_JIS=M.SJIS.getName(),le.GB2312="GB2312",le.ISO88591=M.ISO8859_1.getName(),le.EUC_JP="EUC_JP",le.UTF8=M.UTF8.getName(),le.PLATFORM_DEFAULT_ENCODING=le.UTF8,le.ASSUME_SHIFT_JIS=!1;class ie{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+=le.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 re{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 re(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)===`
|
|
57
|
-
`||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 w=new re(d,h);for(let b=0;b<a;b++)s[b]&&w.set(Math.floor(b%d),Math.floor(b/d));return w}get(e,n){const i=n*this.rowSize+Math.floor(e/32);return(this.bits[i]>>>(e&31)&1)!==0}set(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]|=1<<(e&31)&4294967295}unset(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]&=~(1<<(e&31)&4294967295)}flip(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new A("input matrix dimensions do not match");const n=new W(Math.floor(this.width/32)+1),i=this.rowSize,s=this.bits;for(let a=0,l=this.height;a<l;a++){const d=a*i,h=e.getRow(a,n).getBitArray();for(let p=0;p<i;p++)s[d+p]^=h[p]}}clear(){const e=this.bits,n=e.length;for(let i=0;i<n;i++)e[i]=0}setRegion(e,n,i,s){if(n<0||e<0)throw new A("Left and top must be nonnegative");if(s<1||i<1)throw new A("Height and width must be at least 1");const a=e+i,l=n+s;if(l>this.height||a>this.width)throw new A("The region must fit inside the matrix");const d=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const w=p*d;for(let b=e;b<a;b++)h[w+Math.floor(b/32)]|=1<<(b&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new W(this.width):n.clear();const i=this.rowSize,s=this.bits,a=e*i;for(let l=0;l<i;l++)n.setBulk(l*32,s[a+l]);return n}setRow(e,n){D.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let i=new W(e),s=new W(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)i=this.getRow(a,i),s=this.getRow(n-1-a,s),i.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,i)}getEnclosingRectangle(){const e=this.width,n=this.height,i=this.rowSize,s=this.bits;let a=e,l=n,d=-1,h=-1;for(let p=0;p<n;p++)for(let w=0;w<i;w++){const b=s[p*i+w];if(b!==0){if(p<l&&(l=p),p>h&&(h=p),w*32<a){let I=0;for(;(b<<31-I&4294967295)===0;)I++;w*32+I<a&&(a=w*32+I)}if(w*32+31>d){let I=31;for(;!(b>>>I);)I--;w*32+I>d&&(d=w*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 re))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=" ",i=`
|
|
58
|
-
|
|
59
|
-
`)}return n.toString()}}class Ie extends he{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 Ie(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new Ie(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new Ie(this.delegate.rotateCounterClockwise45())}}class Te extends he{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=Te.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return Te.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 w=e[a],b=e[a+1],I=e[a+2];h=306*w+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*Te.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=Te.makeBufferFromCanvasImageData(n),this}invert(){return new Ie(this)}}Te.DEGREE_TO_RADIANS=Math.PI/180;class ge{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 De=(globalThis||bi||self||window||void 0)&&(globalThis||bi||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(w){try{p(i.next(w))}catch(b){l(b)}}function h(w){try{p(i.throw(w))}catch(b){l(b)}}function p(w){w.done?a(w.value):s(w.value).then(d,h)}p((i=i.apply(C,e||[])).next())})};class At{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 De(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 De(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new ge(n.deviceId,n.label))})}findDeviceById(e){return De(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return De(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return De(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 De(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return De(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 De(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return De(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 De(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 De(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 De(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 De(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 De(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return De(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 Z("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 Z,w=(d instanceof O||d instanceof z)&&i;if(h||w)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(d)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const i=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(i,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof O||s instanceof z,l=s instanceof Z;(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 Te(n),s=new ee(i);return new B(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const i=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=i}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let i,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(i=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=i+"px",n.style.height=s+"px",n.width=i,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Ye{constructor(e,n,i=n==null?0:8*n.length,s,a,l=D.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=D.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);D.arraycopy(n,0,i,0,n.length),D.arraycopy(e,0,i,n.length,e.length),this.resultPoints=i}}getTimestamp(){return this.timestamp}toString(){return this.text}}var It;(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"})(It||(It={}));var te=It,Ve;(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"})(Ve||(Ve={}));var Ne=Ve;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 mn{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 St{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),D.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=mn.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=mn.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;D.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=mn.addOrSubtract(n[l-a],i[l]);return new St(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 w=0;w<a;w++)l[h+w]=mn.addOrSubtract(l[h+w],d.multiply(p,s[w]))}return new St(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 St(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 St(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),w=n.buildMonomial(d,h);i=i.addOrSubtract(w),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 nn extends x{}nn.kind="ArithmeticException";class Ue extends mn{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 St(this,Int32Array.from([0])),this.one=new St(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 St(this,i)}inverse(e){if(e===0)throw new nn;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"+U.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}Ue.AZTEC_DATA_12=new Ue(4201,4096,1),Ue.AZTEC_DATA_10=new Ue(1033,1024,1),Ue.AZTEC_DATA_6=new Ue(67,64,1),Ue.AZTEC_PARAM=new Ue(19,16,1),Ue.QR_CODE_FIELD_256=new Ue(285,256,0),Ue.DATA_MATRIX_FIELD_256=new Ue(301,256,1),Ue.AZTEC_DATA_8=Ue.DATA_MATRIX_FIELD_256,Ue.MAXICODE_FIELD_64=Ue.AZTEC_DATA_6;class Ht extends x{}Ht.kind="ReedSolomonException";class Vt extends x{}Vt.kind="IllegalStateException";class An{constructor(e){this.field=e}decode(e,n){const i=this.field,s=new St(i,e),a=new Int32Array(n);let l=!0;for(let k=0;k<n;k++){const L=s.evaluateAt(i.exp(k+i.getGeneratorBase()));a[a.length-1-k]=L,L!==0&&(l=!1)}if(l)return;const d=new St(i,a),h=this.runEuclideanAlgorithm(i.buildMonomial(n,1),d,n),p=h[0],w=h[1],b=this.findErrorLocations(p),I=this.findErrorMagnitudes(w,b);for(let k=0;k<b.length;k++){const L=e.length-1-i.log(b[k]);if(L<0)throw new Ht("Bad error location");e[L]=Ue.addOrSubtract(e[L],I[k])}}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){const k=e;e=n,n=k}const s=this.field;let a=e,l=n,d=s.getZero(),h=s.getOne();for(;l.getDegree()>=(i/2|0);){let k=a,L=d;if(a=l,d=h,a.isZero())throw new Ht("r_{i-1} was zero");l=k;let F=s.getZero();const j=a.getCoefficient(a.getDegree()),Q=s.inverse(j);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const ae=l.getDegree()-a.getDegree(),ce=s.multiply(l.getCoefficient(l.getDegree()),Q);F=F.addOrSubtract(s.buildMonomial(ae,ce)),l=l.addOrSubtract(a.multiplyByMonomial(ae,ce))}if(h=F.multiply(d).addOrSubtract(L),l.getDegree()>=a.getDegree())throw new Vt("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Ht("sigmaTilde(0) was zero");const w=s.inverse(p),b=h.multiplyScalar(w),I=l.multiplyScalar(w);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 Ht("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 w=a.multiply(n[p],d),b=(w&1)===0?w|1:w&-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 xt;(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"})(xt||(xt={}));class je{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=je.convertBoolArrayToByteArray(s),l=je.getEncodedData(s),d=new 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=xt.UPPER,s=xt.UPPER,a="",l=0;for(;l<n;)if(s===xt.BINARY){if(n-l<5)break;let d=je.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=je.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const p=je.readCode(e,l,8);a+=le.castAsNonUtf8Char(p),l+=8}s=i}else{let d=s===xt.DIGIT?4:5;if(n-l<d)break;let h=je.readCode(e,l,d);l+=d;let p=je.getCharacter(s,h);p.startsWith("CTRL_")?(i=s,s=je.getTable(p.charAt(5)),p.charAt(6)==="L"&&(i=s)):(a+=p,s=i)}return a}static getTable(e){switch(e){case"L":return xt.LOWER;case"P":return xt.PUNCT;case"M":return xt.MIXED;case"D":return xt.DIGIT;case"B":return xt.BINARY;case"U":default:return xt.UPPER}}static getCharacter(e,n){switch(e){case xt.UPPER:return je.UPPER_TABLE[n];case xt.LOWER:return je.LOWER_TABLE[n];case xt.MIXED:return je.MIXED_TABLE[n];case xt.PUNCT:return je.PUNCT_TABLE[n];case xt.DIGIT:return je.DIGIT_TABLE[n];default:throw new Vt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=Ue.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=Ue.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=Ue.AZTEC_DATA_10):(i=12,n=Ue.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new z;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=je.readCode(e,l,i);try{new An(n).decode(d,a-s)}catch(I){throw new z(I)}let h=(1<<i)-1,p=0;for(let I=0;I<s;I++){let k=d[I];if(k===0||k===h)throw new z;(k===1||k===h-1)&&p++}let w=new Array(s*i-p),b=0;for(let I=0;I<s;I++){let k=d[I];if(k===1||k===h-1)w.fill(k>1,b,b+i-1),b+=i-1;else for(let L=i-1;L>=0;--L)w[b++]=(k&1<<L)!==0}return w}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*U.truncDivision(U.truncDivision(s,2)-1,15),h=s/2,p=U.truncDivision(d,2);for(let w=0;w<h;w++){let b=w+U.truncDivision(w,15);a[h-w-1]=p-b-1,a[h+w]=p+b+1}}for(let d=0,h=0;d<i;d++){let p=(i-d)*4+(n?9:12),w=d*2,b=s-1-w;for(let I=0;I<p;I++){let k=I*2;for(let L=0;L<2;L++)l[h+k+L]=e.get(a[w+L],a[w+I]),l[h+2*p+k+L]=e.get(a[w+I],a[b-L]),l[h+4*p+k+L]=e.get(a[b-L],a[b-I]),l[h+6*p+k+L]=e.get(a[b-I],a[w+L])}h+=p*8}return l}static readCode(e,n,i){let s=0;for(let a=n;a<n+i;a++)s<<=1,e[a]&&(s|=1);return s}static readByte(e,n){let i=e.length-n;return i>=8?je.readCode(e,n,8):je.readCode(e,n,i)<<8-i}static convertBoolArrayToByteArray(e){let n=new Uint8Array((e.length+7)/8);for(let i=0;i<n.length;i++)n[i]=je.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}je.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],je.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],je.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
|
|
60
|
-
`,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],je.PUNCT_TABLE=["","\r",`\r
|
|
61
|
-
`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],je.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class ze{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 In{static floatToIntBits(e){return e}}In.MAX_VALUE=Number.MAX_SAFE_INTEGER;class S{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof S){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]),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 ze.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 ue{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class dt extends ue{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 pt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=pt.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 Z}detect(){let e=this.leftInit,n=this.rightInit,i=this.upInit,s=this.downInit,a=!1,l=!0,d=!1,h=!1,p=!1,w=!1,b=!1;const I=this.width,k=this.height;for(;l;){l=!1;let L=!0;for(;(L||!h)&&n<I;)L=this.containsBlackPoint(i,s,n,!1),L?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let F=!0;for(;(F||!p)&&s<k;)F=this.containsBlackPoint(e,n,s,!0),F?(s++,l=!0,p=!0):p||s++;if(s>=k){a=!0;break}let j=!0;for(;(j||!w)&&e>=0;)j=this.containsBlackPoint(i,s,e,!1),j?(e--,l=!0,w=!0):w||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 L=n-e;let F=null;for(let ce=1;F===null&&ce<L;ce++)F=this.getBlackPointOnSegment(e,s-ce,e+ce,s);if(F==null)throw new Z;let j=null;for(let ce=1;j===null&&ce<L;ce++)j=this.getBlackPointOnSegment(e,i+ce,e+ce,i);if(j==null)throw new Z;let Q=null;for(let ce=1;Q===null&&ce<L;ce++)Q=this.getBlackPointOnSegment(n,i+ce,n-ce,i);if(Q==null)throw new Z;let ae=null;for(let ce=1;ae===null&&ce<L;ce++)ae=this.getBlackPointOnSegment(n,s-ce,n-ce,s);if(ae==null)throw new Z;return this.centerEdges(ae,F,Q,j)}else throw new Z}getBlackPointOnSegment(e,n,i,s){const a=ze.round(ze.distance(e,n,i,s)),l=(i-e)/a,d=(s-n)/a,h=this.image;for(let p=0;p<a;p++){const w=ze.round(e+p*l),b=ze.round(n+p*d);if(h.get(w,b))return new S(w,b)}return null}centerEdges(e,n,i,s){const a=e.getX(),l=e.getY(),d=n.getX(),h=n.getY(),p=i.getX(),w=i.getY(),b=s.getX(),I=s.getY(),k=pt.CORR;return a<this.width/2?[new S(b-k,I+k),new S(d+k,h+k),new S(p-k,w-k),new S(a+k,l-k)]:[new S(b+k,I+k),new S(d+k,h-k),new S(p-k,w+k),new S(a-k,l-k)]}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}}pt.INIT_SIZE=10,pt.CORR=1;class Sn{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 Z;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 Z;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 rn{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,w,b,I,k,L,F,j){const Q=rn.quadrilateralToSquare(e,n,i,s,a,l,d,h);return rn.squareToQuadrilateral(p,w,b,I,k,L,F,j).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,w=this.a32,b=this.a33;for(let I=0;I<n;I+=2){const k=e[I],L=e[I+1],F=a*k+h*L+b;e[I]=(i*k+l*L+p)/F,e[I+1]=(s*k+d*L+w)/F}}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,w=this.a32,b=this.a33,I=e.length;for(let k=0;k<I;k++){const L=e[k],F=n[k],j=a*L+h*F+b;e[k]=(i*L+l*F+p)/j,n[k]=(s*L+d*F+w)/j}}static squareToQuadrilateral(e,n,i,s,a,l,d,h){const p=e-i+a-d,w=n-s+l-h;if(p===0&&w===0)return new rn(i-e,a-i,e,s-n,l-s,n,0,0,1);{const b=i-a,I=d-a,k=s-l,L=h-l,F=b*L-I*k,j=(p*L-I*w)/F,Q=(b*w-p*k)/F;return new rn(i-e+j*i,d-e+Q*d,e,s-n+j*s,h-n+Q*h,n,j,Q,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return rn.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new rn(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 rn(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 ri extends Sn{sampleGrid(e,n,i,s,a,l,d,h,p,w,b,I,k,L,F,j,Q,ae,ce){const se=rn.quadrilateralToQuadrilateral(s,a,l,d,h,p,w,b,I,k,L,F,j,Q,ae,ce);return this.sampleGridWithTransform(e,n,i,se)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new Z;const a=new re(n,i),l=new Float32Array(2*n);for(let d=0;d<i;d++){const h=l.length,p=d+.5;for(let w=0;w<h;w+=2)l[w]=w/2+.5,l[w+1]=p;s.transformPoints(l),Sn.checkAndNudgePoints(e,l);try{for(let w=0;w<h;w+=2)e.get(Math.floor(l[w]),Math.floor(l[w+1]))&&a.set(w/2,d)}catch{throw new Z}}return a}}class on{static setGridSampler(e){on.gridSampler=e}static getInstance(){return on.gridSampler}}on.gridSampler=new ri;class Lt{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new S(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class ii{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 dt(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 Z;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(U.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new Z}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 An(Ue.AZTEC_PARAM).decode(l,a)}catch{throw new Z}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),k=this.getFirstDifferent(s,l,-1,1),L=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let F=this.distancePoint(L,b)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(F<.75||F>1.25||!this.isWhiteOrBlackRectangle(b,I,k,L))break}n=b,i=I,s=k,a=L,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new Z;this.compact=this.nbCenterLayers===5;let d=new S(n.getX()+.5,n.getY()-.5),h=new S(i.getX()+.5,i.getY()+.5),p=new S(s.getX()-.5,s.getY()+.5),w=new S(a.getX()-.5,a.getY()-.5);return this.expandSquare([d,h,p,w],2*this.nbCenterLayers-3,2*this.nbCenterLayers)}getMatrixCenter(){let e,n,i,s;try{let d=new pt(this.image).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{let h=this.image.getWidth()/2,p=this.image.getHeight()/2;e=this.getFirstDifferent(new Lt(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(h+7,p+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(h-7,p-7),!1,-1,-1).toResultPoint()}let a=ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4);try{let d=new pt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new Lt(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Lt(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new Lt(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new Lt(a-7,l-7),!1,-1,-1).toResultPoint()}return a=ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4),new Lt(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=on.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,w=l*(n.getY()-e.getY())/a;for(let b=0;b<i;b++)this.image.get(ze.round(d+b*p),ze.round(h+b*w))&&(s|=1<<i-b-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new Lt(e.getX()-a,e.getY()+a),n=new Lt(n.getX()-a,n.getY()-a),i=new Lt(i.getX()+a,i.getY()-a),s=new Lt(s.getX()+a,s.getY()+a);let l=this.getColor(s,e);if(l===0)return!1;let d=this.getColor(e,n);return d!==l||(d=this.getColor(n,i),d!==l)?!1:(d=this.getColor(i,s),d===l)}getColor(e,n){let i=this.distancePoint(e,n),s=(n.getX()-e.getX())/i,a=(n.getY()-e.getY())/i,l=0,d=e.getX(),h=e.getY(),p=this.image.get(e.getX(),e.getY()),w=Math.ceil(i);for(let I=0;I<w;I++)d+=s,h+=a,this.image.get(ze.round(d),ze.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 Lt(a,l)}expandSquare(e,n,i){let s=i/(2*n),a=e[0].getX()-e[2].getX(),l=e[0].getY()-e[2].getY(),d=(e[0].getX()+e[2].getX())/2,h=(e[0].getY()+e[2].getY())/2,p=new S(d+s*a,h+s*l),w=new S(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 S(d+s*a,h+s*l),I=new S(d-s*a,h-s*l);return[p,b,w,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=ze.round(e.getX()),i=ze.round(e.getY());return this.isValid(n,i)}distancePoint(e,n){return ze.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return ze.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*(U.truncDivision(this.nbLayers-4,8)+1)+15}}class hr{decode(e,n=null){let i=null,s=new ii(e.getBlackMatrix()),a=null,l=null;try{let w=s.detectMirror(!1);a=w.getPoints(),this.reportFoundResultPoints(n,a),l=new je().decode(w)}catch(w){i=w}if(l==null)try{let w=s.detectMirror(!0);a=w.getPoints(),this.reportFoundResultPoints(n,a),l=new je().decode(w)}catch(w){throw i??w}let d=new Ye(l.getText(),l.getRawBytes(),l.getNumBits(),a,te.AZTEC,D.currentTimeMillis()),h=l.getByteSegments();h!=null&&d.putMetadata(Ne.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&d.putMetadata(Ne.ERROR_CORRECTION_LEVEL,p),d}reportFoundResultPoints(e,n){if(e!=null){let i=e.get(H.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class Fi extends At{constructor(e=500){super(new hr,e)}}class wt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(H.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),d=l.getResultMetadata();let h=270;d!==null&&d.get(Ne.ORIENTATION)===!0&&(h=h+d.get(Ne.ORIENTATION)%360),l.putMetadata(Ne.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const w=a.getHeight();for(let b=0;b<p.length;b++)p[b]=new S(w-p[b].getY()-1,p[b].getX())}return l}else throw new Z}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new W(i);const l=n&&n.get(H.TRY_HARDER)===!0,d=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const p=Math.trunc(s/2);for(let w=0;w<h;w++){const b=Math.trunc((w+1)/2),I=(w&1)===0,k=p+d*(I?b:-b);if(k<0||k>=s)break;try{a=e.getBlackRow(k,a)}catch{continue}for(let L=0;L<2;L++){if(L===1&&(a.reverse(),n&&n.get(H.NEED_RESULT_POINT_CALLBACK)===!0)){const F=new Map;n.forEach((j,Q)=>F.set(Q,j)),F.delete(H.NEED_RESULT_POINT_CALLBACK),n=F}try{const F=this.decodeRow(k,a,n);if(L===1){F.putMetadata(Ne.ORIENTATION,180);const j=F.getResultPoints();j!==null&&(j[0]=new S(i-j[0].getX()-1,j[0].getY()),j[1]=new S(i-j[1].getX()-1,j[1].getY()))}return F}catch{}}}throw new Z}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 Z;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 Z}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 Z;wt.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 w=e[p],b=n[p]*d,I=w>b?w-b:b-w;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class pe extends wt{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 w=pe.MAX_AVG_VARIANCE,b=-1;for(let I=pe.CODE_START_A;I<=pe.CODE_START_C;I++){const k=wt.patternMatchVariance(a,pe.CODE_PATTERNS[I],pe.MAX_INDIVIDUAL_VARIANCE);k<w&&(w=k,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 Z}static decodeCode(e,n,i){wt.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 Z}decodeRow(e,n,i){const s=i&&i.get(H.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 z}let w=!1,b=!1,I="",k=a[0],L=a[1];const F=Int32Array.from([0,0,0,0,0,0]);let j=0,Q=0,ae=l,ce=0,se=!0,Ze=!1,ke=!1;for(;!w;){const Cr=b;switch(b=!1,j=Q,Q=pe.decodeCode(n,F,L),h[d++]=Q,Q!==pe.CODE_STOP&&(se=!0),Q!==pe.CODE_STOP&&(ce++,ae+=ce*Q),k=L,L+=F.reduce((od,sd)=>od+sd,0),Q){case pe.CODE_START_A:case pe.CODE_START_B:case pe.CODE_START_C:throw new z}switch(p){case pe.CODE_CODE_A:if(Q<64)ke===Ze?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),ke=!1;else if(Q<96)ke===Ze?I+=String.fromCharCode(Q-64):I+=String.fromCharCode(Q+64),ke=!1;else switch(Q!==pe.CODE_STOP&&(se=!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:!Ze&&ke?(Ze=!0,ke=!1):Ze&&ke?(Ze=!1,ke=!1):ke=!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:w=!0;break}break;case pe.CODE_CODE_B:if(Q<96)ke===Ze?I+=String.fromCharCode(32+Q):I+=String.fromCharCode(32+Q+128),ke=!1;else switch(Q!==pe.CODE_STOP&&(se=!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:!Ze&&ke?(Ze=!0,ke=!1):Ze&&ke?(Ze=!1,ke=!1):ke=!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:w=!0;break}break;case pe.CODE_CODE_C:if(Q<100)Q<10&&(I+="0"),I+=Q;else switch(Q!==pe.CODE_STOP&&(se=!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:w=!0;break}break}Cr&&(p=p===pe.CODE_CODE_A?pe.CODE_CODE_B:pe.CODE_CODE_A)}const Jt=L-k;if(L=n.getNextUnset(L),!n.isRange(L,Math.min(n.getSize(),L+(L-k)/2),!1))throw new Z;if(ae-=ce*j,ae%103!==j)throw new O;const wn=I.length;if(wn===0)throw new Z;wn>0&&se&&(p===pe.CODE_CODE_C?I=I.substring(0,wn-2):I=I.substring(0,wn-1));const Qt=(a[1]+a[0])/2,it=k+Jt/2,zt=h.length,sn=new Uint8Array(zt);for(let Cr=0;Cr<zt;Cr++)sn[Cr]=h[Cr];const vr=[new S(Qt,e),new S(it,e)];return new Ye(I,sn,0,vr,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 bt extends wt{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=bt.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,p;do{bt.recordPattern(n,l,s);let F=bt.toNarrowWidePattern(s);if(F<0)throw new Z;h=bt.patternToChar(F),this.decodeRowResult+=h,p=l;for(let j of s)l+=j;l=n.getNextSet(l)}while(h!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let w=0;for(let F of s)w+=F;let b=l-p-w;if(l!==d&&b*2<w)throw new Z;if(this.usingCheckDigit){let F=this.decodeRowResult.length-1,j=0;for(let Q=0;Q<F;Q++)j+=bt.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Q));if(this.decodeRowResult.charAt(F)!==bt.ALPHABET_STRING.charAt(j%43))throw new O;this.decodeRowResult=this.decodeRowResult.substring(0,F)}if(this.decodeRowResult.length===0)throw new Z;let I;this.extendedMode?I=bt.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let k=(a[1]+a[0])/2,L=p+w/2;return new Ye(I,null,0,[new S(k,e),new S(L,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)===bt.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 Z}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<bt.CHARACTER_ENCODINGS.length;n++)if(bt.CHARACTER_ENCODINGS[n]===e)return bt.ALPHABET_STRING.charAt(n);if(e===bt.ASTERISK_ENCODING)return"*";throw new Z}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 z;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new z;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 z;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new z;break}i+=d,s++}else i+=a}return i}}bt.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",bt.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],bt.ASTERISK_ENCODING=148;class et extends wt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new ie;et.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(H.ALLOWED_LENGTHS)),h==null&&(h=et.DEFAULT_ALLOWED_LENGTHS);let p=d.length,w=!1,b=0;for(let L of h){if(p===L){w=!0;break}L>b&&(b=L)}if(!w&&p>b&&(w=!0),!w)throw new z;const I=[new S(s[1],e),new S(a[0],e)];return new Ye(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;){wt.recordPattern(e,n,a);for(let p=0;p<5;p++){let w=2*p;l[p]=a[w],d[p]=a[w+1]}let h=et.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=et.skipWhiteSpace(e),i=et.findGuardPattern(e,n,et.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 Z}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new Z;return i}decodeEnd(e){e.reverse();try{let n=et.skipWhiteSpace(e),i;try{i=et.findGuardPattern(e,n,et.END_PATTERN_REVERSED[0])}catch(a){a instanceof Z&&(i=et.findGuardPattern(e,n,et.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 w=n;w<l;w++)if(e.get(w)!==d)a[h]++;else{if(h===s-1){if(wt.patternMatchVariance(a,i,et.MAX_INDIVIDUAL_VARIANCE)<et.MAX_AVG_VARIANCE)return[p,w];p+=a[0]+a[1],D.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,d=!d}throw new Z}static decodeDigit(e){let n=et.MAX_AVG_VARIANCE,i=-1,s=et.PATTERNS.length;for(let a=0;a<s;a++){let l=et.PATTERNS[a],d=wt.patternMatchVariance(e,l,et.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new Z}}et.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])],et.MAX_AVG_VARIANCE=.38,et.MAX_INDIVIDUAL_VARIANCE=.5,et.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],et.START_PATTERN=Int32Array.from([1,1,1,1]),et.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class _e extends wt{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=_e.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 _e.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return _e.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 z;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 z;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return _e.findGuardPattern(e,n,!1,_e.START_END_PATTERN,new Int32Array(_e.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,w=i;for(let b=n;b<l;b++)if(e.get(b)!==w)a[d]++;else{if(d===p-1){if(wt.patternMatchVariance(a,s,_e.MAX_INDIVIDUAL_VARIANCE)<_e.MAX_AVG_VARIANCE)return Int32Array.from([h,b]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let k=0;k<d-1;k++)a[k]=I[k];a[d-1]=0,a[d]=0,d--}else d++;a[d]=1,w=!w}throw new Z}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],w=wt.patternMatchVariance(n,p,_e.MAX_INDIVIDUAL_VARIANCE);w<a&&(a=w,l=h)}if(l>=0)return l;throw new Z}}_e.MAX_AVG_VARIANCE=.48,_e.MAX_INDIVIDUAL_VARIANCE=.7,_e.START_END_PATTERN=Int32Array.from([1,1,1]),_e.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),_e.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),_e.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 be{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=be.parseExtensionString(l),h=[new S((i[0]+i[1])/2,e),new S(a,e)],p=new Ye(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 w=_e.decodeDigit(e,s,l,_e.L_AND_G_PATTERNS);i+=String.fromCharCode(48+w%10);for(let b of s)l+=b;w>=10&&(d|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new Z;let h=this.determineCheckDigit(d);if(be.extensionChecksum(i.toString())!==h)throw new Z;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 Z}static parseExtensionString(e){if(e.length!==5)return null;let n=be.parseExtension5String(e);return n==null?null:new Map([[Ne.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 Ge{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=Ge.parseExtensionString(l),h=[new S((i[0]+i[1])/2,e),new S(a,e)],p=new Ye(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=_e.decodeDigit(e,s,l,_e.L_AND_G_PATTERNS);i+=String.fromCharCode(48+p%10);for(let w of s)l+=w;p>=10&&(d|=1<<1-h),h!==1&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==2)throw new Z;if(parseInt(i.toString())%4!==d)throw new Z;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ne.ISSUE_NUMBER,parseInt(e)]])}}class Jn{static decodeRow(e,n,i){let s=_e.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new be().decodeRow(e,n,s)}catch{return new Ge().decodeRow(e,n,s)}}}Jn.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class We extends _e{constructor(){super(),this.decodeRowStringBuffer="",We.L_AND_G_PATTERNS=We.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=We.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];We.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=We.findStartGuardPattern(n),a=i==null?null:i.get(H.NEED_RESULT_POINT_CALLBACK);if(a!=null){const se=new S((s[0]+s[1])/2,e);a.foundPossibleResultPoint(se)}let l=this.decodeMiddle(n,s,this.decodeRowStringBuffer),d=l.rowOffset,h=l.resultString;if(a!=null){const se=new S(d,e);a.foundPossibleResultPoint(se)}let p=this.decodeEnd(n,d);if(a!=null){const se=new S((p[0]+p[1])/2,e);a.foundPossibleResultPoint(se)}let w=p[1],b=w+(w-p[0]);if(b>=n.getSize()||!n.isRange(w,b,!1))throw new Z;let I=h.toString();if(I.length<8)throw new z;if(!We.checkChecksum(I))throw new O;let k=(s[1]+s[0])/2,L=(p[1]+p[0])/2,F=this.getBarcodeFormat(),j=[new S(k,e),new S(L,e)],Q=new Ye(I,null,0,j,F,new Date().getTime()),ae=0;try{let se=Jn.decodeRow(e,n,p[1]);Q.putMetadata(Ne.UPC_EAN_EXTENSION,se.getText()),Q.putAllMetadata(se.getResultMetadata()),Q.addResultPoints(se.getResultPoints()),ae=se.getText().length}catch{}let ce=i==null?null:i.get(H.ALLOWED_EAN_EXTENSIONS);if(ce!=null){let se=!1;for(let Ze in ce)if(ae.toString()===Ze){se=!0;break}if(!se)throw new Z}return Q}decodeEnd(e,n){return We.findGuardPattern(e,n,!1,We.START_END_PATTERN,new Int32Array(We.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return We.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return We.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 z;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 z;i+=a}return(1e3-i)%10}}class Qn extends We{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 w=We.decodeDigit(e,s,l,We.L_AND_G_PATTERNS);i+=String.fromCharCode(48+w%10);for(let b of s)l+=b;w>=10&&(d|=1<<5-p)}i=Qn.determineFirstDigit(i,d),l=We.findGuardPattern(e,l,!0,We.MIDDLE_PATTERN,new Int32Array(We.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let w=We.decodeDigit(e,s,l,We.L_PATTERNS);i+=String.fromCharCode(48+w);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 Z}}Qn.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class Qo extends We{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=We.decodeDigit(e,s,l,We.L_PATTERNS);i+=String.fromCharCode(48+p);for(let w of s)l+=w}l=We.findGuardPattern(e,l,!0,We.MIDDLE_PATTERN,new Int32Array(We.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=We.decodeDigit(e,s,l,We.L_PATTERNS);i+=String.fromCharCode(48+p);for(let w of s)l+=w}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return te.EAN_8}}class es extends We{constructor(){super(...arguments),this.ean13Reader=new Qn}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 Ye(n.substring(1),null,null,e.getResultPoints(),te.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new Z}reset(){this.ean13Reader.reset()}}class xn extends We{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 w=xn.decodeDigit(e,s,l,xn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+w%10);for(let b of s)l+=b;w>=10&&(d|=1<<5-p)}let h=xn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return xn.findGuardPatternWithoutCounters(e,n,!0,xn.MIDDLE_END_PATTERN)}checkChecksum(e){return We.checkChecksum(xn.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 Z.getNotFoundInstance()}getBarcodeFormat(){return te.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new ie;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()}}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 Ui extends wt{constructor(e){super();let n=e==null?null:e.get(H.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new Qn),i.push(new es),i.push(new Qo),i.push(new xn)):(n.indexOf(te.EAN_13)>-1&&i.push(new Qn),n.indexOf(te.UPC_A)>-1&&i.push(new es),n.indexOf(te.EAN_8)>-1&&i.push(new Qo),n.indexOf(te.UPC_E)>-1&&i.push(new xn)),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(H.POSSIBLE_FORMATS),h=d==null||d.includes(te.UPC_A);if(l&&h){const p=a.getRawBytes(),w=new Ye(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),te.UPC_A);return w.putAllMetadata(a.getResultMetadata()),w}return a}catch{}throw new Z}reset(){for(let e of this.readers)e.reset()}}class Zt extends wt{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(wt.patternMatchVariance(e,n[i],Zt.MAX_INDIVIDUAL_VARIANCE)<Zt.MAX_AVG_VARIANCE)return i;throw new Z}static count(e){return ze.sum(new Int32Array(e))}static increment(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]>s&&(s=n[a],i=a);e[i]++}static decrement(e,n){let i=0,s=n[0];for(let a=1;a<e.length;a++)n[a]<s&&(s=n[a],i=a);e[i]--}static isFinderPattern(e){let n=e[0]+e[1],i=n+e[2]+e[3],s=n/i;if(s>=Zt.MIN_FINDER_PATTERN_RATIO&&s<=Zt.MAX_FINDER_PATTERN_RATIO){let a=Number.MAX_SAFE_INTEGER,l=Number.MIN_SAFE_INTEGER;for(let d of e)d>l&&(l=d),d<a&&(a=d);return l<10*a}return!1}}Zt.MAX_AVG_VARIANCE=.2,Zt.MAX_INDIVIDUAL_VARIANCE=.45,Zt.MIN_FINDER_PATTERN_RATIO=9.5/12,Zt.MAX_FINDER_PATTERN_RATIO=12.5/14;class pr{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 pr))return!1;const n=e;return this.value===n.value&&this.checksumPortion===n.checksumPortion}hashCode(){return this.value^this.checksumPortion}}class oi{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 S(i,a)),this.resultPoints.push(new S(s,a))}getValue(){return this.value}getStartEnd(){return this.startEnd}getResultPoints(){return this.resultPoints}equals(e){if(!(e instanceof oi))return!1;const n=e;return this.value===n.value}hashCode(){return this.value}}class Tn{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 w=Tn.combins(s-p-1,d-h-2);if(i&&l===0&&s-p-(d-h-1)>=d-h-1&&(w-=Tn.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+=Tn.combins(s-p-I-1,d-h-3);w-=b*(d-1-h)}else s-p>n&&w--;a+=w}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 ku{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new W(i),a=0,d=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(d&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let p=e[h],w=p.getLeftChar().getValue();for(let b=11;b>=0;--b)(w&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 er{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 qt extends zi{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===qt.FNC1}}qt.FNC1="$";class tr 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 fn extends zi{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new z;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===fn.FNC1}isSecondDigitFNC1(){return this.secondDigit===fn.FNC1}isAnyFNC1(){return this.firstDigit===fn.FNC1||this.secondDigit===fn.FNC1}}fn.FNC1=10;class xe{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new Z;let n=e.substring(0,2);for(let a of xe.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===xe.VARIABLE_LENGTH?xe.processVariableAI(2,a[2],e):xe.processFixedAI(2,a[1],e);if(e.length<3)throw new Z;let i=e.substring(0,3);for(let a of xe.THREE_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===xe.VARIABLE_LENGTH?xe.processVariableAI(3,a[2],e):xe.processFixedAI(3,a[1],e);for(let a of xe.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===xe.VARIABLE_LENGTH?xe.processVariableAI(4,a[2],e):xe.processFixedAI(4,a[1],e);if(e.length<4)throw new Z;let s=e.substring(0,4);for(let a of xe.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===xe.VARIABLE_LENGTH?xe.processVariableAI(4,a[2],e):xe.processFixedAI(4,a[1],e);throw new Z}static processFixedAI(e,n,i){if(i.length<e)throw new Z;let s=i.substring(0,e);if(i.length<e+n)throw new Z;let a=i.substring(e,e+n),l=i.substring(e+n),d="("+s+")"+a,h=xe.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=xe.parseFieldsInGeneralPurpose(d);return p==null?h:h+p}}xe.VARIABLE_LENGTH=[],xe.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",xe.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",xe.VARIABLE_LENGTH,20],["22",xe.VARIABLE_LENGTH,29],["30",xe.VARIABLE_LENGTH,8],["37",xe.VARIABLE_LENGTH,8],["90",xe.VARIABLE_LENGTH,30],["91",xe.VARIABLE_LENGTH,30],["92",xe.VARIABLE_LENGTH,30],["93",xe.VARIABLE_LENGTH,30],["94",xe.VARIABLE_LENGTH,30],["95",xe.VARIABLE_LENGTH,30],["96",xe.VARIABLE_LENGTH,30],["97",xe.VARIABLE_LENGTH,3],["98",xe.VARIABLE_LENGTH,30],["99",xe.VARIABLE_LENGTH,30]],xe.THREE_DIGIT_DATA_LENGTH=[["240",xe.VARIABLE_LENGTH,30],["241",xe.VARIABLE_LENGTH,30],["242",xe.VARIABLE_LENGTH,6],["250",xe.VARIABLE_LENGTH,30],["251",xe.VARIABLE_LENGTH,30],["253",xe.VARIABLE_LENGTH,17],["254",xe.VARIABLE_LENGTH,20],["400",xe.VARIABLE_LENGTH,30],["401",xe.VARIABLE_LENGTH,30],["402",17],["403",xe.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",xe.VARIABLE_LENGTH,20],["421",xe.VARIABLE_LENGTH,15],["422",3],["423",xe.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],xe.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",xe.VARIABLE_LENGTH,15],["391",xe.VARIABLE_LENGTH,18],["392",xe.VARIABLE_LENGTH,15],["393",xe.VARIABLE_LENGTH,18],["703",xe.VARIABLE_LENGTH,30]],xe.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",xe.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",xe.VARIABLE_LENGTH,20],["8003",xe.VARIABLE_LENGTH,30],["8004",xe.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",xe.VARIABLE_LENGTH,30],["8008",xe.VARIABLE_LENGTH,12],["8018",18],["8020",xe.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",xe.VARIABLE_LENGTH,70],["8200",xe.VARIABLE_LENGTH,70]];class gr{constructor(e){this.buffer=new ie,this.information=e}decodeAllCodes(e,n){let i=n,s=null;do{let a=this.decodeGeneralPurposeField(i,s),l=xe.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 fn(this.information.getSize(),fn.FNC1,fn.FNC1):new fn(this.information.getSize(),a-1,fn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new fn(e+7,i,s)}extractNumericValueFromBitArray(e,n){return gr.extractNumericValueFromBitArray(this.information,e,n)}static extractNumericValueFromBitArray(e,n,i){let s=0;for(let a=0;a<i;++a)e.get(n+a)&&(s|=1<<i-a-1);return s}decodeGeneralPurposeField(e,n){this.buffer.setLengthToZero(),n!=null&&this.buffer.append(n),this.current.setPosition(e);let i=this.parseBlocks();return i!=null&&i.isRemaining()?new tr(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new tr(this.current.getPosition(),this.buffer.toString())}parseBlocks(){let e,n;do{let i=this.current.getPosition();if(this.current.isAlpha()?(n=this.parseAlphaBlock(),e=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),e=n.isFinished()):(n=this.parseNumericBlock(),e=n.isFinished()),!(i!==this.current.getPosition())&&!e)break}while(!e);return n.getDecodedInformation()}parseNumericBlock(){for(;this.isStillNumeric(this.current.getPosition());){let e=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFirstDigitFNC1()){let n;return e.isSecondDigitFNC1()?n=new tr(this.current.getPosition(),this.buffer.toString()):n=new tr(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new er(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new er(!1)}parseIsoIec646Block(){for(;this.isStillIsoIec646(this.current.getPosition());){let e=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new er(!1)}parseAlphaBlock(){for(;this.isStillAlpha(this.current.getPosition());){let e=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(e.getNewPosition()),e.isFNC1()){let n=new tr(this.current.getPosition(),this.buffer.toString());return new er(!0,n)}this.buffer.append(e.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new er(!1)}isStillIsoIec646(e){if(e+5>this.information.getSize())return!1;let n=this.extractNumericValueFromBitArray(e,5);if(n>=5&&n<16)return!0;if(e+7>this.information.getSize())return!1;let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<116)return!0;if(e+8>this.information.getSize())return!1;let s=this.extractNumericValueFromBitArray(e,8);return s>=232&&s<253}decodeIsoIec646(e){let n=this.extractNumericValueFromBitArray(e,5);if(n===15)return new qt(e+5,qt.FNC1);if(n>=5&&n<15)return new qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new qt(e+7,""+(i+1));if(i>=90&&i<116)return new qt(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 z}return new qt(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 qt(e+5,qt.FNC1);if(n>=5&&n<15)return new qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new qt(e+6,""+(i+33));let s;switch(i){case 58:s="*";break;case 59:s=",";break;case 60:s="-";break;case 61:s=".";break;case 62:s="/";break;default:throw new Vt("Decoding invalid alphanumeric value: "+i)}return new qt(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 gr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class Yt 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)}Yt.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)}}Yt.GTIN_SIZE=40;class mr extends Yt{constructor(e){super(e)}parseInformation(){let e=new ie;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(mr.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,mr.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,mr.HEADER_SIZE+44)}}mr.HEADER_SIZE=4;class si extends Vi{constructor(e){super(e)}parseInformation(){let e=new ie;return this.getGeneralDecoder().decodeAllCodes(e,si.HEADER_SIZE)}}si.HEADER_SIZE=5;class ai extends Yt{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 Nn extends ai{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Nn.HEADER_SIZE+ai.GTIN_SIZE+Nn.WEIGHT_SIZE)throw new Z;let e=new ie;return this.encodeCompressedGtin(e,Nn.HEADER_SIZE),this.encodeCompressedWeight(e,Nn.HEADER_SIZE+ai.GTIN_SIZE,Nn.WEIGHT_SIZE),e.toString()}}Nn.HEADER_SIZE=5,Nn.WEIGHT_SIZE=15;class Ru extends Nn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Mu extends Nn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class On extends Yt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<On.HEADER_SIZE+Yt.GTIN_SIZE)throw new Z;let e=new ie;this.encodeCompressedGtin(e,On.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(On.HEADER_SIZE+Yt.GTIN_SIZE,On.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(On.HEADER_SIZE+Yt.GTIN_SIZE+On.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}On.HEADER_SIZE=8,On.LAST_DIGIT_SIZE=2;class jt extends Yt{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<jt.HEADER_SIZE+Yt.GTIN_SIZE)throw new Z;let e=new ie;this.encodeCompressedGtin(e,jt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(jt.HEADER_SIZE+Yt.GTIN_SIZE,jt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(jt.HEADER_SIZE+Yt.GTIN_SIZE+jt.LAST_DIGIT_SIZE,jt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(jt.HEADER_SIZE+Yt.GTIN_SIZE+jt.LAST_DIGIT_SIZE+jt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}jt.HEADER_SIZE=8,jt.LAST_DIGIT_SIZE=2,jt.FIRST_THREE_DIGITS_SIZE=10;class ft extends ai{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=ft.HEADER_SIZE+ft.GTIN_SIZE+ft.WEIGHT_SIZE+ft.DATE_SIZE)throw new Z;let e=new ie;return this.encodeCompressedGtin(e,ft.HEADER_SIZE),this.encodeCompressedWeight(e,ft.HEADER_SIZE+ft.GTIN_SIZE,ft.WEIGHT_SIZE),this.encodeCompressedDate(e,ft.HEADER_SIZE+ft.GTIN_SIZE+ft.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,ft.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}}ft.HEADER_SIZE=8,ft.WEIGHT_SIZE=20,ft.DATE_SIZE=16;function ts(C){try{if(C.get(1))return new mr(C);if(!C.get(2))return new si(C);switch(gr.extractNumericValueFromBitArray(C,1,4)){case 4:return new Ru(C);case 5:return new Mu(C)}switch(gr.extractNumericValueFromBitArray(C,1,5)){case 12:return new On(C);case 13:return new jt(C)}switch(gr.extractNumericValueFromBitArray(C,1,7)){case 56:return new ft(C,"310","11");case 57:return new ft(C,"320","11");case 58:return new ft(C,"310","13");case 59:return new ft(C,"320","13");case 60:return new ft(C,"310","15");case 61:return new ft(C,"320","15");case 62:return new ft(C,"310","17");case 63:return new ft(C,"320","17")}}catch(e){throw console.log(e),new Vt("unknown decoder: "+C)}}class Vn{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 Vn?Vn.equalsOrNull(e.leftchar,n.leftchar)&&Vn.equalsOrNull(e.rightchar,n.rightchar)&&Vn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:Vn.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 Zt{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 Z){if(!this.pairs.length)throw new Z;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 Z}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 Z}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(Vn.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=ku.buildBitArray(e),s=ts(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 Ye(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 Z;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(w){p=null,this.verbose&&console.log(w)}return new Vn(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,w=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]=w,this.startEnd[1]=b;return}d&&oe.reverseCounters(s),w+=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 Z}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();D.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 oi(h,[a,l],a,l,n)}decodeDataCharacter(e,n,i,s){let a=this.getDataCharacterCounters();for(let it=0;it<a.length;it++)a[it]=0;if(s)oe.recordPatternInReverse(e,n.getStartEnd()[0],a);else{oe.recordPattern(e,n.getStartEnd()[1],a);for(let it=0,zt=a.length-1;it<zt;it++,zt--){let sn=a[it];a[it]=a[zt],a[zt]=sn}}let l=17,d=ze.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(d-h)/h>.3)throw new Z;let p=this.getOddCounts(),w=this.getEvenCounts(),b=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let it=0;it<a.length;it++){let zt=1*a[it]/d,sn=zt+.5;if(sn<1){if(zt<.3)throw new Z;sn=1}else if(sn>8){if(zt>8.7)throw new Z;sn=8}let vr=it/2;(it&1)==0?(p[vr]=sn,b[vr]=zt-sn):(w[vr]=sn,I[vr]=zt-sn)}this.adjustOddEvenCounts(l);let k=4*n.getValue()+(i?0:2)+(s?0:1)-1,L=0,F=0;for(let it=p.length-1;it>=0;it--){if(oe.isNotA1left(n,i,s)){let zt=oe.WEIGHTS[k][2*it];F+=p[it]*zt}L+=p[it]}let j=0;for(let it=w.length-1;it>=0;it--)if(oe.isNotA1left(n,i,s)){let zt=oe.WEIGHTS[k][2*it+1];j+=w[it]*zt}let Q=F+j;if((L&1)!=0||L>13||L<4)throw new Z;let ae=(13-L)/2,ce=oe.SYMBOL_WIDEST[ae],se=9-ce,Ze=Tn.getRSSvalue(p,ce,!0),ke=Tn.getRSSvalue(w,se,!1),Jt=oe.EVEN_TOTAL_SUBSET[ae],wn=oe.GSUM[ae],Qt=Ze*Jt+ke+wn;return new pr(Qt,Q)}static isNotA1left(e,n,i){return!(e.getValue()==0&&n&&i)}adjustOddEvenCounts(e){let n=ze.sum(new Int32Array(this.getOddCounts())),i=ze.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,w=(i&1)==0;if(h==1)if(p){if(w)throw new Z;a=!0}else{if(!w)throw new Z;d=!0}else if(h==-1)if(p){if(w)throw new Z;s=!0}else{if(!w)throw new Z;l=!0}else if(h==0){if(p){if(!w)throw new Z;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(w)throw new Z}else throw new Z;if(s){if(a)throw new Z;oe.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&oe.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new Z;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 Du extends pr{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 yt extends Zt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);yt.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);yt.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&&yt.checkChecksum(l,d))return yt.constructResult(l,d)}throw new Z}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 ie;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 w=a.charAt(p).charCodeAt(0)-48;l+=(p&1)===0?3*w:w}l=10-l%10,l===10&&(l=0),a.append(l.toString());let d=e.getFinderPattern().getResultPoints(),h=n.getFinderPattern().getResultPoints();return new Ye(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(H.NEED_RESULT_POINT_CALLBACK);if(d!=null){let w=(a[0]+a[1])/2;n&&(w=e.getSize()-1-w),d.foundPossibleResultPoint(new S(w,i))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Du(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let j=0;j<s.length;j++)s[j]=0;if(i)wt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{wt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let j=0,Q=s.length-1;j<Q;j++,Q--){let ae=s[j];s[j]=s[Q],s[Q]=ae}}let a=i?16:15,l=ze.sum(new Int32Array(s))/a,d=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),w=this.getEvenRoundingErrors();for(let j=0;j<s.length;j++){let Q=s[j]/l,ae=Math.floor(Q+.5);ae<1?ae=1:ae>8&&(ae=8);let ce=Math.floor(j/2);(j&1)===0?(d[ce]=ae,p[ce]=Q-ae):(h[ce]=ae,w[ce]=Q-ae)}this.adjustOddEvenCounts(i,a);let b=0,I=0;for(let j=d.length-1;j>=0;j--)I*=9,I+=d[j],b+=d[j];let k=0,L=0;for(let j=h.length-1;j>=0;j--)k*=9,k+=h[j],L+=h[j];let F=I+3*k;if(i){if((b&1)!==0||b>12||b<4)throw new Z;let j=(12-b)/2,Q=yt.OUTSIDE_ODD_WIDEST[j],ae=9-Q,ce=Tn.getRSSvalue(d,Q,!1),se=Tn.getRSSvalue(h,ae,!0),Ze=yt.OUTSIDE_EVEN_TOTAL_SUBSET[j],ke=yt.OUTSIDE_GSUM[j];return new pr(ce*Ze+se+ke,F)}else{if((L&1)!==0||L>10||L<4)throw new Z;let j=(10-L)/2,Q=yt.INSIDE_ODD_WIDEST[j],ae=9-Q,ce=Tn.getRSSvalue(d,Q,!0),se=Tn.getRSSvalue(h,ae,!1),Ze=yt.INSIDE_ODD_TOTAL_SUBSET[j],ke=yt.INSIDE_GSUM[j];return new pr(se*Ze+ce+ke,F)}}findFinderPattern(e,n){let i=this.getDecodeFinderCounters();i[0]=0,i[1]=0,i[2]=0,i[3]=0;let s=e.getSize(),a=!1,l=0;for(;l<s&&(a=!e.get(l),n!==a);)l++;let d=0,h=l;for(let p=l;p<s;p++)if(e.get(p)!==a)i[d]++;else{if(d===3){if(Zt.isFinderPattern(i))return[h,p];h+=i[0]+i[1],i[0]=i[2],i[1]=i[3],i[2]=0,i[3]=0,d--}else d++;i[d]=1,a=!a}throw new Z}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);D.arraycopy(h,0,p,1,h.length-1),p[0]=d;const w=this.parseFinderValue(p,yt.FINDER_PATTERNS);let b=l,I=s[1];return i&&(b=e.getSize()-1-b,I=e.getSize()-1-I),new oi(w,[l,s[1]],b,I,n)}adjustOddEvenCounts(e,n){let i=ze.sum(new Int32Array(this.getOddCounts())),s=ze.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,w=(i&1)===(e?1:0),b=(s&1)===1;if(p===1)if(w){if(b)throw new Z;l=!0}else{if(!b)throw new Z;h=!0}else if(p===-1)if(w){if(b)throw new Z;a=!0}else{if(!b)throw new Z;d=!0}else if(p===0){if(w){if(!b)throw new Z;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(b)throw new Z}else throw new Z;if(a){if(l)throw new Z;Zt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Zt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new Z;Zt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&Zt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}yt.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],yt.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],yt.OUTSIDE_GSUM=[0,161,961,2015,2715],yt.INSIDE_GSUM=[0,336,1036,1516],yt.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],yt.INSIDE_ODD_WIDEST=[2,4,6,8],yt.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 xr extends wt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(H.POSSIBLE_FORMATS):null,s=e&&e.get(H.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(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 bt(s)),i.includes(te.CODE_128)&&this.readers.push(new pe),i.includes(te.ITF)&&this.readers.push(new et),i.includes(te.RSS_14)&&this.readers.push(new yt),i.includes(te.RSS_EXPANDED)&&this.readers.push(new oe(this.verbose))):(this.readers.push(new Ui(e)),this.readers.push(new bt),this.readers.push(new Ui(e)),this.readers.push(new pe),this.readers.push(new et),this.readers.push(new yt),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 Z}reset(){this.readers.forEach(e=>e.reset())}}class Pu extends At{constructor(e=500,n){super(new xr(n),e,n)}}class Ke{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class Xe{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class $e{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 w of p)d+=w.getCount()*(w.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 z;for(let i of $e.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new z}toString(){return""+this.versionNumber}static buildVersions(){return[new $e(1,10,10,8,8,new Ke(5,new Xe(1,3))),new $e(2,12,12,10,10,new Ke(7,new Xe(1,5))),new $e(3,14,14,12,12,new Ke(10,new Xe(1,8))),new $e(4,16,16,14,14,new Ke(12,new Xe(1,12))),new $e(5,18,18,16,16,new Ke(14,new Xe(1,18))),new $e(6,20,20,18,18,new Ke(18,new Xe(1,22))),new $e(7,22,22,20,20,new Ke(20,new Xe(1,30))),new $e(8,24,24,22,22,new Ke(24,new Xe(1,36))),new $e(9,26,26,24,24,new Ke(28,new Xe(1,44))),new $e(10,32,32,14,14,new Ke(36,new Xe(1,62))),new $e(11,36,36,16,16,new Ke(42,new Xe(1,86))),new $e(12,40,40,18,18,new Ke(48,new Xe(1,114))),new $e(13,44,44,20,20,new Ke(56,new Xe(1,144))),new $e(14,48,48,22,22,new Ke(68,new Xe(1,174))),new $e(15,52,52,24,24,new Ke(42,new Xe(2,102))),new $e(16,64,64,14,14,new Ke(56,new Xe(2,140))),new $e(17,72,72,16,16,new Ke(36,new Xe(4,92))),new $e(18,80,80,18,18,new Ke(48,new Xe(4,114))),new $e(19,88,88,20,20,new Ke(56,new Xe(4,144))),new $e(20,96,96,22,22,new Ke(68,new Xe(4,174))),new $e(21,104,104,24,24,new Ke(56,new Xe(6,136))),new $e(22,120,120,18,18,new Ke(68,new Xe(6,175))),new $e(23,132,132,20,20,new Ke(62,new Xe(8,163))),new $e(24,144,144,22,22,new Ke(62,new Xe(8,156),new Xe(2,155))),new $e(25,8,18,6,16,new Ke(7,new Xe(1,5))),new $e(26,8,32,6,14,new Ke(11,new Xe(1,10))),new $e(27,12,26,10,24,new Ke(14,new Xe(1,16))),new $e(28,12,36,10,16,new Ke(18,new Xe(1,22))),new $e(29,16,36,14,16,new Ke(24,new Xe(1,32))),new $e(30,16,48,14,22,new Ke(28,new Xe(1,49)))]}}$e.VERSIONS=$e.buildVersions();class $i{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new z;this.version=$i.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new re(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return $e.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,w=!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&&!w)e[n++]=this.readCorner4(a,l)&255,i-=2,s+=2,w=!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 z;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,w=new re(p,h);for(let b=0;b<l;++b){const I=b*s;for(let k=0;k<d;++k){const L=k*a;for(let F=0;F<s;++F){const j=b*(s+2)+1+F,Q=I+F;for(let ae=0;ae<a;++ae){const ce=k*(a+2)+1+ae;if(e.get(ce,j)){const se=L+ae;w.set(se,Q)}}}}}return w}}class Wi{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 F of a)s+=F.getCount();const l=new Array(s);let d=0;for(let F of a)for(let j=0;j<F.getCount();j++){const Q=F.getDataCodewords(),ae=i.getECCodewords()+Q;l[d++]=new Wi(Q,new Uint8Array(ae))}const p=l[0].codewords.length-i.getECCodewords(),w=p-1;let b=0;for(let F=0;F<w;F++)for(let j=0;j<d;j++)l[j].codewords[F]=e[b++];const I=n.getVersionNumber()===24,k=I?8:d;for(let F=0;F<k;F++)l[F].codewords[p-1]=e[b++];const L=l[0].codewords.length;for(let F=p;F<L;F++)for(let j=0;j<d;j++){const Q=I?(j+8)%d:j,ae=I&&Q>7?F-1:F;l[Q].codewords[ae]=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 Tt;(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"})(Tt||(Tt={}));class Zn{static decode(e){const n=new Hi(e),i=new ie,s=new ie,a=new Array;let l=Tt.ASCII_ENCODE;do if(l===Tt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Tt.C40_ENCODE:this.decodeC40Segment(n,i);break;case Tt.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Tt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Tt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Tt.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new z}l=Tt.ASCII_ENCODE}while(l!==Tt.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 z;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Tt.ASCII_ENCODE;if(a===129)return Tt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Tt.C40_ENCODE;case 231:return Tt.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 Tt.ANSIX12_ENCODE;case 239:return Tt.TEXT_ENCODE;case 240:return Tt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new z;break}}while(e.available()>0);return Tt.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 z;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 z}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 z}}}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 z;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 z}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 z;break;default:throw new z}}}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 z;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 z;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new z;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(me.decode(d,le.ISO88591))}catch(h){throw new Vt("Platform does not support required encoding: "+h.message)}}static unrandomize255State(e,n){const i=149*n%255+1,s=e-i;return s>=0?s:s+256}}Zn.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"],Zn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],Zn.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"],Zn.TEXT_SHIFT2_SET_CHARS=Zn.C40_SHIFT2_SET_CHARS,Zn.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 Bu{constructor(){this.rsDecoder=new An(Ue.DATA_MATRIX_FIELD_256)}decode(e){const n=new $i(e),i=n.getVersion(),s=n.readCodewords(),a=Wi.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 w=a[p],b=w.getCodewords(),I=w.getNumDataCodewords();this.correctErrors(b,I);for(let k=0;k<I;k++)d[k*h+p]=b[k]}return Zn.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Et{constructor(e){this.image=e,this.rectangleDetector=new pt(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 Z;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=Et.sampleGrid(this.image,i,s,a,l,d,h);return new ue(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 S(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 S(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),w=l,b=[a,n,i,s];return w>d&&(w=d,b[0]=n,b[1]=i,b[2]=s,b[3]=a),w>h&&(w=h,b[0]=i,b[1]=s,b[2]=a,b[3]=n),w>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=Et.shiftPoint(i,s,(l+1)*4),h=Et.shiftPoint(s,i,(l+1)*4),p=this.transitionsBetween(d,n),w=this.transitionsBetween(h,a);return p<w?(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=Et.shiftPoint(n,i,(d+1)*4),p=Et.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(p,a);let w=new S(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),b=new S(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(w))return this.isValid(b)?b:null;if(!this.isValid(b))return w;let I=this.transitionsBetween(h,w)+this.transitionsBetween(p,w),k=this.transitionsBetween(h,b)+this.transitionsBetween(p,b);return I>k?w: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=Et.shiftPoint(n,i,d*4),p=Et.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 w=(n.getX()+i.getX()+s.getX()+a.getX())/4,b=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Et.moveAway(n,w,b),i=Et.moveAway(i,w,b),s=Et.moveAway(s,w,b),a=Et.moveAway(a,w,b);let I,k;return h=Et.shiftPoint(n,i,d*4),h=Et.shiftPoint(h,a,l*4),I=Et.shiftPoint(i,n,d*4),I=Et.shiftPoint(I,s,l*4),p=Et.shiftPoint(s,a,d*4),p=Et.shiftPoint(p,i,l*4),k=Et.shiftPoint(a,s,d*4),k=Et.shiftPoint(k,n,l*4),[h,I,p,k]}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 on.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 F=i;i=s,s=F,F=a,a=l,l=F}let h=Math.abs(a-i),p=Math.abs(l-s),w=-h/2,b=s<l?1:-1,I=i<a?1:-1,k=0,L=this.image.get(d?s:i,d?i:s);for(let F=i,j=s;F!==a;F+=I){let Q=this.image.get(d?j:F,d?F:j);if(Q!==L&&(k++,L=Q),w+=p,w>0){if(j===l)break;j+=b,w-=h}}return k}}class $n{constructor(){this.decoder=new Bu}decode(e,n=null){let i,s;if(n!=null&&n.has(H.PURE_BARCODE)){const p=$n.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(p),s=$n.NO_POINTS}else{const p=new Et(e.getBlackMatrix()).detect();i=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=i.getRawBytes(),l=new Ye(i.getText(),a,8*a.length,s,te.DATA_MATRIX,D.currentTimeMillis()),d=i.getByteSegments();d!=null&&l.putMetadata(Ne.BYTE_SEGMENTS,d);const h=i.getECLevel();return h!=null&&l.putMetadata(Ne.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n==null||i==null)throw new Z;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,w=(l-a+1)/s;if(p<=0||w<=0)throw new Z;const b=s/2;a+=b,d+=b;const I=new re(p,w);for(let k=0;k<w;k++){const L=a+k*s;for(let F=0;F<p;F++)e.get(d+F*s,L)&&I.set(F,k)}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 Z;const l=s-e[0];if(l===0)throw new Z;return l}}$n.NO_POINTS=[];class Lu extends At{constructor(e=500){super(new $n,e)}}var wr;(function(C){C[C.L=0]="L",C[C.M=1]="M",C[C.Q=2]="Q",C[C.H=3]="H"})(wr||(wr={}));class st{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,st.FOR_BITS.set(i,this),st.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return st.L;case"M":return st.M;case"Q":return st.Q;case"H":return st.H;default:throw new E(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof st))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=st.FOR_BITS.size)throw new A;return st.FOR_BITS.get(e)}}st.FOR_BITS=new Map,st.FOR_VALUE=new Map,st.L=new st(wr.L,"L",1),st.M=new st(wr.M,"M",0),st.Q=new st(wr.Q,"Q",3),st.H=new st(wr.H,"H",2);class $t{constructor(e){this.errorCorrectionLevel=st.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return U.bitCount(e^n)}static decodeFormatInformation(e,n){const i=$t.doDecodeFormatInformation(e,n);return i!==null?i:$t.doDecodeFormatInformation(e^$t.FORMAT_INFO_MASK_QR,n^$t.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=Number.MAX_SAFE_INTEGER,s=0;for(const a of $t.FORMAT_INFO_DECODE_LOOKUP){const l=a[0];if(l===e||l===n)return new $t(a[1]);let d=$t.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=$t.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=3?new $t(s):null}getErrorCorrectionLevel(){return this.errorCorrectionLevel}getDataMask(){return this.dataMask}hashCode(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask}equals(e){if(!(e instanceof $t))return!1;const n=e;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask}}$t.FORMAT_INFO_MASK_QR=21522,$t.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 G{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const i of n)e+=i.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class N{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class ve{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 z;try{return this.getVersionForNumber((e-17)/4)}catch{throw new z}}static getVersionForNumber(e){if(e<1||e>40)throw new A;return ve.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<ve.VERSION_DECODE_INFO.length;s++){const a=ve.VERSION_DECODE_INFO[s];if(a===e)return ve.getVersionForNumber(s+7);const l=$t.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?ve.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new re(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}}ve.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]),ve.VERSIONS=[new ve(1,new Int32Array(0),new G(7,new N(1,19)),new G(10,new N(1,16)),new G(13,new N(1,13)),new G(17,new N(1,9))),new ve(2,Int32Array.from([6,18]),new G(10,new N(1,34)),new G(16,new N(1,28)),new G(22,new N(1,22)),new G(28,new N(1,16))),new ve(3,Int32Array.from([6,22]),new G(15,new N(1,55)),new G(26,new N(1,44)),new G(18,new N(2,17)),new G(22,new N(2,13))),new ve(4,Int32Array.from([6,26]),new G(20,new N(1,80)),new G(18,new N(2,32)),new G(26,new N(2,24)),new G(16,new N(4,9))),new ve(5,Int32Array.from([6,30]),new G(26,new N(1,108)),new G(24,new N(2,43)),new G(18,new N(2,15),new N(2,16)),new G(22,new N(2,11),new N(2,12))),new ve(6,Int32Array.from([6,34]),new G(18,new N(2,68)),new G(16,new N(4,27)),new G(24,new N(4,19)),new G(28,new N(4,15))),new ve(7,Int32Array.from([6,22,38]),new G(20,new N(2,78)),new G(18,new N(4,31)),new G(18,new N(2,14),new N(4,15)),new G(26,new N(4,13),new N(1,14))),new ve(8,Int32Array.from([6,24,42]),new G(24,new N(2,97)),new G(22,new N(2,38),new N(2,39)),new G(22,new N(4,18),new N(2,19)),new G(26,new N(4,14),new N(2,15))),new ve(9,Int32Array.from([6,26,46]),new G(30,new N(2,116)),new G(22,new N(3,36),new N(2,37)),new G(20,new N(4,16),new N(4,17)),new G(24,new N(4,12),new N(4,13))),new ve(10,Int32Array.from([6,28,50]),new G(18,new N(2,68),new N(2,69)),new G(26,new N(4,43),new N(1,44)),new G(24,new N(6,19),new N(2,20)),new G(28,new N(6,15),new N(2,16))),new ve(11,Int32Array.from([6,30,54]),new G(20,new N(4,81)),new G(30,new N(1,50),new N(4,51)),new G(28,new N(4,22),new N(4,23)),new G(24,new N(3,12),new N(8,13))),new ve(12,Int32Array.from([6,32,58]),new G(24,new N(2,92),new N(2,93)),new G(22,new N(6,36),new N(2,37)),new G(26,new N(4,20),new N(6,21)),new G(28,new N(7,14),new N(4,15))),new ve(13,Int32Array.from([6,34,62]),new G(26,new N(4,107)),new G(22,new N(8,37),new N(1,38)),new G(24,new N(8,20),new N(4,21)),new G(22,new N(12,11),new N(4,12))),new ve(14,Int32Array.from([6,26,46,66]),new G(30,new N(3,115),new N(1,116)),new G(24,new N(4,40),new N(5,41)),new G(20,new N(11,16),new N(5,17)),new G(24,new N(11,12),new N(5,13))),new ve(15,Int32Array.from([6,26,48,70]),new G(22,new N(5,87),new N(1,88)),new G(24,new N(5,41),new N(5,42)),new G(30,new N(5,24),new N(7,25)),new G(24,new N(11,12),new N(7,13))),new ve(16,Int32Array.from([6,26,50,74]),new G(24,new N(5,98),new N(1,99)),new G(28,new N(7,45),new N(3,46)),new G(24,new N(15,19),new N(2,20)),new G(30,new N(3,15),new N(13,16))),new ve(17,Int32Array.from([6,30,54,78]),new G(28,new N(1,107),new N(5,108)),new G(28,new N(10,46),new N(1,47)),new G(28,new N(1,22),new N(15,23)),new G(28,new N(2,14),new N(17,15))),new ve(18,Int32Array.from([6,30,56,82]),new G(30,new N(5,120),new N(1,121)),new G(26,new N(9,43),new N(4,44)),new G(28,new N(17,22),new N(1,23)),new G(28,new N(2,14),new N(19,15))),new ve(19,Int32Array.from([6,30,58,86]),new G(28,new N(3,113),new N(4,114)),new G(26,new N(3,44),new N(11,45)),new G(26,new N(17,21),new N(4,22)),new G(26,new N(9,13),new N(16,14))),new ve(20,Int32Array.from([6,34,62,90]),new G(28,new N(3,107),new N(5,108)),new G(26,new N(3,41),new N(13,42)),new G(30,new N(15,24),new N(5,25)),new G(28,new N(15,15),new N(10,16))),new ve(21,Int32Array.from([6,28,50,72,94]),new G(28,new N(4,116),new N(4,117)),new G(26,new N(17,42)),new G(28,new N(17,22),new N(6,23)),new G(30,new N(19,16),new N(6,17))),new ve(22,Int32Array.from([6,26,50,74,98]),new G(28,new N(2,111),new N(7,112)),new G(28,new N(17,46)),new G(30,new N(7,24),new N(16,25)),new G(24,new N(34,13))),new ve(23,Int32Array.from([6,30,54,78,102]),new G(30,new N(4,121),new N(5,122)),new G(28,new N(4,47),new N(14,48)),new G(30,new N(11,24),new N(14,25)),new G(30,new N(16,15),new N(14,16))),new ve(24,Int32Array.from([6,28,54,80,106]),new G(30,new N(6,117),new N(4,118)),new G(28,new N(6,45),new N(14,46)),new G(30,new N(11,24),new N(16,25)),new G(30,new N(30,16),new N(2,17))),new ve(25,Int32Array.from([6,32,58,84,110]),new G(26,new N(8,106),new N(4,107)),new G(28,new N(8,47),new N(13,48)),new G(30,new N(7,24),new N(22,25)),new G(30,new N(22,15),new N(13,16))),new ve(26,Int32Array.from([6,30,58,86,114]),new G(28,new N(10,114),new N(2,115)),new G(28,new N(19,46),new N(4,47)),new G(28,new N(28,22),new N(6,23)),new G(30,new N(33,16),new N(4,17))),new ve(27,Int32Array.from([6,34,62,90,118]),new G(30,new N(8,122),new N(4,123)),new G(28,new N(22,45),new N(3,46)),new G(30,new N(8,23),new N(26,24)),new G(30,new N(12,15),new N(28,16))),new ve(28,Int32Array.from([6,26,50,74,98,122]),new G(30,new N(3,117),new N(10,118)),new G(28,new N(3,45),new N(23,46)),new G(30,new N(4,24),new N(31,25)),new G(30,new N(11,15),new N(31,16))),new ve(29,Int32Array.from([6,30,54,78,102,126]),new G(30,new N(7,116),new N(7,117)),new G(28,new N(21,45),new N(7,46)),new G(30,new N(1,23),new N(37,24)),new G(30,new N(19,15),new N(26,16))),new ve(30,Int32Array.from([6,26,52,78,104,130]),new G(30,new N(5,115),new N(10,116)),new G(28,new N(19,47),new N(10,48)),new G(30,new N(15,24),new N(25,25)),new G(30,new N(23,15),new N(25,16))),new ve(31,Int32Array.from([6,30,56,82,108,134]),new G(30,new N(13,115),new N(3,116)),new G(28,new N(2,46),new N(29,47)),new G(30,new N(42,24),new N(1,25)),new G(30,new N(23,15),new N(28,16))),new ve(32,Int32Array.from([6,34,60,86,112,138]),new G(30,new N(17,115)),new G(28,new N(10,46),new N(23,47)),new G(30,new N(10,24),new N(35,25)),new G(30,new N(19,15),new N(35,16))),new ve(33,Int32Array.from([6,30,58,86,114,142]),new G(30,new N(17,115),new N(1,116)),new G(28,new N(14,46),new N(21,47)),new G(30,new N(29,24),new N(19,25)),new G(30,new N(11,15),new N(46,16))),new ve(34,Int32Array.from([6,34,62,90,118,146]),new G(30,new N(13,115),new N(6,116)),new G(28,new N(14,46),new N(23,47)),new G(30,new N(44,24),new N(7,25)),new G(30,new N(59,16),new N(1,17))),new ve(35,Int32Array.from([6,30,54,78,102,126,150]),new G(30,new N(12,121),new N(7,122)),new G(28,new N(12,47),new N(26,48)),new G(30,new N(39,24),new N(14,25)),new G(30,new N(22,15),new N(41,16))),new ve(36,Int32Array.from([6,24,50,76,102,128,154]),new G(30,new N(6,121),new N(14,122)),new G(28,new N(6,47),new N(34,48)),new G(30,new N(46,24),new N(10,25)),new G(30,new N(2,15),new N(64,16))),new ve(37,Int32Array.from([6,28,54,80,106,132,158]),new G(30,new N(17,122),new N(4,123)),new G(28,new N(29,46),new N(14,47)),new G(30,new N(49,24),new N(10,25)),new G(30,new N(24,15),new N(46,16))),new ve(38,Int32Array.from([6,32,58,84,110,136,162]),new G(30,new N(4,122),new N(18,123)),new G(28,new N(13,46),new N(32,47)),new G(30,new N(48,24),new N(14,25)),new G(30,new N(42,15),new N(32,16))),new ve(39,Int32Array.from([6,26,54,82,110,138,166]),new G(30,new N(20,117),new N(4,118)),new G(28,new N(40,47),new N(7,48)),new G(30,new N(43,24),new N(22,25)),new G(30,new N(10,15),new N(67,16))),new ve(40,Int32Array.from([6,30,58,86,114,142,170]),new G(30,new N(19,118),new N(6,119)),new G(28,new N(18,47),new N(31,48)),new G(30,new N(34,24),new N(34,25)),new G(30,new N(20,15),new N(61,16)))];var Mt;(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"})(Mt||(Mt={}));class hn{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)}}hn.values=new Map([[Mt.DATA_MASK_000,new hn(Mt.DATA_MASK_000,(C,e)=>(C+e&1)===0)],[Mt.DATA_MASK_001,new hn(Mt.DATA_MASK_001,(C,e)=>(C&1)===0)],[Mt.DATA_MASK_010,new hn(Mt.DATA_MASK_010,(C,e)=>e%3===0)],[Mt.DATA_MASK_011,new hn(Mt.DATA_MASK_011,(C,e)=>(C+e)%3===0)],[Mt.DATA_MASK_100,new hn(Mt.DATA_MASK_100,(C,e)=>(Math.floor(C/2)+Math.floor(e/3)&1)===0)],[Mt.DATA_MASK_101,new hn(Mt.DATA_MASK_101,(C,e)=>C*e%6===0)],[Mt.DATA_MASK_110,new hn(Mt.DATA_MASK_110,(C,e)=>C*e%6<3)],[Mt.DATA_MASK_111,new hn(Mt.DATA_MASK_111,(C,e)=>(C+e+C*e%3&1)===0)]]);class Fu{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new z;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=$t.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new z}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 ve.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=ve.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=ve.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new z}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=hn.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,w=0;for(let b=s-1;b>0;b-=2){b===6&&b--;for(let I=0;I<s;I++){const k=l?s-1-I:I;for(let L=0;L<2;L++)a.get(b-L,k)||(w++,p<<=1,this.bitMatrix.get(b-L,k)&&(p|=1),w===8&&(d[h++]=p,w=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new z;return d}remask(){if(this.parsedFormatInfo===null)return;const e=hn.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 ji{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 L of l)a+=L.getCount();const d=new Array(a);let h=0;for(const L of l)for(let F=0;F<L.getCount();F++){const j=L.getDataCodewords(),Q=s.getECCodewordsPerBlock()+j;d[h++]=new ji(j,new Uint8Array(Q))}const p=d[0].codewords.length;let w=d.length-1;for(;w>=0&&d[w].codewords.length!==p;)w--;w++;const b=p-s.getECCodewordsPerBlock();let I=0;for(let L=0;L<b;L++)for(let F=0;F<h;F++)d[F].codewords[L]=e[I++];for(let L=w;L<h;L++)d[L].codewords[b]=e[I++];const k=d[0].codewords.length;for(let L=b;L<k;L++)for(let F=0;F<h;F++){const j=F<w?L:L+1;d[F].codewords[j]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var pn;(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"})(pn||(pn={}));class Ee{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,Ee.FOR_BITS.set(s,this),Ee.FOR_VALUE.set(e,this)}static forBits(e){const n=Ee.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 Ee))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Ee.FOR_BITS=new Map,Ee.FOR_VALUE=new Map,Ee.TERMINATOR=new Ee(pn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Ee.NUMERIC=new Ee(pn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Ee.ALPHANUMERIC=new Ee(pn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Ee.STRUCTURED_APPEND=new Ee(pn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Ee.BYTE=new Ee(pn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Ee.ECI=new Ee(pn.ECI,"ECI",Int32Array.from([0,0,0]),7),Ee.KANJI=new Ee(pn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Ee.FNC1_FIRST_POSITION=new Ee(pn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Ee.FNC1_SECOND_POSITION=new Ee(pn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Ee.HANZI=new Ee(pn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class gt{static decode(e,n,i,s){const a=new Hi(e);let l=new ie;const d=new Array;let h=-1,p=-1;try{let w=null,b=!1,I;do{if(a.available()<4)I=Ee.TERMINATOR;else{const k=a.readBits(4);I=Ee.forBits(k)}switch(I){case Ee.TERMINATOR:break;case Ee.FNC1_FIRST_POSITION:case Ee.FNC1_SECOND_POSITION:b=!0;break;case Ee.STRUCTURED_APPEND:if(a.available()<16)throw new z;h=a.readBits(8),p=a.readBits(8);break;case Ee.ECI:const k=gt.parseECIValue(a);if(w=M.getCharacterSetECIByValue(k),w===null)throw new z;break;case Ee.HANZI:const L=a.readBits(4),F=a.readBits(I.getCharacterCountBits(n));L===gt.GB2312_SUBSET&>.decodeHanziSegment(a,l,F);break;default:const j=a.readBits(I.getCharacterCountBits(n));switch(I){case Ee.NUMERIC:gt.decodeNumericSegment(a,l,j);break;case Ee.ALPHANUMERIC:gt.decodeAlphanumericSegment(a,l,j,b);break;case Ee.BYTE:gt.decodeByteSegment(a,l,j,w,d,s);break;case Ee.KANJI:gt.decodeKanjiSegment(a,l,j);break;default:throw new z}break}}while(I!==Ee.TERMINATOR)}catch{throw new z}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 z;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(me.decode(s,le.GB2312))}catch(l){throw new z(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new z;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(me.decode(s,le.SHIFT_JIS))}catch(l){throw new z(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new z;const d=new Uint8Array(i);for(let p=0;p<i;p++)d[p]=e.readBits(8);let h;s===null?h=le.guessEncoding(d,l):h=s.getName();try{n.append(me.decode(d,h))}catch(p){throw new z(p)}a.push(d)}static toAlphaNumericChar(e){if(e>=gt.ALPHANUMERIC_CHARS.length)throw new z;return gt.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new z;const l=e.readBits(11);n.append(gt.toAlphaNumericChar(Math.floor(l/45))),n.append(gt.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new z;n.append(gt.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 z;const s=e.readBits(10);if(s>=1e3)throw new z;n.append(gt.toAlphaNumericChar(Math.floor(s/100))),n.append(gt.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(gt.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new z;const s=e.readBits(7);if(s>=100)throw new z;n.append(gt.toAlphaNumericChar(Math.floor(s/10))),n.append(gt.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new z;const s=e.readBits(4);if(s>=10)throw new z;n.append(gt.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 z}}gt.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",gt.GB2312_SUBSET=1;class ns{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 Uu{constructor(){this.rsDecoder=new An(Ue.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(re.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new Fu(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 ns(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=ji.getDataBlocks(a,i,s);let d=0;for(const w of l)d+=w.getNumDataCodewords();const h=new Uint8Array(d);let p=0;for(const w of l){const b=w.getCodewords(),I=w.getNumDataCodewords();this.correctErrors(b,I);for(let k=0;k<I;k++)h[p++]=b[k]}return gt.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Gi extends S{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 li{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 w=e;for(;w<s&&!d.get(w,p);)w++;let b=0;for(;w<s;){if(d.get(w,p))if(b===1)l[1]++;else if(b===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,w);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]++;w++}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 Z}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)?li.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i){const s=e[0]+e[1]+e[2],a=li.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 S{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 zu{constructor(e){this.bottomLeft=e[0],this.topLeft=e[1],this.topRight=e[2]}getBottomLeft(){return this.bottomLeft}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}}class Dt{constructor(e,n){this.image=e,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}getImage(){return this.image}getPossibleCenters(){return this.possibleCenters}find(e){const n=e!=null&&e.get(H.TRY_HARDER)!==void 0,i=e!=null&&e.get(H.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Dt.MAX_MODULES));(d<Dt.MIN_SKIP||n)&&(d=Dt.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let 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 k=0;k<l;k++)if(s.get(k,b))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(Dt.foundPatternCross(p)){if(this.handlePossibleCenter(p,b,k,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const F=this.findRowSkip();F>p[2]&&(b+=F-p[2]-d,k=l-1)}else{p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;continue}I=0,p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0}else p[0]=p[2],p[1]=p[3],p[2]=p[4],p[3]=1,p[4]=0,I=3;else p[++I]++;else p[I]++;Dt.foundPatternCross(p)&&this.handlePossibleCenter(p,b,l,i)===!0&&(d=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const w=this.selectBestPatterns();return S.orderBestPatterns(w),new zu(w)}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 w=a[0]+a[1]+a[2]+a[3]+a[4];return Math.abs(w-s)<2*s&&Dt.foundPatternCross(a)}crossCheckVertical(e,n,i,s){const a=this.image,l=a.getHeight(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(n,h);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(n,h)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(n,h)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(n,h);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(n,h)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(n,h)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=2*s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}crossCheckHorizontal(e,n,i,s){const a=this.image,l=a.getWidth(),d=this.getCrossCheckStateCount();let h=e;for(;h>=0&&a.get(h,n);)d[2]++,h--;if(h<0)return NaN;for(;h>=0&&!a.get(h,n)&&d[1]<=i;)d[1]++,h--;if(h<0||d[1]>i)return NaN;for(;h>=0&&a.get(h,n)&&d[0]<=i;)d[0]++,h--;if(d[0]>i)return NaN;for(h=e+1;h<l&&a.get(h,n);)d[2]++,h++;if(h===l)return NaN;for(;h<l&&!a.get(h,n)&&d[3]<i;)d[3]++,h++;if(h===l||d[3]>=i)return NaN;for(;h<l&&a.get(h,n)&&d[4]<i;)d[4]++,h++;if(d[4]>=i)return NaN;const p=d[0]+d[1]+d[2]+d[3]+d[4];return 5*Math.abs(p-s)>=s?NaN:Dt.foundPatternCross(d)?Dt.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Dt.centerFromEnd(e,i),d=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(d)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(d),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(d),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const w=this.possibleCenters;for(let b=0,I=w.length;b<I;b++){const k=w[b];if(k.aboutEquals(h,d,l)){w[b]=k.combineEstimate(d,l,h),p=!0;break}}if(!p){const b=new Xi(l,d,h);w.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()>=Dt.CENTER_QUORUM)if(n==null)n=i;else return this.hasSkipped=!0,Math.floor((Math.abs(n.getX()-i.getX())-Math.abs(n.getY()-i.getY()))/2);return 0}haveMultiplyConfirmedCenters(){let e=0,n=0;const i=this.possibleCenters.length;for(const l of this.possibleCenters)l.getCount()>=Dt.CENTER_QUORUM&&(e++,n+=l.getEstimatedModuleSize());if(e<3)return!1;const s=n/i;let a=0;for(const l of this.possibleCenters)a+=Math.abs(l.getEstimatedModuleSize()-s);return a<=.05*n}selectBestPatterns(){const e=this.possibleCenters.length;if(e<3)throw new Z;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 w=Math.abs(p.getEstimatedModuleSize()-i),b=Math.abs(h.getEstimatedModuleSize()-i);return w<b?-1:w>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]]}}Dt.CENTER_QUORUM=2,Dt.MIN_SKIP=3,Dt.MAX_MODULES=57;class Sr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(H.NEED_RESULT_POINT_CALLBACK);const i=new Dt(this.image,this.resultPointCallback).find(e);return this.processFinderPatternInfo(i)}processFinderPatternInfo(e){const n=e.getTopLeft(),i=e.getTopRight(),s=e.getBottomLeft(),a=this.calculateModuleSize(n,i,s);if(a<1)throw new Z("No pattern found in proccess finder.");const l=Sr.computeDimension(n,i,s,a),d=ve.getProvisionalVersionForDimension(l),h=d.getDimensionForVersion()-7;let p=null;if(d.getAlignmentPatternCenters().length>0){const k=i.getX()-n.getX()+s.getX(),L=i.getY()-n.getY()+s.getY(),F=1-3/h,j=Math.floor(n.getX()+F*(k-n.getX())),Q=Math.floor(n.getY()+F*(L-n.getY()));for(let ae=4;ae<=16;ae<<=1)try{p=this.findAlignmentInRegion(a,j,Q,ae);break}catch(ce){if(!(ce instanceof Z))throw ce}}const w=Sr.createTransform(n,i,s,p,l),b=Sr.sampleGrid(this.image,w,l);let I;return p===null?I=[s,n,i]:I=[s,n,i,p],new ue(b,I)}static createTransform(e,n,i,s,a){const l=a-3.5;let d,h,p,w;return s!==null?(d=s.getX(),h=s.getY(),p=l-3,w=p):(d=n.getX()-e.getX()+i.getX(),h=n.getY()-e.getY()+i.getY(),p=l,w=l),rn.quadrilateralToQuadrilateral(3.5,3.5,l,3.5,p,w,3.5,l,e.getX(),e.getY(),n.getX(),n.getY(),d,h,i.getX(),i.getY())}static sampleGrid(e,n,i){return on.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=ze.round(S.distance(e,n)/s),l=ze.round(S.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 Z("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 k=e;e=n,n=k,k=i,i=s,s=k}const l=Math.abs(i-e),d=Math.abs(s-n);let h=-l/2;const p=e<i?1:-1,w=n<s?1:-1;let b=0;const I=i+p;for(let k=e,L=n;k!==I;k+=p){const F=a?L:k,j=a?k:L;if(b===1===this.image.get(F,j)){if(b===2)return ze.distance(k,L,e,n);b++}if(h+=d,h>0){if(L===s)break;L+=w,h-=l}}return b===2?ze.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 Z("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 Z("Alignment bottom exceeds estimated module size.");return new li(this.image,l,h,d-l,p-h,e,this.resultPointCallback).find()}}class Wn{constructor(){this.decoder=new Uu}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(H.PURE_BARCODE)!==void 0){const h=Wn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=Wn.NO_POINTS}else{const h=new Sr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof ns&&i.getOther().applyMirroredCorrection(s);const a=new Ye(i.getText(),i.getRawBytes(),void 0,s,te.QR_CODE,void 0),l=i.getByteSegments();l!==null&&a.putMetadata(Ne.BYTE_SEGMENTS,l);const d=i.getECLevel();return d!==null&&a.putMetadata(Ne.ERROR_CORRECTION_LEVEL,d),i.hasStructuredAppend()&&(a.putMetadata(Ne.STRUCTURED_APPEND_SEQUENCE,i.getStructuredAppendSequenceNumber()),a.putMetadata(Ne.STRUCTURED_APPEND_PARITY,i.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n===null||i===null)throw new Z;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 Z;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new Z;const p=Math.round((h-d+1)/s),w=Math.round((l-a+1)/s);if(p<=0||w<=0)throw new Z;if(w!==p)throw new Z;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 Z;d-=I}const k=a+Math.floor((w-1)*s)-l;if(k>0){if(k>b)throw new Z;a-=k}const L=new re(p,w);for(let F=0;F<w;F++){const j=a+Math.floor(F*s);for(let Q=0;Q<p;Q++)e.get(d+Math.floor(Q*s),j)&&L.set(Q,F)}return L}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 Z;return(a-e[0])/7}}Wn.NO_POINTS=new Array;class Se{PDF417Common(){}static getBitCountSum(e){return ze.sum(e)}static toIntArray(e){if(e==null||!e.length)return Se.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=$.binarySearch(Se.SYMBOL_TABLE,e&262143);return n<0?-1:(Se.CODEWORD_TABLE[n]-1)%Se.NUMBER_OF_CODEWORDS}}Se.NUMBER_OF_CODEWORDS=929,Se.MAX_CODEWORDS_IN_BARCODE=Se.NUMBER_OF_CODEWORDS-1,Se.MIN_ROWS_IN_BARCODE=3,Se.MAX_ROWS_IN_BARCODE=90,Se.MODULES_IN_CODEWORD=17,Se.MODULES_IN_STOP_PATTERN=18,Se.BARS_IN_MODULE=8,Se.EMPTY_INT_ARRAY=new Int32Array([]),Se.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]),Se.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 Vu{constructor(e,n){this.bits=e,this.points=n}getBits(){return this.bits}getPoints(){return this.points}}class Be{static detectMultiple(e,n,i){let s=e.getBlackMatrix(),a=Be.detect(i,s);return a.length||(s=s.clone(),s.rotate180(),a=Be.detect(i,s)),new Vu(s,a)}static detect(e,n){const i=new Array;let s=0,a=0,l=!1;for(;s<n.getHeight();){const d=Be.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+=Be.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 Be.copyToResult(l,Be.findRowsWithPattern(e,s,a,n,i,Be.START_PATTERN),Be.INDEXES_START_PATTERN),l[4]!=null&&(i=Math.trunc(l[4].getX()),n=Math.trunc(l[4].getY())),Be.copyToResult(l,Be.findRowsWithPattern(e,s,a,n,i,Be.STOP_PATTERN),Be.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+=Be.ROW_STEP){let b=Be.findGuardPattern(e,a,s,i,!1,l,p);if(b!=null){for(;s>0;){const I=Be.findGuardPattern(e,a,--s,i,!1,l,p);if(I!=null)b=I;else{s++;break}}d[0]=new S(b[0],s),d[1]=new S(b[1],s),h=!0;break}}let w=s+1;if(h){let b=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;w<n;w++){const k=Be.findGuardPattern(e,I[0],w,i,!1,l,p);if(k!=null&&Math.abs(I[0]-k[0])<Be.MAX_PATTERN_DRIFT&&Math.abs(I[1]-k[1])<Be.MAX_PATTERN_DRIFT)I=k,b=0;else{if(b>Be.SKIPPED_ROW_COUNT_MAX)break;b++}}w-=b+1,d[2]=new S(I[0],w),d[3]=new S(I[1],w)}return w-s<Be.BARCODE_MIN_HEIGHT&&$.fill(d,null),d}static findGuardPattern(e,n,i,s,a,l,d){$.fillWithin(d,0,d.length,0);let h=n,p=0;for(;e.get(h,i)&&h>0&&p++<Be.MAX_PIXEL_DRIFT;)h--;let w=h,b=0,I=l.length;for(let k=a;w<s;w++)if(e.get(w,i)!==k)d[b]++;else{if(b===I-1){if(Be.patternMatchVariance(d,l,Be.MAX_INDIVIDUAL_VARIANCE)<Be.MAX_AVG_VARIANCE)return new Int32Array([h,w]);h+=d[0]+d[1],D.arraycopy(d,2,d,0,b-1),d[b-1]=0,d[b]=0,b--}else b++;d[b]=1,k=!k}return b===I-1&&Be.patternMatchVariance(d,l,Be.MAX_INDIVIDUAL_VARIANCE)<Be.MAX_AVG_VARIANCE?new Int32Array([h,w-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 w=e[p],b=n[p]*d,I=w>b?w-b:b-w;if(I>i)return 1/0;h+=I}return h/a}}Be.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),Be.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),Be.MAX_AVG_VARIANCE=.42,Be.MAX_INDIVIDUAL_VARIANCE=.8,Be.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),Be.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),Be.MAX_PIXEL_DRIFT=3,Be.MAX_PATTERN_DRIFT=5,Be.SKIPPED_ROW_COUNT_MAX=25,Be.ROW_STEP=5,Be.BARCODE_MIN_HEIGHT=10;class Ft{constructor(e,n){if(n.length===0)throw new A;this.field=e;let i=n.length;if(i>1&&n[0]===0){let s=1;for(;s<i&&n[s]===0;)s++;s===i?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(i-s),D.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;D.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=this.field.add(n[l-a],i[l]);return new Ft(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof Ft?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new A("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new Ft(this.field,new Int32Array([0]));let n=this.coefficients,i=n.length,s=e.coefficients,a=s.length,l=new Int32Array(i+a-1);for(let d=0;d<i;d++){let h=n[d];for(let p=0;p<a;p++)l[d+p]=this.field.add(l[d+p],this.field.multiply(h,s[p]))}return new Ft(this.field,l)}negative(){let e=this.coefficients.length,n=new Int32Array(e);for(let i=0;i<e;i++)n[i]=this.field.subtract(0,this.coefficients[i]);return new Ft(this.field,n)}multiplyScalar(e){if(e===0)return new Ft(this.field,new Int32Array([0]));if(e===1)return this;let n=this.coefficients.length,i=new Int32Array(n);for(let s=0;s<n;s++)i[s]=this.field.multiply(this.coefficients[s],e);return new Ft(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new A;if(n===0)return new Ft(this.field,new Int32Array([0]));let i=this.coefficients.length,s=new Int32Array(i+e);for(let a=0;a<i;a++)s[a]=this.field.multiply(this.coefficients[a],n);return new Ft(this.field,s)}toString(){let e=new ie;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 Zu{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 nn;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 Zu{constructor(e,n){super(),this.modulus=e,this.expTable=new Int32Array(e),this.logTable=new Int32Array(e);let i=1;for(let s=0;s<e;s++)this.expTable[s]=i,i=i*n%e;for(let s=0;s<e-1;s++)this.logTable[this.expTable[s]]=s;this.zero=new Ft(this,new Int32Array([0])),this.one=new Ft(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new A;if(n===0)return this.zero;let i=new Int32Array(e+1);return i[0]=n,new Ft(this,i)}}qi.PDF417_GF=new qi(Se.NUMBER_OF_CODEWORDS,3);class rs{constructor(){this.field=qi.PDF417_GF}decode(e,n,i){let s=new Ft(this.field,e),a=new Int32Array(n),l=!1;for(let L=n;L>0;L--){let F=s.evaluateAt(this.field.exp(L));a[n-L]=F,F!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const L of i){let F=this.field.exp(e.length-1-L),j=new Ft(this.field,new Int32Array([this.field.subtract(0,F),1]));d=d.multiply(j)}let h=new Ft(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),w=p[0],b=p[1],I=this.findErrorLocations(w),k=this.findErrorMagnitudes(b,w,I);for(let L=0;L<I.length;L++){let F=e.length-1-this.field.log(I[L]);if(F<0)throw O.getChecksumInstance();e[F]=this.field.subtract(e[F],k[L])}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,k=l;if(s=a,l=d,s.isZero())throw O.getChecksumInstance();a=I;let L=this.field.getZero(),F=s.getCoefficient(s.getDegree()),j=this.field.inverse(F);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Q=a.getDegree()-s.getDegree(),ae=this.field.multiply(a.getCoefficient(a.getDegree()),j);L=L.add(this.field.buildMonomial(Q,ae)),a=a.subtract(s.multiplyByMonomial(Q,ae))}d=L.multiply(l).subtract(k).negative()}let h=d.getCoefficient(0);if(h===0)throw O.getChecksumInstance();let p=this.field.inverse(h),w=d.multiply(p),b=a.multiply(p);return[w,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 O.getChecksumInstance();return i}findErrorMagnitudes(e,n,i){let s=n.getDegree(),a=new Int32Array(s);for(let p=1;p<=s;p++)a[s-p]=this.field.multiply(p,n.getCoefficient(p));let l=new Ft(this.field,a),d=i.length,h=new Int32Array(d);for(let p=0;p<d;p++){let w=this.field.inverse(i[p]),b=this.field.subtract(0,e.evaluateAt(w)),I=this.field.inverse(l.evaluateAt(w));h[p]=this.field.multiply(b,I)}return h}}class nr{constructor(e,n,i,s,a){e instanceof nr?this.constructor_2(e):this.constructor_1(e,n,i,s,a)}constructor_1(e,n,i,s,a){const l=n==null||i==null,d=s==null||a==null;if(l&&d)throw new Z;l?(n=new S(0,s.getY()),i=new S(0,a.getY())):d&&(s=new S(e.getWidth()-1,n.getY()),a=new S(e.getWidth()-1,i.getY())),this.image=e,this.topLeft=n,this.bottomLeft=i,this.topRight=s,this.bottomRight=a,this.minX=Math.trunc(Math.min(n.getX(),i.getX())),this.maxX=Math.trunc(Math.max(s.getX(),a.getX())),this.minY=Math.trunc(Math.min(n.getY(),s.getY())),this.maxY=Math.trunc(Math.max(i.getY(),a.getY()))}constructor_2(e){this.image=e.image,this.topLeft=e.getTopLeft(),this.bottomLeft=e.getBottomLeft(),this.topRight=e.getTopRight(),this.bottomRight=e.getBottomRight(),this.minX=e.getMinX(),this.maxX=e.getMaxX(),this.minY=e.getMinY(),this.maxY=e.getMaxY()}static merge(e,n){return e==null?n:n==null?e:new nr(e.image,e.topLeft,e.bottomLeft,n.topRight,n.bottomRight)}addMissingRows(e,n,i){let s=this.topLeft,a=this.bottomLeft,l=this.topRight,d=this.bottomRight;if(e>0){let h=i?this.topLeft:this.topRight,p=Math.trunc(h.getY()-e);p<0&&(p=0);let w=new S(h.getX(),p);i?s=w:l=w}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 w=new S(h.getX(),p);i?a=w:d=w}return new nr(this.image,s,a,l,d)}getMinX(){return this.minX}getMaxX(){return this.maxX}getMinY(){return this.minY}getMaxY(){return this.maxY}getTopLeft(){return this.topLeft}getTopRight(){return this.topRight}getBottomLeft(){return this.bottomLeft}getBottomRight(){return this.bottomRight}}class $u{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 Tr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,p,w,b){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=w?parseInt(w.substr(1)):void 0,k;switch(b){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Tr.form(e,n)}toString(){return this.buffer}}class Nr{constructor(e){this.boundingBox=new nr(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let i=1;i<Nr.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 Tr;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()}}Nr.MAX_NEARBY_DISTANCE=5;class Or{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 Se.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class is extends Nr{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,w=0;for(let b=l;b<d;b++){if(n[b]==null)continue;let I=n[b],k=I.getRowNumber()-h;if(k===0)w++;else if(k===1)p=Math.max(p,w),w=1,h=I.getRowNumber();else if(k<0||I.getRowNumber()>=e.getRowCount()||k>b)n[b]=null;else{let L;p>2?L=(p-2)*k:L=k;let F=L>=b;for(let j=1;j<=L&&!F;j++)F=n[b-j]!=null;F?n[b]=null:(h=I.getRowNumber(),w=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 w=d[p];w.setRowNumberAsRowIndicatorColumn();let b=w.getRowNumber()-h;b===0||(b===1?h=w.getRowNumber():w.getRowNumber()>=e.getRowCount()?d[p]=null:h=w.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Or,i=new Or,s=new Or,a=new Or;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]<Se.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>Se.MAX_ROWS_IN_BARCODE)return null;let l=new $u(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+`
|
|
62
|
-
`+super.toString()}}class kr{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=Se.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=kr.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=kr.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(kr.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 Tr;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 Rr{constructor(e,n,i,s){this.rowNumber=Rr.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!==Rr.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}}Rr.BARCODE_ROW_UNKNOWN=-1;class Kt{static initialize(){for(let e=0;e<Se.SYMBOL_TABLE.length;e++){let n=Se.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<Se.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,Kt.RATIOS_TABLE[e]||(Kt.RATIOS_TABLE[e]=new Array(Se.BARS_IN_MODULE)),Kt.RATIOS_TABLE[e][Se.BARS_IN_MODULE-s-1]=Math.fround(a/Se.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=Kt.getDecodedCodewordValue(Kt.sampleBitCounts(e));return n!==-1?n:Kt.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=ze.sum(e),i=new Int32Array(Se.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<Se.MODULES_IN_CODEWORD;l++){let d=n/(2*Se.MODULES_IN_CODEWORD)+l*n/Se.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=Kt.getBitValue(e);return Se.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=ze.sum(e),i=new Array(Se.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=In.MAX_VALUE,a=-1;this.bSymbolTableReady||Kt.initialize();for(let l=0;l<Kt.RATIOS_TABLE.length;l++){let d=0,h=Kt.RATIOS_TABLE[l];for(let p=0;p<Se.BARS_IN_MODULE;p++){let w=Math.fround(h[p]-i[p]);if(d+=Math.fround(w*w),d>=s)break}d<s&&(s=d,a=Se.SYMBOL_TABLE[l])}return a}}Kt.bSymbolTableReady=!1,Kt.RATIOS_TABLE=new Array(Se.SYMBOL_TABLE.length).map(C=>new Array(Se.BARS_IN_MODULE));class os{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 ss{static parseLong(e,n=void 0){return parseInt(e,n)}}class as extends x{}as.kind="NullPointerException";class Wu{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new as;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new P;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class Hu extends x{}class ju extends Wu{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 Hu;i=U.MAX_VALUE}this.buf=$.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 P;this.ensureCapacity(this.count+i),D.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 $.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 nt;(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"})(nt||(nt={}));function ls(){if(typeof window<"u")return window.BigInt||null;if(typeof bi<"u")return bi.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let ci;function Hn(C){if(typeof ci>"u"&&(ci=ls()),ci===null)throw new Error("BigInt is not supported!");return ci(C)}function Gu(){let C=[];C[0]=Hn(1);let e=Hn(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 ie(""),s=M.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new os;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:M.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 z;default:a--,a=J.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw z.getFormatInstance()}if(i.length()===0)throw z.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 z.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(U.parseInt(J.decodeBase900toBase10(s,J.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new ie;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 ie;n=J.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new ie;n=J.textCompaction(e,n+1,h),i.setSender(h.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new ie;n=J.textCompaction(e,n+1,p),i.setAddressee(p.toString());break;case J.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let w=new ie;n=J.numericCompaction(e,n+1,w),i.setSegmentCount(U.parseInt(w.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let b=new ie;n=J.numericCompaction(e,n+1,b),i.setTimestamp(ss.parseLong(b.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new ie;n=J.numericCompaction(e,n+1,I),i.setChecksum(U.parseInt(I.toString()));break;case J.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let k=new ie;n=J.numericCompaction(e,n+1,k),i.setFileSize(ss.parseLong(k.toString()));break;default:throw z.getFormatInstance()}break;case J.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw z.getFormatInstance()}if(l!==-1){let d=n-l;i.isLastSegment()&&d--,i.setOptionalData($.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=nt.ALPHA,l=nt.ALPHA,d=0;for(;d<i;){let h=e[d],p="";switch(a){case nt.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case J.LL:a=nt.LOWER;break;case J.ML:a=nt.MIXED;break;case J.PS:l=a,a=nt.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=nt.ALPHA;break}break;case nt.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case J.AS:l=a,a=nt.ALPHA_SHIFT;break;case J.ML:a=nt.MIXED;break;case J.PS:l=a,a=nt.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=nt.ALPHA;break}break;case nt.MIXED:if(h<J.PL)p=J.MIXED_CHARS[h];else switch(h){case J.PL:a=nt.PUNCT;break;case 26:p=" ";break;case J.LL:a=nt.LOWER;break;case J.AL:a=nt.ALPHA;break;case J.PS:l=a,a=nt.PUNCT_SHIFT;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=nt.ALPHA;break}break;case nt.PUNCT:if(h<J.PAL)p=J.PUNCT_CHARS[h];else switch(h){case J.PAL:a=nt.ALPHA;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=nt.ALPHA;break}break;case nt.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=nt.ALPHA;break}break;case nt.PUNCT_SHIFT:if(a=l,h<J.PAL)p=J.PUNCT_CHARS[h];else switch(h){case J.PAL:a=nt.ALPHA;break;case J.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case J.TEXT_COMPACTION_MODE_LATCH:a=nt.ALPHA;break}break}p!==""&&s.append(p),d++}}static byteCompaction(e,n,i,s,a){let l=new ju,d=0,h=0,p=!1;switch(e){case J.BYTE_COMPACTION_MODE_LATCH:let w=new Int32Array(6),b=n[s++];for(;s<n[0]&&!p;)switch(w[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(Hn(h)>>Hn(8*(5-I))));h=0,d=0}break}s===n[0]&&b<J.TEXT_COMPACTION_MODE_LATCH&&(w[d++]=b);for(let I=0;I<d;I++)l.write(w[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 k=0;k<6;++k)l.write(Number(Hn(h)>>Hn(8*(5-k))));h=0,d=0}}break}return a.append(me.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=Hn(0);for(let a=0;a<n;a++)i+=J.EXP900[n-a-1]*Hn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new z;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 ,:
|
|
63
|
-
-.$/"|*()?{}'`,J.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",J.EXP900=ls()?Gu():[],J.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Le{constructor(){}static decode(e,n,i,s,a,l,d){let h=new nr(e,n,i,s,a),p=null,w=null,b;for(let L=!0;;L=!1){if(n!=null&&(p=Le.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(w=Le.getRowIndicatorColumn(e,h,s,!1,l,d)),b=Le.merge(p,w),b==null)throw Z.getNotFoundInstance();let F=b.getBoundingBox();if(L&&F!=null&&(F.getMinY()<h.getMinY()||F.getMaxY()>h.getMaxY()))h=F;else break}b.setBoundingBox(h);let I=b.getBarcodeColumnCount()+1;b.setDetectionResultColumn(0,p),b.setDetectionResultColumn(I,w);let k=p!=null;for(let L=1;L<=I;L++){let F=k?L:I-L;if(b.getDetectionResultColumn(F)!==void 0)continue;let j;F===0||F===I?j=new is(h,F===0):j=new Nr(h),b.setDetectionResultColumn(F,j);let Q=-1,ae=Q;for(let ce=h.getMinY();ce<=h.getMaxY();ce++){if(Q=Le.getStartColumn(b,F,ce,k),Q<0||Q>h.getMaxX()){if(ae===-1)continue;Q=ae}let se=Le.detectCodeword(e,h.getMinX(),h.getMaxX(),k,Q,ce,l,d);se!=null&&(j.setCodeword(ce,se),ae=Q,l=Math.min(l,se.getWidth()),d=Math.max(d,se.getWidth()))}}return Le.createDecoderResult(b)}static merge(e,n){if(e==null&&n==null)return null;let i=Le.getBarcodeMetadata(e,n);if(i==null)return null;let s=nr.merge(Le.adjustBoundingBox(e),Le.adjustBoundingBox(n));return new kr(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=Le.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 is(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,w=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=Le.detectCodeword(e,0,e.getWidth(),s,w,b,a,l);I!=null&&(d.setCodeword(b,I),s?w=I.getStartX():w=I.getEndX())}}return d}static adjustCodewordCount(e,n){let i=n[0][1],s=i.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Le.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>Se.MAX_CODEWORDS_IN_BARCODE)throw Z.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=Le.createBarcodeMatrix(e);Le.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 w=n[h][p+1].getValue(),b=h*e.getBarcodeColumnCount()+p;w.length===0?i.push(b):w.length===1?s[b]=w[0]:(l.push(b),a.push(w))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return Le.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,Se.toIntArray(i),Se.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 Le.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof O))throw h}if(l.length===0)throw O.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw O.getChecksumInstance()}throw O.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Or;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(Le.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(Le.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;Le.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=Le.adjustCodewordStartColumn(e,n,i,s,a,l);let p=Le.getModuleBitCount(e,n,i,s,a,l);if(p==null)return null;let w,b=ze.sum(p);if(s)w=a+b;else{for(let L=0;L<p.length/2;L++){let F=p[L];p[L]=p[p.length-1-L],p[p.length-1-L]=F}w=a,a=w-b}if(!Le.checkCodewordSkew(b,d,h))return null;let I=Kt.getDecodedValue(p),k=Se.getCodeword(I);return k===-1?null:new Rr(a,w,Le.getCodewordBucketNumber(I),k)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),p=0,w=s?1:-1,b=s;for(;(s?d<i:d>=n)&&p<h.length;)e.get(d,l)===b?(h[p]++,d+=w):(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)>Le.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-Le.CODEWORD_SKEW_SIZE<=e&&e<=i+Le.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw z.getFormatInstance();let s=1<<n+1,a=Le.correctErrors(e,i,s);Le.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+Le.MAX_ERRORS||i<0||i>Le.MAX_EC_CODEWORDS)throw O.getChecksumInstance();return Le.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw z.getFormatInstance();let i=e[0];if(i>e.length)throw z.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw z.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 Le.getCodewordBucketNumber(Le.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Tr;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()}}Le.CODEWORD_SKEW_SIZE=2,Le.MAX_ERRORS=3,Le.MAX_EC_CODEWORDS=512,Le.errorCorrection=new rs;class Ut{decode(e,n=null){let i=Ut.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw Z.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Ut.decode(e,n,!0)}catch(i){throw i instanceof z||i instanceof O?Z.getNotFoundInstance():i}}static decode(e,n,i){const s=new Array,a=Be.detectMultiple(e,n,i);for(const l of a.getPoints()){const d=Le.decode(a.getBits(),l[4],l[5],l[6],l[7],Ut.getMinCodewordWidth(l),Ut.getMaxCodewordWidth(l)),h=new Ye(d.getText(),d.getRawBytes(),void 0,l,te.PDF_417);h.putMetadata(Ne.ERROR_CORRECTION_LEVEL,d.getECLevel());const p=d.getOther();p!=null&&h.putMetadata(Ne.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?U.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Ut.getMaxWidth(e[0],e[4]),Ut.getMaxWidth(e[6],e[2])*Se.MODULES_IN_CODEWORD/Se.MODULES_IN_STOP_PATTERN),Math.max(Ut.getMaxWidth(e[1],e[5]),Ut.getMaxWidth(e[7],e[3])*Se.MODULES_IN_CODEWORD/Se.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Ut.getMinWidth(e[0],e[4]),Ut.getMinWidth(e[6],e[2])*Se.MODULES_IN_CODEWORD/Se.MODULES_IN_STOP_PATTERN),Math.min(Ut.getMinWidth(e[1],e[5]),Ut.getMinWidth(e[7],e[3])*Se.MODULES_IN_CODEWORD/Se.MODULES_IN_STOP_PATTERN)))}reset(){}}class ui extends x{}ui.kind="ReaderException";class cs{constructor(e,n){this.verbose=e===!0,n&&this.setHints(n)}decode(e,n){return n&&this.setHints(n),this.decodeInternal(e)}decodeWithState(e){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(e)}setHints(e){this.hints=e;const n=!c(e)&&e.get(H.TRY_HARDER)===!0,i=c(e)?null:e.get(H.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===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 xr(e,this.verbose)),i.includes(te.QR_CODE)&&s.push(new Wn),i.includes(te.DATA_MATRIX)&&s.push(new $n),i.includes(te.AZTEC)&&s.push(new hr),i.includes(te.PDF_417)&&s.push(new Ut),a&&n&&s.push(new xr(e,this.verbose))}s.length===0&&(n||s.push(new xr(e,this.verbose)),s.push(new Wn),s.push(new $n),s.push(new hr),s.push(new Ut),n&&s.push(new xr(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 ui("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 ui)continue}throw new Z("No MultiFormat Readers were able to detect the code.")}}class Xu extends At{constructor(e=null,n=500){const i=new cs;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class qu extends At{constructor(e=500){super(new Ut,e)}}class Yu extends At{constructor(e=500){super(new Wn,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 Nt=Yi;class Ki{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new St(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 St(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);D.arraycopy(e,0,a,0,i);let l=new St(this.field,a);l=l.multiplyByMonomial(n,1);const h=l.divide(s)[1].getCoefficients(),p=n-h.length;for(let w=0;w<p;w++)e[i+w]=0;D.arraycopy(h,0,e,i+p,h.length)}}class _t{constructor(){}static applyMaskPenaltyRule1(e){return _t.applyMaskPenaltyRule1Internal(e,!0)+_t.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 _t.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&&(_t.isWhiteHorizontal(h,d-4,d)||_t.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&&(_t.isWhiteVertical(i,d,l-4,l)||_t.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*_t.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 w=0;w<s;w++)p[w]===1&&n++}const l=e.getHeight()*e.getWidth();return Math.floor(Math.abs(n*2-l)*10/l)*_t.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 w=0;w<a;w++){const b=n?l[d][w]:l[w][d];b===p?h++:(h>=5&&(i+=_t.N1+(h-5)),h=1,p=b)}h>=5&&(i+=_t.N1+(h-5))}return i}}_t.N1=3,_t.N2=3,_t.N3=40,_t.N4=10;class di{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)$.fill(n,e)}equals(e){if(!(e instanceof di))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 ie;for(let n=0,i=this.height;n<i;++n){const s=this.bytes[n];for(let a=0,l=this.width;a<l;++a)switch(s[a]){case 0:e.append(" 0");break;case 1:e.append(" 1");break;default:e.append(" ");break}e.append(`
|
|
64
|
-
`)}return e.toString()}}class rr{constructor(){this.maskPattern=-1}getMode(){return this.mode}getECLevel(){return this.ecLevel}getVersion(){return this.version}getMaskPattern(){return this.maskPattern}getMatrix(){return this.matrix}toString(){const e=new ie;return e.append(`<<
|
|
55
|
+
`}setStatic(r){this.staticPrompt=r}setSkillMeta(r){this.skillMetaPrompt=r}setTemp(r){this.tempPrompt=r}appendTemp(r){this.tempPrompt+=r}}const ho={model:"deepseek-ai/DeepSeek-V3",maxSteps:15,extraTools:{}},Va={apiKey:"sk-trial",baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt",providerType:"deepseek"};function F2(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 U2 extends Kn.BaseModelProvider{transport;agent;promptManager;llmConfig={...ho,...Va};isGenuiEnabled;debugStream=!1;constructor(r,o,c){super(r);let u;c&&"llm"in c?u={...ho,...c}:u={...ho,...Va,...c||{}},this.llmConfig=u;const m={llmConfig:u.llm?{llm:u.llm}:{...u}};this.agent=new Jn.AgentModelProvider(m),this.promptManager=new L2,this.promptManager.setStatic(o)}updateLLMConfig({model:r,baseURL:o,genuiUrl:c,apiKey:u,providerType:f,useReActMode:m,llm:g,providerOptions:C,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 A=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 v;if(f==="deepseek")v=bc;else if(f==="openai")v=xu;else if(typeof f=="function")v=f;else throw new Error(`Unsupported providerType: ${f}`);this.agent.llm=v({apiKey:u,baseURL:A,...x?{headers:x}:{}})}this.llmConfig.providerOptions=C,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:F2(this.llmConfig.providerOptions,D2),prepareStep:({messages:O})=>{this.cleanGetSkillContentToolResult(O);const M=this.cleanupOldSnapshotsInMessages(O),D=Object.keys(this.llmConfig.extraTools||{});Object.values(this.agent.mcpTools||{}).forEach(G=>{D.push(...Object.keys(G||{}))});const B=Array.from(new Set(D)).filter(G=>!this.agent.ignoreToolnames.includes(G));return{system:this.promptManager.getSystemPrompt(),messages:M,activeTools:B}},onStepFinish:O=>{if(O.finishReason==="tool-calls"&&O.content.length>0){const M=O.content[O.content.length-1];if(M.toolName==="get_skill_content"&&M.type==="tool-result"){const D=M.output.content;this.promptManager.appendTemp(D)}}},onFinish:async()=>{await this.agent.closeAll(),this.promptManager.setTemp("")}},f={role:"user",content:c.content},g=[...(O=>O.map(M=>({role:M.role,content:M.content})))(this.agent.responseMessages),f];u.messages=g;const C=await this.agent.chatStream(u),x=new Pp,v=await new P2({debug:this.debugStream,onFinish:()=>{_.nextTick(()=>{x.resolve(),o.onDone()})}}).traverse(C),P={role:"assistant",content:"",uiContent:[]};return _.watch(v,O=>{if(!O)o.onData(P);else{const D=O.steps.map(B=>B.contents).flat().map(B=>{if(B.type==="text")return B2(B.text);if(B.type==="reasoning")return{type:"collapsible-text",title:"思考过程",content:B.text,thinkId:B.id};if(B.type==="tool")return{type:"tool",id:B.id,name:B.toolName,content:JSON.stringify({input:B.inputStr,output:B.output}),status:B.error?"failed":B.running?"running":"success"}});if(O?.error){const B={type:"markdown",content:`**错误**:${O.error.responseBody||O.error.message||"未知错误"}`};D.push(B)}(O.steps.length>=1||O?.error)&&o.onData({...P,uiContent:D.flat(),usage:O.totalUsage||null})}},{deep:!0}),x.promise}chat(r){throw new Error("Method not implemented.")}}const z2=({systemPrompt:t,llmConfig:r,emit:o})=>{const c=new U2({provider:"custom"},t,r),u=new Kn.AIClient({providerImplementation:c,provider:"custom"}),{messageManager:f,createConversation:m,getCurrentConversation:g,switchConversation:C,deleteConversation:x,updateTitle:A,state:v}=Kn.useConversation({client:u,autoSave:!0,events:{onLoaded(){},onReceiveData(K,V,z){z(),V.value[V.value.length-1].role==="assistant"&&V.value.pop(),o("before-ai-render",K),V.value.push(K)}}}),{messageState:P,inputMessage:O,sendMessage:M,abortRequest:D,messages:B,addMessage:G,send:Z}=f,U=_.ref(),Q=async(K,V,z)=>{if(z){const{shouldBlock:S}=await z(K);if(S)return!1}O.value=K;const te=g();if(te&&te.title==="新会话"&&A(te.id,O.value.slice(0,15)),V&&V.length>0){const S=[{type:"text",text:O.value},...V],Te=[];O.value&&Te.push({type:"text",content:O.value});for(const re of V)re.type==="image"&&re.image&&Te.push({type:"image",content:re.image});const ye={role:"user",content:S,uiContent:Te};B.value.push(ye),O.value="",Z()}else{const S={role:"user",content:O.value,uiContent:[{type:"text",content:O.value}]};B.value.push(S),O.value="",Z()}return!0};return _.onMounted(()=>{U.value?.focus()}),_.onUnmounted(()=>{c.agent.closeAll()}),{agent:c.agent,customAgentProvider:c,client:u,messageManager:f,addMessage:G,send:Z,conversationState:v,messages:B,messageState:P,inputMessage:O,sendMessage:M,abortRequest:D,senderRef:U,handleSendMessage:Q,createConversation:m,switchConversation:C,deleteConversation:x,getCurrentConversation:g}};function V2(){}const Pn=Object.assign,Ko=typeof window<"u",Fi=t=>t!==null&&typeof t=="object",tr=t=>t!=null,Ro=t=>typeof t=="function",Z2=t=>Fi(t)&&Ro(t.then)&&Ro(t.catch),yu=t=>typeof t=="number"||/^\d+(\.\d+)?$/.test(t),$2=()=>Ko?/ios|iphone|ipad|ipod/.test(navigator.userAgent.toLowerCase()):!1;function Za(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 H2(t,r,o){return r.reduce((c,u)=>(c[u]=t[u],c),{})}const ki=null,un=[Number,String],fr={type:Boolean,default:!0},W2=t=>({type:Number,default:t}),dn=t=>({type:String,default:t});var Jo=typeof window<"u";function wu(t){let r;_.onMounted(()=>{t(),_.nextTick(()=>{r=!0})}),_.onActivated(()=>{r&&t()})}function _u(t,r,o={}){if(!Jo)return;const{target:c=window,passive:u=!1,capture:f=!1}=o;let m=!1,g;const C=v=>{if(m)return;const P=_.unref(v);P&&!g&&(P.addEventListener(t,r,{capture:f,passive:u}),g=!0)},x=v=>{if(m)return;const P=_.unref(v);P&&g&&(P.removeEventListener(t,r,f),g=!1)};_.onUnmounted(()=>x(c)),_.onDeactivated(()=>x(c)),wu(()=>C(c));let A;return _.isRef(c)&&(A=_.watch(c,(v,P)=>{x(P),C(v)})),()=>{A?.(),x(c),m=!0}}var vi,po;function j2(){if(!vi&&(vi=_.ref(0),po=_.ref(0),Jo)){const t=()=>{vi.value=window.innerWidth,po.value=window.innerHeight};t(),window.addEventListener("resize",t,{passive:!0}),window.addEventListener("orientationchange",t,{passive:!0})}return{width:vi,height:po}}var G2=/scroll|auto|overlay/i,X2=Jo?window:void 0;function q2(t){return t.tagName!=="HTML"&&t.tagName!=="BODY"&&t.nodeType===1}function Y2(t,r=X2){let o=t;for(;o&&o!==r&&q2(o);){const{overflowY:c}=window.getComputedStyle(o);if(G2.test(c))return o;o=o.parentNode}return r}$2();const K2=t=>t.stopPropagation();function vu(t,r){(typeof t.cancelable!="boolean"||t.cancelable)&&t.preventDefault(),K2(t)}j2();function Cn(t){if(tr(t))return yu(t)?`${t}px`:String(t)}function J2(t){if(tr(t)){if(Array.isArray(t))return{width:Cn(t[0]),height:Cn(t[1])};const r=Cn(t);return{width:r,height:r}}}function Q2(t){const r={};return t!==void 0&&(r.zIndex=+t),r}const ex=/-(\w)/g,Cu=t=>t.replace(ex,(r,o)=>o.toUpperCase()),tx=t=>t.replace(/([A-Z])/g,"-$1").toLowerCase().replace(/^-/,""),{hasOwnProperty:nx}=Object.prototype;function rx(t,r,o){const c=r[o];tr(c)&&(!nx.call(t,o)||!Fi(c)?t[o]=c:t[o]=bu(Object(t[o]),c))}function bu(t,r){return Object.keys(r).forEach(o=>{rx(t,r,o)}),t}var ix={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 $a=_.ref("zh-CN"),Ha=_.reactive({"zh-CN":ix}),ox={messages(){return Ha[$a.value]},use(t,r){$a.value=t,this.add({[t]:r})},add(t={}){bu(Ha,t)}};var sx=ox;function ax(t){const r=Cu(t)+".";return(o,...c)=>{const u=sx.messages(),f=Za(u,r+o)||Za(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 lx(t){return(r,o)=>(r&&typeof r!="string"&&(o=r,r=""),r=r?`${t}__${r}`:t,`${r}${Mo(r,o)}`)}function gr(t){const r=`van-${t}`;return[r,lx(r),ax(r)]}const cx="van-haptics-feedback",Wa=5;function ux(t,{args:r=[],done:o,canceled:c,error:u}){if(t){const f=t.apply(null,r);Z2(f)?f.then(m=>{m?o():c&&c()}).catch(u||V2):f?o():c&&c()}else o()}function oi(t){return t.install=r=>{const{name:o}=t;o&&(r.component(o,t),r.component(Cu(`-${o}`),t))},t}const dx=Symbol();function Eu(t){const r=_.getCurrentInstance();r&&Pn(r.proxy,t)}const[fx,ja]=gr("badge"),hx={dot:Boolean,max:un,tag:dn("div"),color:String,offset:Array,content:un,showZero:fr,position:dn("top-right")};var px=_.defineComponent({name:fx,props:hx,setup(t,{slots:r}){const o=()=>{if(r.content)return!0;const{content:g,showZero:C}=t;return tr(g)&&g!==""&&(C||g!==0&&g!=="0")},c=()=>{const{dot:g,max:C,content:x}=t;if(!g&&o())return r.content?r.content():tr(C)&&yu(x)&&+x>+C?`${C}+`:x},u=g=>g.startsWith("-")?g.replace("-",""):`-${g}`,f=_.computed(()=>{const g={background:t.color};if(t.offset){const[C,x]=t.offset,{position:A}=t,[v,P]=A.split("-");r.default?(typeof x=="number"?g[v]=Cn(v==="top"?x:-x):g[v]=v==="top"?Cn(x):u(x),typeof C=="number"?g[P]=Cn(P==="left"?C:-C):g[P]=P==="left"?Cn(C):u(C)):(g.marginTop=Cn(x),g.marginLeft=Cn(C))}return g}),m=()=>{if(o()||t.dot)return _.createVNode("div",{class:ja([t.position,{dot:t.dot,fixed:!!r.default}]),style:f.value},[c()])};return()=>{if(r.default){const{tag:g}=t;return _.createVNode(g,{class:ja("wrapper")},{default:()=>[r.default(),m()]})}return m()}}});const mx=oi(px);let Au=2e3;const gx=()=>++Au,xx=t=>{Au=t},[Iu,yx]=gr("config-provider"),Su=Symbol(Iu),wx={tag:dn("div"),theme:dn("light"),zIndex:Number,themeVars:Object,themeVarsDark:Object,themeVarsLight:Object,themeVarsScope:dn("local"),iconPrefix:String};function _x(t){return t.replace(/([a-zA-Z])(\d)/g,"$1-$2")}function vx(t){const r={};return Object.keys(t).forEach(o=>{const c=_x(tx(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:Iu,props:wx,setup(t,{slots:r}){const o=_.computed(()=>vx(Pn({},t.themeVars,t.theme==="dark"?t.themeVarsDark:t.themeVarsLight)));if(Ko){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(Su,t),_.watchEffect(()=>{t.zIndex!==void 0&&xx(t.zIndex)}),()=>_.createVNode(t.tag,{class:yx(),style:t.themeVarsScope==="local"?o.value:void 0},{default:()=>{var c;return[(c=r.default)==null?void 0:c.call(r)]}})}});const[Cx,Ga]=gr("icon"),bx=t=>t?.includes("/"),Ex={dot:Boolean,tag:dn("i"),name:String,size:un,badge:un,color:String,badgeProps:Object,classPrefix:String};var Ax=_.defineComponent({name:Cx,props:Ex,setup(t,{slots:r}){const o=_.inject(Su,null),c=_.computed(()=>t.classPrefix||o?.iconPrefix||Ga());return()=>{const{tag:u,dot:f,name:m,size:g,badge:C,color:x}=t,A=bx(m);return _.createVNode(mx,_.mergeProps({dot:f,tag:u,class:[c.value,A?"":`${c.value}-${m}`],style:{color:x,fontSize:Cn(g)},content:C},t.badgeProps),{default:()=>{var v;return[(v=r.default)==null?void 0:v.call(r),A&&_.createVNode("img",{class:Ga("image"),src:m},null)]}})}}});const Qo=oi(Ax),[Ix,Xr]=gr("loading"),Sx=Array(12).fill(null).map((t,r)=>_.createVNode("i",{class:Xr("line",String(r+1))},null)),Tx=_.createVNode("svg",{class:Xr("circular"),viewBox:"25 25 50 50"},[_.createVNode("circle",{cx:"50",cy:"50",r:"20",fill:"none"},null)]),Nx={size:un,type:dn("circular"),color:String,vertical:Boolean,textSize:un,textColor:String};var Ox=_.defineComponent({name:Ix,props:Nx,setup(t,{slots:r}){const o=_.computed(()=>Pn({color:t.color},J2(t.size))),c=()=>{const f=t.type==="spinner"?Sx:Tx;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:Cn(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 kx=oi(Ox),Rx={show:Boolean,zIndex:un,overlay:fr,duration:un,teleport:[String,Object],lockScroll:fr,lazyRender:fr,beforeClose:Function,overlayProps:Object,overlayStyle:Object,overlayClass:ki,transitionAppear:Boolean,closeOnClickOverlay:fr};function Mx(t,r){return t>r?"horizontal":r>t?"vertical":""}function Dx(){const t=_.ref(0),r=_.ref(0),o=_.ref(0),c=_.ref(0),u=_.ref(0),f=_.ref(0),m=_.ref(""),g=_.ref(!0),C=()=>m.value==="vertical",x=()=>m.value==="horizontal",A=()=>{o.value=0,c.value=0,u.value=0,f.value=0,m.value="",g.value=!0};return{move:(O=>{const M=O.touches[0];o.value=(M.clientX<0?0:M.clientX)-t.value,c.value=M.clientY-r.value,u.value=Math.abs(o.value),f.value=Math.abs(c.value);const D=10;(!m.value||u.value<D&&f.value<D)&&(m.value=Mx(u.value,f.value)),g.value&&(u.value>Wa||f.value>Wa)&&(g.value=!1)}),start:(O=>{A(),t.value=O.touches[0].clientX,r.value=O.touches[0].clientY}),reset:A,startX:t,startY:r,deltaX:o,deltaY:c,offsetX:u,offsetY:f,direction:m,isVertical:C,isHorizontal:x,isTap:g}}let Vr=0;const Xa="van-overflow-hidden";function Px(t,r){const o=Dx(),c="01",u="10",f=A=>{o.move(A);const v=o.deltaY.value>0?u:c,P=Y2(A.target,t.value),{scrollHeight:O,offsetHeight:M,scrollTop:D}=P;let B="11";D===0?B=M>=O?"00":"01":D+M>=O&&(B="10"),B!=="11"&&o.isVertical()&&!(parseInt(B,2)&parseInt(v,2))&&vu(A)},m=()=>{document.addEventListener("touchstart",o.start),document.addEventListener("touchmove",f,{passive:!1}),Vr||document.body.classList.add(Xa),Vr++},g=()=>{Vr&&(document.removeEventListener("touchstart",o.start),document.removeEventListener("touchmove",f),Vr--,Vr||document.body.classList.remove(Xa))},C=()=>r()&&m(),x=()=>r()&&g();wu(C),_.onDeactivated(x),_.onBeforeUnmount(x),_.watch(r,A=>{A?m():g()})}function Tu(t){const r=_.ref(!1);return _.watch(t,o=>{o&&(r.value=o)},{immediate:!0}),o=>()=>r.value?o():null}const qa=()=>{var t;const{scopeId:r}=((t=_.getCurrentInstance())==null?void 0:t.vnode)||{};return r?{[r]:""}:null},[Bx,Lx]=gr("overlay"),Fx={show:Boolean,zIndex:un,duration:un,className:ki,lockScroll:fr,lazyRender:fr,customStyle:Object,teleport:[String,Object]};var Ux=_.defineComponent({name:Bx,inheritAttrs:!1,props:Fx,setup(t,{attrs:r,slots:o}){const c=_.ref(),u=Tu(()=>t.show||!t.lazyRender),f=g=>{t.lockScroll&&vu(g)},m=u(()=>{var g;const C=Pn(Q2(t.zIndex),t.customStyle);return tr(t.duration)&&(C.animationDuration=`${t.duration}s`),_.withDirectives(_.createVNode("div",_.mergeProps({ref:c,style:C,class:[Lx(),t.className]},r),[(g=o.default)==null?void 0:g.call(o)]),[[_.vShow,t.show]])});return _u("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 zx=oi(Ux),Vx=Pn({},Rx,{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}),[Zx,Ya]=gr("popup");var $x=_.defineComponent({name:Zx,inheritAttrs:!1,props:Vx,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(),C=Tu(()=>t.show||!t.lazyRender),x=_.computed(()=>{const V={zIndex:m.value};if(tr(t.duration)){const z=t.position==="center"?"animationDuration":"transitionDuration";V[z]=`${t.duration}s`}return V}),A=()=>{u||(u=!0,m.value=t.zIndex!==void 0?+t.zIndex:gx(),r("open"))},v=()=>{u&&ux(t.beforeClose,{done(){u=!1,r("close"),r("update:show",!1)}})},P=V=>{r("clickOverlay",V),t.closeOnClickOverlay&&v()},O=()=>{if(t.overlay){const V=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(zx,_.mergeProps(V,qa(),{onClick:P}),{default:c["overlay-content"]})}},M=V=>{r("clickCloseIcon",V),v()},D=()=>{if(t.closeable)return _.createVNode(Qo,{role:"button",tabindex:0,name:t.closeIcon,class:[Ya("close-icon",t.closeIconPosition),cx],classPrefix:t.iconPrefix,onClick:M},null)};let B;const G=()=>{B&&clearTimeout(B),B=setTimeout(()=>{r("opened")})},Z=()=>r("closed"),U=V=>r("keydown",V),Q=C(()=>{var V;const{destroyOnClose:z,round:te,position:S,safeAreaInsetTop:Te,safeAreaInsetBottom:ye,show:re}=t;if(!(!re&&z))return _.withDirectives(_.createVNode("div",_.mergeProps({ref:g,style:x.value,role:"dialog",tabindex:0,class:[Ya({round:te,[S]:S}),{"van-safe-area-top":Te,"van-safe-area-bottom":ye}],onKeydown:U},o,qa()),[(V=c.default)==null?void 0:V.call(c),D()]),[[_.vShow,re]])}),K=()=>{const{position:V,transition:z,transitionAppear:te}=t,S=V==="center"?"van-fade":`van-popup-slide-${V}`;return _.createVNode(_.Transition,{name:z||S,appear:te,onAfterEnter:G,onAfterLeave:Z},{default:Q})};return _.watch(()=>t.show,V=>{V&&!u&&(A(),o.tabindex===0&&_.nextTick(()=>{var z;(z=g.value)==null||z.focus()})),!V&&u&&(u=!1,r("close"))}),Eu({popupRef:g}),Px(g,()=>t.show&&t.lockScroll),_u("popstate",()=>{t.closeOnPopstate&&(v(),f=!1)}),_.onMounted(()=>{t.show&&A()}),_.onActivated(()=>{f&&(r("update:show",!0),f=!1)}),_.onDeactivated(()=>{t.show&&t.teleport&&(v(),f=!0)}),_.provide(dx,()=>t.show),()=>t.teleport?_.createVNode(_.Teleport,{to:t.teleport},{default:()=>[O(),K()]}):_.createVNode(_.Fragment,null,[O(),K()])}});const Hx=oi($x);let Zr=0;function Wx(t){t?(Zr||document.body.classList.add("van-toast--unclickable"),Zr++):Zr&&(Zr--,Zr||document.body.classList.remove("van-toast--unclickable"))}const[jx,Sr]=gr("toast"),Gx=["show","overlay","teleport","transition","overlayClass","overlayStyle","closeOnClickOverlay","zIndex"],Xx={icon:String,show:Boolean,type:dn("text"),overlay:Boolean,message:un,iconSize:un,duration:W2(2e3),position:dn("middle"),teleport:[String,Object],wordBreak:String,className:ki,iconPrefix:String,transition:dn("van-fade"),loadingType:String,forbidClick:Boolean,overlayClass:ki,overlayStyle:Object,closeOnClick:Boolean,closeOnClickOverlay:Boolean,zIndex:un};var qx=_.defineComponent({name:jx,props:Xx,emits:["update:show"],setup(t,{emit:r,slots:o}){let c,u=!1;const f=()=>{const v=t.show&&t.forbidClick;u!==v&&(u=v,Wx(u))},m=v=>r("update:show",v),g=()=>{t.closeOnClick&&m(!1)},C=()=>clearTimeout(c),x=()=>{const{icon:v,type:P,iconSize:O,iconPrefix:M,loadingType:D}=t;if(v||P==="success"||P==="fail")return _.createVNode(Qo,{name:v||P,size:O,class:Sr("icon"),classPrefix:M},null);if(P==="loading")return _.createVNode(kx,{class:Sr("loading"),size:O,type:D},null)},A=()=>{const{type:v,message:P}=t;if(o.message)return _.createVNode("div",{class:Sr("text")},[o.message()]);if(tr(P)&&P!=="")return v==="html"?_.createVNode("div",{key:0,class:Sr("text"),innerHTML:String(P)},null):_.createVNode("div",{class:Sr("text")},[P])};return _.watch(()=>[t.show,t.forbidClick],f),_.watch(()=>[t.show,t.type,t.message,t.duration],()=>{C(),t.show&&t.duration>0&&(c=setTimeout(()=>{m(!1)},t.duration))}),_.onMounted(f),_.onUnmounted(f),()=>_.createVNode(Hx,_.mergeProps({class:[Sr([t.position,t.wordBreak==="normal"?"break-normal":t.wordBreak,{[t.type]:!t.icon}]),t.className],lockScroll:!1,onClick:g,onClosed:C,"onUpdate:show":m},H2(t,Gx)),{default:()=>[x(),A()]})}});function Yx(){const t=_.reactive({show:!1}),r=u=>{t.show=u},o=u=>{Pn(t,u,{transitionAppear:!0}),r(!0)},c=()=>r(!1);return Eu({open:o,close:c,toggle:r}),{open:o,close:c,state:t,toggle:r}}function Kx(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 Jx={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=[],Qx=!1,Ka=Pn({},Jx);const ey=new Map;function Nu(t){return Fi(t)?t:{message:t}}function ty(){const{instance:t}=Kx({setup(){const r=_.ref(""),{open:o,state:c,close:u,toggle:f}=Yx(),m=()=>{},g=()=>{const C={onClosed:m,"onUpdate:show":f};return _.createVNode(qx,_.mergeProps(c,C),null)};return _.watch(r,C=>{c.message=C}),_.getCurrentInstance().render=g,{open:o,close:u,message:r}}});return t}function ny(){if(!bi.length||Qx){const t=ty();bi.push(t)}return bi[bi.length-1]}function Je(t={}){if(!Ko)return{};const r=ny(),o=Nu(t);return r.open(Pn({},Ka,ey.get(o.type||Ka.type),o)),r}const ry=t=>r=>Je(Pn({type:t},Nu(r))),Ou=ry("loading"),iy=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=oy(u);f&&o.push({name:c,config:f})}return o}catch(r){throw new Error(`JSON 解析失败: ${r instanceof Error?r.message:"未知错误"}`)}},oy=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}},sy=(t,r,o)=>{const c=async(f,m,g,C,x)=>{if(await t.insertMcpServer(f,m)){const v=t.mcpTools[f];if(v){const O={id:`plugin-${f.replace("mcp-server-","")}`,name:g,icon:x||o,description:C||(typeof m=="object"&&"url"in m?m.url:""),enabled:!0,expanded:!0,tools:Object.keys(v).map(M=>({id:M,name:M,description:v[M].description,enabled:!0})),originMcpConfig:_.markRaw(m)};return r.value.push(O),!0}else return await t.removeMcpServer(f),!1}else return!1};return{handleCustomAdd:async(f,m)=>{Ou("添加工具中...");try{if(f==="code"){if(typeof m!="string"){Je("添加工具失败:code 类型需要 JSON 字符串格式");return}const Z=iy(m);if(Z.length===0){Je("添加工具失败:JSON 配置格式不正确或未找到有效的服务器配置");return}let U=0,Q=0;for(const{name:K,config:V}of Z){const z=`mcp-server-${K}`;await c(z,V,K)?U++:Q++}await t.closeAll(),Q===0?Je(`成功添加 ${U} 个工具`):U>0?Je(`成功添加 ${U} 个工具,${Q} 个失败`):Je("添加工具失败:所有服务器都无法连接");return}if(typeof m=="string"){Je("添加工具失败:数据格式不正确");return}const{description:g,headers:C,name:x,thumbnail:A,type:v,url:P}=m;if(!x||!P||!v){Je("添加工具失败:缺少必要参数(名称、URL或类型)");return}const M=`mcp-server-${`custom-${x}-${Date.now()}`}`;let D;if(typeof C=="string"&&C.trim())try{D=JSON.parse(C)}catch(Z){console.warn("Failed to parse headers JSON:",Z)}else typeof C=="object"&&(D=C);await c(M,{type:v,url:P,headers:D,useAISdkClient:!0},x,g,A)?(await t.closeAll(),Je("添加工具完成")):Je("重复添加工具或无法获取工具列表")}catch(g){console.error("handleCustomAdd error:",g),Je(`添加工具失败:${g instanceof Error?g.message:"未知错误"}`)}}}};function ay(t,r,o){const c=_.ref([]),u=_.ref([]),f=_.ref(!1),m=K=>t.mcpServers[K]?.type==="local",g=(K,V)=>{V?t.ignoreToolnames=t.ignoreToolnames.filter(z=>z!==K):t.ignoreToolnames.includes(K)||t.ignoreToolnames.push(K)},C=(K,V)=>{r.value||(r.value={});const z={...r.value};K===null?Object.keys(z).forEach(te=>{z[te]=V}):z[K]=V,r.value=z},x=K=>{const V=u.value.find(z=>z.id===K);V&&(V.addState="idle")},A=K=>{const V=t.mcpTools[K];if(!V)return[];const z=m(K),te=r.value||{};return Object.keys(V).map(S=>{const Te=Object.prototype.hasOwnProperty.call(te,S),ye=z&&Te?te[S]:!0;return g(S,ye),{id:S,name:S,description:V[S].description,enabled:ye}})},v=()=>{c.value.forEach(V=>{const z=new Map(V.tools.map(S=>[S.id,S.enabled])),te=A(V.id).map(S=>{const Te=z.has(S.id)?!!z.get(S.id):S.enabled;return g(S.id,Te),{...S,enabled:Te}});V.tools=te});const K=new Set(c.value.flatMap(V=>V.tools.map(z=>z.id)));t.ignoreToolnames=t.ignoreToolnames.filter(V=>K.has(V))},P=async K=>{const V=K.pluginId;if(!await t.insertMcpServer(V,K.mcpServer))return!1;if(!t.mcpTools[V])return await t.removeMcpServer(V),!1;const S=A(V);if(S.length===0&&K.mcpServer?.type!=="builtin")return await t.removeMcpServer(V),!1;const Te=c.value.find(re=>re.id===K.pluginId);if(Te)return Te.tools=S,Te.originMcpConfig=_.markRaw(K.mcpServer),!0;const ye={id:K.pluginId,name:K.name,icon:K.icon||o,description:K.description,enabled:!0,expanded:!1,tools:S,originMcpConfig:_.markRaw(K.mcpServer)};return c.value.push(ye),!0};return{installedPlugins:c,marketPlugins:u,pluginVisible:f,loadMcpServerToPlugin:async(K,V)=>{let z,te;if("type"in V&&V.type==="local")z="本地工具",te="本地工具列表";else if("type"in V&&V.type==="builtin")z="浏览器内置工具",te="通过 navigator.modelContextTesting 暴露的浏览器原生 MCP 工具";else{const S=new URL(V.url);z=S.origin,te=S.searchParams.get("sessionId")||("sessionId"in V?V.sessionId:"")||""}await P({pluginId:K,name:z,description:te,mcpServer:V})},togglePlugin:(K,V)=>{const z=m(K.id);K.tools.forEach(te=>{te.enabled=V,g(te.id,V),z&&C(te.id,V)})},toggleTool:(K,V,z)=>{const te=m(K.id);K.tools.forEach(S=>{S.id===V&&(S.enabled=z)}),g(V,z),te&&C(V,z)},deletePlugin:async K=>{const V=c.value.find(te=>te.id===K.id);if(!V)return;c.value=c.value.filter(te=>te.id!==V.id),x(V.id);const z=K.id;await t.removeMcpServer(z)},addPluginCore:P,addPluginFromMarket:async K=>{K.addState="loading";const V={type:K.type,url:K.url,headers:K.headers,useAISdkClient:!0},z=await P({pluginId:K.id,name:K.name,description:K.description||"",icon:K.icon,mcpServer:V});K.addState=z?"added":"idle"},addPluginFromScan:async(K,V)=>{const z={type:"streamableHttp",url:`${V}mcp?sessionId=${K}`},te=new URL(`${V}mcp?sessionId=${K}`);return await P({pluginId:`plugin-${K}`,name:te.origin,description:K,mcpServer:z})},handleClientDisconnected:async K=>{const V=K,z=c.value.find(te=>te.id===V);return await t.removeMcpServer(K),z?(c.value=c.value.filter(te=>te.id!==V),x(V),z):null},searchPlugin:(K,V)=>K.trim()===""||V.name.toLowerCase().includes(K.toLowerCase()),syncInstalledPluginTools:v}}function ly(t){const{onToolCatalogChanged:r}=t,o=typeof window<"u"&&window!==window.top,c=P=>P===window||o&&P===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(P){console.warn("[useRouteBasedTools] refresh tool catalog failed:",P)}}while(m&&!u)}finally{f=!1}}},C=P=>{!c(P.source)||P.data?.type!==Jn.MSG_TOOL_CATALOG_CHANGED||g()};let x=!1;const A=()=>{x||(u=!1,x=!0,window.addEventListener("message",C),o&&window.parent&&window.parent.postMessage({type:Jn.MSG_REMOTER_READY},"*"))},v=()=>{x&&(u=!0,m=!1,x=!1,window.removeEventListener("message",C))};_.onMounted(()=>{A()}),_.onUnmounted(()=>{v()})}function cy(t){const{skillsRef:r,customAgentProvider:o}=t,c=_.computed(()=>{const g=r?.value;return g?Jn.getSkillOverviews(g):[]}),u=_.computed(()=>{const g=c.value;return g.length>0?Jn.formatSkillsForSystemPrompt(g):""}),f=_.computed(()=>{const g=r?.value;return g?Jn.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 uy=["title"],dy=_.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:C,outputTokenDetails:x}=r.usage,A=C?.cacheReadTokens||0,v=x?.reasoningTokens||0;return{cachedInputTokens:[A/g*100+"%",A],inputTokens:[(f-A)/g*100+"%",f],reasoningTokens:[v/g*100+"%",v],outputTokens:[(m-v)/g*100+"%",m]}}),u=_.computed(()=>{const{inputTokens:f=0,outputTokens:m=0,totalTokens:g=0,inputTokenDetails:C,outputTokenDetails:x}=r.usage,A=C?.cacheReadTokens||0,v=x?.reasoningTokens||0;return[`inputTokens: ${f}`,`outputTokens: ${m}`,`totalTokens: ${g}`,`cachedInputTokens: ${A}`,`reasoningTokens: ${v}`].join(`
|
|
56
|
+
`)});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,C)=>(_.openBlock(),_.createElementBlock("div",{key:C,class:_.normalizeClass(C),style:_.normalizeStyle({width:g[0]})},null,6))),128))],8,uy))}}),nr=(t,r)=>{const o=t.__vccOpts||t;for(const[c,u]of r)o[c]=u;return o},fy=nr(dy,[["__scopeId","data-v-000098b4"]]),hy={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 py(t,r){return _.openBlock(),_.createElementBlock("svg",hy,[...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 ku={render:py};function my(t){const{messages:r,messageState:o,inputMessage:c,handleSendMessage:u}=t,f=_.h(ku,{style:{width:"48px",height:"48px"}}),m=_.ref({}),g=_.computed(()=>Kn.GeneratingStatus.includes(o.status)),C=_.computed(()=>r.value.findLastIndex(O=>O.role==="assistant")),x=O=>O===void 0?"复制":m.value[O]?"复制成功":"复制",A=async O=>{const D=r.value[O].uiContent.map(B=>B.content).join(`
|
|
57
|
+
`);try{await navigator.clipboard.writeText(D),O!==void 0&&(m.value[O]=!0,setTimeout(()=>{m.value[O]=!1},3e3))}catch(B){console.error("复制失败:",B),Je("复制失败,请重试")}},v=async O=>{const M=r.value.findLastIndex((B,G)=>B.role==="user"&&G<=O);if(M===-1){console.warn("未找到可重新生成的用户消息"),Je("无法重新生成消息");return}const D=r.value[M];if(r.value=r.value.slice(0,M),Array.isArray(D.content)){const G=D.content.find(U=>U.type==="text")?.text||"",Z=D.content.filter(U=>U.type!=="text");c.value=G,await u(G,Z.length>0?Z:void 0)}else c.value=D.content,await u(D.content)},P={assistant:{type:"markdown",placement:"start",avatar:t.props.roleAvatar.assistant,maxWidth:"80%",customContentField:"uiContent",slots:{footer:({index:O})=>{const M=C.value===O;return g.value&&M?"":_.h("div",{class:["assistant-actions",{"latest-assistant":M,"historical-assistant":!M}],style:{display:"flex",justifyContent:"flex-start",alignItems:"center",gap:"4px"}},[_.h(Ut.IconButton,{icon:Or.IconRefresh,size:24,onClick:()=>v(O)}),_.h(hd,{effect:"light",content:x(O),placement:"right",visibleArrow:!1},()=>_.h(Ut.IconButton,{icon:Or.IconCopy,size:24,onClick:()=>A(O)})),r.value[O].usage?_.h(fy,{usage:r.value[O].usage}):null])}}},user:{placement:"end",avatar:t.props.roleAvatar.user,maxWidth:"80%",customContentField:"uiContent"}};return{welcomeIcon:f,roles:P,copyingStates:m,isProcessing:g,latestAssistantMessageIndex:C,copyTooltipContent:x,copyMessageToClipboard:A,regenerateMessage:v}}function gy(t){const{createConversation:r,switchConversation:o,deleteConversation:c,getCurrentConversation:u,abortRequest:f,conversationState:m,customAgentProvider:g}=t,C=_.ref(!1),x=()=>{_.nextTick(()=>{const M=document.querySelector("div.tr-bubble-list");M&&M.scrollTo({top:M.scrollHeight,behavior:"smooth"})})};return{showHistory:C,handleCreateConversation:()=>{f();const M=[];g.agent.responseMessages=M,r();const D=u();D.aiSdkMessages=M},handleHistorySelect:M=>{f(),o(M.id);const D=u();g.agent.responseMessages=D.aiSdkMessages,C.value=!1,x()},handleHistoryUpdateTitle:(M,D)=>{D.title=M},handleHistoryDelete:(M,D)=>{if(M.id==="delete"){if(m.currentId===D.id){Je("不允许删除当前会话");return}c(D.id)}},scrollToBottom:x}}function xy(t){const{sessionId:r,agentRoot:o,mode:c,qrCodeUrl:u,remoteUrl:f,menuItems:m,AILogoUrl:g,show:C,addPluginFromScan:x,inputMessage:A}=t;let v=null,P=!1;const O=async Z=>{if(Ou("添加工具中..."),Z){const U=await x(Z,o);Je(U?"添加工具完成":"重复添加工具或添加失败")}else Je("添加工具失败")},M=async Z=>{if(/^\/[A-Za-z0-9-]{6,}$/.test(Z)){try{const U=await fetch(`${o}client?sessionId=${Z.slice(1)}`);if(!U.ok)throw new Error(`HTTP ${U.status}`);const K=(await U.json())?.data?.sessionId;K?await O(K):Je("添加工具失败,请检查识别码是否正确"),A.value=""}catch(U){console.error("识别码处理失败:",U),Je("添加工具失败,请检查识别码是否正确"),A.value=""}return!0}return!1},D=()=>{const Z=U=>{v&&(v.destroy(),v=null),v=Jn.createRemoter({sessionId:U||void 0,qrCodeUrl:u,remoteUrl:f,menuItems:m?.value,logoUrl:g,onShowAIChat:()=>C.value=!0}),C.value&&v.hide()};_.watch(r,U=>{if(c!=="remoter")return;const Q=!!U;v?!P&&Q&&(Z(U),P=!0):(Z(U),P=Q)},{immediate:!0}),m&&_.watch(m,()=>{c==="remoter"&&v&&Z(r.value)},{deep:!0}),_.watch(C,U=>{v&&(U?v.hide():v.show())},{immediate:!0})},B=()=>{_.watch(r,Z=>{Z&&O(Z)})};return{handleScanSuccess:O,handleSessionIdInput:M,initialize:()=>{r.value&&O(r.value),c==="remoter"&&D(),B()},initializeRemoter:D,watchSessionIdChanges:B}}function yy(t){return new Promise((r,o)=>{const c=new FileReader;c.onload=()=>r(c.result),c.onerror=o,c.readAsDataURL(t)})}function wy(t){return t.type.startsWith("image/")}function _y(t,r){const o=r*1024*1024;return t.size<=o}async function vy(t){if(t.length===0)return[];const r=[];for(const o of t)if(o.rawFile)try{const c=await yy(o.rawFile);wy(o.rawFile)&&r.push({type:"image",image:c})}catch(c){console.error("文件转换失败:",c),Je({type:"fail",message:"文件处理失败"})}return r}function Cy(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))){Je({type:"fail",message:`不支持的文件类型: ${g.type}`});continue}if(!_y(g,f)){Je({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 by(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:C}=Cy({maxFileSize:u,supportedTypes:f});return _.watch(o,()=>{if(m.value.length>0&&r.value){const O=r.value.multimodal?.maxFileSize||10,M=r.value.multimodal?.supportedMimeTypes||["image/"];m.value.filter(B=>{if(!B.rawFile||!M.some(U=>B.rawFile.type.startsWith(U)))return!0;const Z=O*1024*1024;return B.rawFile.size>Z}).length>0&&(C(),Je("切换模型后,之前选择的附件已清空"))}}),{hasMultimodalSupport:c,attachments:m,onFilesSelected:O=>{g(O)},checkCanSendAttachments:()=>m.value.length>0&&!c.value?(Je("当前模型不支持附件,请先移除附件或切换支持多模态的模型"),!1):!0,processAttachments:async()=>m.value.length===0?[]:await vy(m.value),cleanupAttachments:()=>{m.value.length>0&&C()},clearAttachments:C}}var _e;(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"})(_e||(_e={}));var Ja=new Map([[_e.QR_CODE,"QR_CODE"],[_e.AZTEC,"AZTEC"],[_e.CODABAR,"CODABAR"],[_e.CODE_39,"CODE_39"],[_e.CODE_93,"CODE_93"],[_e.CODE_128,"CODE_128"],[_e.DATA_MATRIX,"DATA_MATRIX"],[_e.MAXICODE,"MAXICODE"],[_e.ITF,"ITF"],[_e.EAN_13,"EAN_13"],[_e.EAN_8,"EAN_8"],[_e.PDF_417,"PDF_417"],[_e.RSS_14,"RSS_14"],[_e.RSS_EXPANDED,"RSS_EXPANDED"],[_e.UPC_A,"UPC_A"],[_e.UPC_E,"UPC_E"],[_e.UPC_EAN_EXTENSION,"UPC_EAN_EXTENSION"]]),Qa;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.URL=1]="URL"})(Qa||(Qa={}));function Ey(t){return Object.values(_e).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 Ay=(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})(),Ru=(function(){function t(r,o){this.format=r,this.formatName=o}return t.prototype.toString=function(){return this.formatName},t.create=function(r){if(!Ja.has(r))throw"".concat(r," not in html5QrcodeSupportedFormatsTextMap");return new t(r,Ja.get(r))},t})(),el=(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 Iy=(function(){function t(){}return t.createFrom=function(r){return{errorMessage:r,type:Do.UNKWOWN_ERROR}},t})(),Sy=(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 Fn(t){return typeof t>"u"||t===null}var Nr=(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})(),Mu=(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,C=m;g<C.length;g++){var x=C[g];if(f.has(x))return o.logError("".concat(x," is not supported videoConstaints."),!0),!1}return!0},t})(),Ei=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Ty(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Wr={exports:{}},Ny=Wr.exports,tl;function Oy(){return tl||(tl=1,(function(t,r){(function(o,c){c(r)})(Ny,(function(o){function c(b){return b==null}var u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,e){b.__proto__=e}||function(b,e){for(var n in e)e.hasOwnProperty(n)&&(b[n]=e[n])};function f(b,e){u(b,e);function n(){this.constructor=b}b.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}function m(b,e){var n=Object.setPrototypeOf;n?n(b,e):b.__proto__=e}function g(b,e){e===void 0&&(e=b.constructor);var n=Error.captureStackTrace;n&&n(b,e)}var C=(function(b){f(e,b);function e(n){var i=this.constructor,s=b.call(this,n)||this;return Object.defineProperty(s,"name",{value:i.name,enumerable:!1}),m(s,i.prototype),g(s),s}return e})(Error);class x extends C{constructor(e=void 0){super(e),this.message=e}getKind(){return this.constructor.kind}}x.kind="Exception";class A extends x{}A.kind="ArgumentException";class v extends x{}v.kind="IllegalArgumentException";class P{constructor(e){if(this.binarizer=e,e===null)throw new v("Binarizer must be non-null.")}getWidth(){return this.binarizer.getWidth()}getHeight(){return this.binarizer.getHeight()}getBlackRow(e,n){return this.binarizer.getBlackRow(e,n)}getBlackMatrix(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix}isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported()}crop(e,n,i,s){const a=this.binarizer.getLuminanceSource().crop(e,n,i,s);return new P(this.binarizer.createBinarizer(a))}isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported()}rotateCounterClockwise(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new P(this.binarizer.createBinarizer(e))}rotateCounterClockwise45(){const e=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new P(this.binarizer.createBinarizer(e))}toString(){try{return this.getBlackMatrix().toString()}catch{return""}}}class O extends x{static getChecksumInstance(){return new O}}O.kind="ChecksumException";class M{constructor(e){this.source=e}getLuminanceSource(){return this.source}getWidth(){return this.source.getWidth()}getHeight(){return this.source.getHeight()}}class D{static arraycopy(e,n,i,s,a){for(;a--;)i[s++]=e[n++]}static currentTimeMillis(){return Date.now()}}class B extends x{}B.kind="IndexOutOfBoundsException";class G extends B{constructor(e=void 0,n=void 0){super(n),this.index=e,this.message=n}}G.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 v("fromIndex("+n+") > toIndex("+i+")");if(n<0)throw new G(n);if(i>e)throw new G(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 D.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 U{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)}}U.MIN_VALUE_32_BITS=-2147483648,U.MAX_VALUE=Number.MAX_SAFE_INTEGER;class Q{constructor(e,n){e===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=e,n==null?this.bits=Q.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=Q.makeArray(e);D.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+U.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+U.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 v;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 v;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 v("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 v("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 Q))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 Q(this.size,this.bits.slice())}}var K;(function(b){b[b.OTHER=0]="OTHER",b[b.PURE_BARCODE=1]="PURE_BARCODE",b[b.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",b[b.TRY_HARDER=3]="TRY_HARDER",b[b.CHARACTER_SET=4]="CHARACTER_SET",b[b.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",b[b.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",b[b.ASSUME_GS1=7]="ASSUME_GS1",b[b.RETURN_CODABAR_START_END=8]="RETURN_CODABAR_START_END",b[b.NEED_RESULT_POINT_CALLBACK=9]="NEED_RESULT_POINT_CALLBACK",b[b.ALLOWED_EAN_EXTENSIONS=10]="ALLOWED_EAN_EXTENSIONS"})(K||(K={}));var V=K;class z extends x{static getFormatInstance(){return new z}}z.kind="FormatException";var te;(function(b){b[b.Cp437=0]="Cp437",b[b.ISO8859_1=1]="ISO8859_1",b[b.ISO8859_2=2]="ISO8859_2",b[b.ISO8859_3=3]="ISO8859_3",b[b.ISO8859_4=4]="ISO8859_4",b[b.ISO8859_5=5]="ISO8859_5",b[b.ISO8859_6=6]="ISO8859_6",b[b.ISO8859_7=7]="ISO8859_7",b[b.ISO8859_8=8]="ISO8859_8",b[b.ISO8859_9=9]="ISO8859_9",b[b.ISO8859_10=10]="ISO8859_10",b[b.ISO8859_11=11]="ISO8859_11",b[b.ISO8859_13=12]="ISO8859_13",b[b.ISO8859_14=13]="ISO8859_14",b[b.ISO8859_15=14]="ISO8859_15",b[b.ISO8859_16=15]="ISO8859_16",b[b.SJIS=16]="SJIS",b[b.Cp1250=17]="Cp1250",b[b.Cp1251=18]="Cp1251",b[b.Cp1252=19]="Cp1252",b[b.Cp1256=20]="Cp1256",b[b.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",b[b.UTF8=22]="UTF8",b[b.ASCII=23]="ASCII",b[b.Big5=24]="Big5",b[b.GB18030=25]="GB18030",b[b.EUC_KR=26]="EUC_KR"})(te||(te={}));class S{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,S.VALUE_IDENTIFIER_TO_ECI.set(e,this),S.NAME_TO_ECI.set(i,this);const a=this.values;for(let l=0,d=a.length;l!==d;l++){const h=a[l];S.VALUES_TO_ECI.set(h,this)}for(const l of s)S.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 z("incorect value");const n=S.VALUES_TO_ECI.get(e);if(n===void 0)throw new z("incorect value");return n}static getCharacterSetECIByName(e){const n=S.NAME_TO_ECI.get(e);if(n===void 0)throw new z("incorect value");return n}equals(e){if(!(e instanceof S))return!1;const n=e;return this.getName()===n.getName()}}S.VALUE_IDENTIFIER_TO_ECI=new Map,S.VALUES_TO_ECI=new Map,S.NAME_TO_ECI=new Map,S.Cp437=new S(te.Cp437,Int32Array.from([0,2]),"Cp437"),S.ISO8859_1=new S(te.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),S.ISO8859_2=new S(te.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),S.ISO8859_3=new S(te.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),S.ISO8859_4=new S(te.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),S.ISO8859_5=new S(te.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),S.ISO8859_6=new S(te.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),S.ISO8859_7=new S(te.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),S.ISO8859_8=new S(te.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),S.ISO8859_9=new S(te.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),S.ISO8859_10=new S(te.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),S.ISO8859_11=new S(te.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),S.ISO8859_13=new S(te.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),S.ISO8859_14=new S(te.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),S.ISO8859_15=new S(te.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),S.ISO8859_16=new S(te.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),S.SJIS=new S(te.SJIS,20,"SJIS","Shift_JIS"),S.Cp1250=new S(te.Cp1250,21,"Cp1250","windows-1250"),S.Cp1251=new S(te.Cp1251,22,"Cp1251","windows-1251"),S.Cp1252=new S(te.Cp1252,23,"Cp1252","windows-1252"),S.Cp1256=new S(te.Cp1256,24,"Cp1256","windows-1256"),S.UnicodeBigUnmarked=new S(te.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),S.UTF8=new S(te.UTF8,26,"UTF8","UTF-8"),S.ASCII=new S(te.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),S.Big5=new S(te.Big5,28,"Big5"),S.GB18030=new S(te.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),S.EUC_KR=new S(te.EUC_KR,30,"EUC_KR","EUC-KR");class Te extends x{}Te.kind="UnsupportedOperationException";class ye{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!ye.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 S?e:S.getCharacterSetECIByName(e)}static decodeFallback(e,n){const i=this.encodingCharacterSet(n);if(ye.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(S.UnicodeBigUnmarked))return String.fromCharCode.apply(null,new Uint16Array(e.buffer));throw new Te(`Encoding ${this.encodingName(n)} not supported by fallback.`)}static isDecodeFallbackSupported(e){return e.equals(S.UTF8)||e.equals(S.ISO8859_1)||e.equals(S.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 re{static castAsNonUtf8Char(e,n=null){const i=n?n.getName():this.ISO88591;return ye.decode(new Uint8Array([e]),i)}static guessEncoding(e,n){if(n!=null&&n.get(V.CHARACTER_SET)!==void 0)return n.get(V.CHARACTER_SET).toString();const i=e.length;let s=!0,a=!0,l=!0,d=0,h=0,p=0,y=0,E=0,I=0,k=0,L=0,F=0,H=0,Y=0;const le=e.length>3&&e[0]===239&&e[1]===187&&e[2]===191;for(let ce=0;ce<i&&(s||a||l);ce++){const ae=e[ce]&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)&&Y++),a&&(E>0?ae<64||ae===127||ae>252?a=!1:E--:ae===128||ae===160||ae>239?a=!1:ae>160&&ae<224?(I++,L=0,k++,k>F&&(F=k)):ae>127?(E++,k=0,L++,L>H&&(H=L)):(k=0,L=0))}return l&&d>0&&(l=!1),a&&E>0&&(a=!1),l&&(le||h+p+y>0)?re.UTF8:a&&(re.ASSUME_SHIFT_JIS||F>=3||H>=3)?re.SHIFT_JIS:s&&a?F===2&&I===2||Y*10>=i?re.SHIFT_JIS:re.ISO88591:s?re.ISO88591:a?re.SHIFT_JIS:l?re.UTF8:re.PLATFORM_DEFAULT_ENCODING}static format(e,...n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,k;switch(E){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}static getBytes(e,n){return ye.encode(e,n)}static getCharCode(e,n=0){return e.charCodeAt(n)}static getCharAt(e){return String.fromCharCode(e)}}re.SHIFT_JIS=S.SJIS.getName(),re.GB2312="GB2312",re.ISO88591=S.ISO8859_1.getName(),re.EUC_JP="EUC_JP",re.UTF8=S.UTF8.getName(),re.PLATFORM_DEFAULT_ENCODING=re.UTF8,re.ASSUME_SHIFT_JIS=!1;class xe{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+=re.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 Me{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 v("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 Me(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 v("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)===`
|
|
58
|
+
`||e.charAt(p)==="\r"){if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new v("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 v("illegal character encountered: "+e.substring(p));if(a>l){if(d===-1)d=a-l;else if(a-l!==d)throw new v("row lengths do not match");h++}const y=new Me(d,h);for(let E=0;E<a;E++)s[E]&&y.set(Math.floor(E%d),Math.floor(E/d));return y}get(e,n){const i=n*this.rowSize+Math.floor(e/32);return(this.bits[i]>>>(e&31)&1)!==0}set(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]|=1<<(e&31)&4294967295}unset(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]&=~(1<<(e&31)&4294967295)}flip(e,n){const i=n*this.rowSize+Math.floor(e/32);this.bits[i]^=1<<(e&31)&4294967295}xor(e){if(this.width!==e.getWidth()||this.height!==e.getHeight()||this.rowSize!==e.getRowSize())throw new v("input matrix dimensions do not match");const n=new Q(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 v("Left and top must be nonnegative");if(s<1||i<1)throw new v("Height and width must be at least 1");const a=e+i,l=n+s;if(l>this.height||a>this.width)throw new v("The region must fit inside the matrix");const d=this.rowSize,h=this.bits;for(let p=n;p<l;p++){const y=p*d;for(let E=e;E<a;E++)h[y+Math.floor(E/32)]|=1<<(E&31)&4294967295}}getRow(e,n){n==null||n.getSize()<this.width?n=new Q(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){D.arraycopy(n.getBitArray(),0,this.bits,e*this.rowSize,this.rowSize)}rotate180(){const e=this.getWidth(),n=this.getHeight();let i=new Q(e),s=new Q(e);for(let a=0,l=Math.floor((n+1)/2);a<l;a++)i=this.getRow(a,i),s=this.getRow(n-1-a,s),i.reverse(),s.reverse(),this.setRow(a,s),this.setRow(n-1-a,i)}getEnclosingRectangle(){const e=this.width,n=this.height,i=this.rowSize,s=this.bits;let a=e,l=n,d=-1,h=-1;for(let p=0;p<n;p++)for(let y=0;y<i;y++){const E=s[p*i+y];if(E!==0){if(p<l&&(l=p),p>h&&(h=p),y*32<a){let I=0;for(;(E<<31-I&4294967295)===0;)I++;y*32+I<a&&(a=y*32+I)}if(y*32+31>d){let I=31;for(;!(E>>>I);)I--;y*32+I>d&&(d=y*32+I)}}}return d<a||h<l?null:Int32Array.from([a,l,d-a+1,h-l+1])}getTopLeftOnBit(){const e=this.rowSize,n=this.bits;let i=0;for(;i<n.length&&n[i]===0;)i++;if(i===n.length)return null;const s=i/e;let a=i%e*32;const l=n[i];let d=0;for(;(l<<31-d&4294967295)===0;)d++;return a+=d,Int32Array.from([a,s])}getBottomRightOnBit(){const e=this.rowSize,n=this.bits;let i=n.length-1;for(;i>=0&&n[i]===0;)i--;if(i<0)return null;const s=Math.floor(i/e);let a=Math.floor(i%e)*32;const l=n[i];let d=31;for(;!(l>>>d);)d--;return a+=d,Int32Array.from([a,s])}getWidth(){return this.width}getHeight(){return this.height}getRowSize(){return this.rowSize}equals(e){if(!(e instanceof Me))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=`
|
|
59
|
+
`){return this.buildToString(e,n,i)}buildToString(e,n,i){let s=new xe;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 Me(this.width,this.height,this.rowSize,this.bits.slice())}}class $ extends x{static getNotFoundInstance(){return new $}}$.kind="NotFoundException";class ge extends M{constructor(e){super(e),this.luminances=ge.EMPTY,this.buckets=new Int32Array(ge.LUMINANCE_BUCKETS)}getBlackRow(e,n){const i=this.getLuminanceSource(),s=i.getWidth();n==null||n.getSize()<s?n=new Q(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)>>ge.LUMINANCE_SHIFT]++;const d=ge.estimateBlackPoint(l);if(s<3)for(let h=0;h<s;h++)(a[h]&255)<d&&n.set(h);else{let h=a[0]&255,p=a[1]&255;for(let y=1;y<s-1;y++){const E=a[y+1]&255;(p*4-h-E)/2<d&&n.set(y),h=p,p=E}}return n}getBlackMatrix(){const e=this.getLuminanceSource(),n=e.getWidth(),i=e.getHeight(),s=new Me(n,i);this.initArrays(n);const a=this.buckets;for(let h=1;h<5;h++){const p=Math.floor(i*h/5),y=e.getRow(p,this.luminances),E=Math.floor(n*4/5);for(let I=Math.floor(n/5);I<E;I++){const k=y[I]&255;a[k>>ge.LUMINANCE_SHIFT]++}}const l=ge.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 ge(e)}initArrays(e){this.luminances.length<e&&(this.luminances=new Uint8ClampedArray(e));const n=this.buckets;for(let i=0;i<ge.LUMINANCE_BUCKETS;i++)n[i]=0}static estimateBlackPoint(e){const n=e.length;let i=0,s=0,a=0;for(let y=0;y<n;y++)e[y]>a&&(s=y,a=e[y]),e[y]>i&&(i=e[y]);let l=0,d=0;for(let y=0;y<n;y++){const E=y-s,I=e[y]*E*E;I>d&&(l=y,d=I)}if(s>l){const y=s;s=l,l=y}if(l-s<=n/16)throw new $;let h=l-1,p=-1;for(let y=l-1;y>s;y--){const E=y-s,I=E*E*(l-y)*(i-e[y]);I>p&&(h=y,p=I)}return h<<ge.LUMINANCE_SHIFT}}ge.LUMINANCE_BITS=5,ge.LUMINANCE_SHIFT=8-ge.LUMINANCE_BITS,ge.LUMINANCE_BUCKETS=1<<ge.LUMINANCE_BITS,ge.EMPTY=Uint8ClampedArray.from([0]);class ne extends ge{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>=ne.MINIMUM_DIMENSION&&i>=ne.MINIMUM_DIMENSION){const s=e.getMatrix();let a=n>>ne.BLOCK_SIZE_POWER;(n&ne.BLOCK_SIZE_MASK)!==0&&a++;let l=i>>ne.BLOCK_SIZE_POWER;(i&ne.BLOCK_SIZE_MASK)!==0&&l++;const d=ne.calculateBlackPoints(s,a,l,n,i),h=new Me(n,i);ne.calculateThresholdForBlock(s,a,l,n,i,d,h),this.matrix=h}else this.matrix=super.getBlackMatrix();return this.matrix}createBinarizer(e){return new ne(e)}static calculateThresholdForBlock(e,n,i,s,a,l,d){const h=a-ne.BLOCK_SIZE,p=s-ne.BLOCK_SIZE;for(let y=0;y<i;y++){let E=y<<ne.BLOCK_SIZE_POWER;E>h&&(E=h);const I=ne.cap(y,2,i-3);for(let k=0;k<n;k++){let L=k<<ne.BLOCK_SIZE_POWER;L>p&&(L=p);const F=ne.cap(k,2,n-3);let H=0;for(let le=-2;le<=2;le++){const ce=l[I+le];H+=ce[F-2]+ce[F-1]+ce[F]+ce[F+1]+ce[F+2]}const Y=H/25;ne.thresholdBlock(e,L,E,Y,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<ne.BLOCK_SIZE;d++,h+=a)for(let p=0;p<ne.BLOCK_SIZE;p++)(e[h+p]&255)<=s&&l.set(n+p,i+d)}static calculateBlackPoints(e,n,i,s,a){const l=a-ne.BLOCK_SIZE,d=s-ne.BLOCK_SIZE,h=new Array(i);for(let p=0;p<i;p++){h[p]=new Int32Array(n);let y=p<<ne.BLOCK_SIZE_POWER;y>l&&(y=l);for(let E=0;E<n;E++){let I=E<<ne.BLOCK_SIZE_POWER;I>d&&(I=d);let k=0,L=255,F=0;for(let Y=0,le=y*s+I;Y<ne.BLOCK_SIZE;Y++,le+=s){for(let ce=0;ce<ne.BLOCK_SIZE;ce++){const ae=e[le+ce]&255;k+=ae,ae<L&&(L=ae),ae>F&&(F=ae)}if(F-L>ne.MIN_DYNAMIC_RANGE)for(Y++,le+=s;Y<ne.BLOCK_SIZE;Y++,le+=s)for(let ce=0;ce<ne.BLOCK_SIZE;ce++)k+=e[le+ce]&255}let H=k>>ne.BLOCK_SIZE_POWER*2;if(F-L<=ne.MIN_DYNAMIC_RANGE&&(H=L/2,p>0&&E>0)){const Y=(h[p-1][E]+2*h[p][E-1]+h[p-1][E-1])/4;L<Y&&(H=Y)}h[p][E]=H}}return h}}ne.BLOCK_SIZE_POWER=3,ne.BLOCK_SIZE=1<<ne.BLOCK_SIZE_POWER,ne.BLOCK_SIZE_MASK=ne.BLOCK_SIZE-1,ne.MINIMUM_DIMENSION=ne.BLOCK_SIZE*5,ne.MIN_DYNAMIC_RANGE=24;class J{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 Te("This luminance source does not support cropping.")}isRotateSupported(){return!1}rotateCounterClockwise(){throw new Te("This luminance source does not support rotation by 90 degrees.")}rotateCounterClockwise45(){throw new Te("This luminance source does not support rotation by 45 degrees.")}toString(){const e=new Uint8ClampedArray(this.width);let n=new xe;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(`
|
|
60
|
+
`)}return n.toString()}}class me extends J{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 me(this.delegate.crop(e,n,i,s))}isRotateSupported(){return this.delegate.isRotateSupported()}invert(){return this.delegate}rotateCounterClockwise(){return new me(this.delegate.rotateCounterClockwise())}rotateCounterClockwise45(){return new me(this.delegate.rotateCounterClockwise45())}}class fe extends J{constructor(e){super(e.width,e.height),this.canvas=e,this.tempCanvasElement=null,this.buffer=fe.makeBufferFromCanvasImageData(e)}static makeBufferFromCanvasImageData(e){const n=e.getContext("2d").getImageData(0,0,e.width,e.height);return fe.toGrayscaleBuffer(n.data,e.width,e.height)}static toGrayscaleBuffer(e,n,i){const s=new Uint8ClampedArray(n*i);for(let a=0,l=0,d=e.length;a<d;a+=4,l++){let h;if(e[a+3]===0)h=255;else{const y=e[a],E=e[a+1],I=e[a+2];h=306*y+601*E+117*I+512>>10}s[l]=h}return s}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("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*fe.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=fe.makeBufferFromCanvasImageData(n),this}invert(){return new me(this)}}fe.DEGREE_TO_RADIANS=Math.PI/180;class ie{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 pe=(globalThis||Ei||self||window||void 0)&&(globalThis||Ei||self||window||void 0).__awaiter||function(b,e,n,i){function s(a){return a instanceof n?a:new n(function(l){l(a)})}return new(n||(n=Promise))(function(a,l){function d(y){try{p(i.next(y))}catch(E){l(E)}}function h(y){try{p(i.throw(y))}catch(E){l(E)}}function p(y){y.done?a(y.value):s(y.value).then(d,h)}p((i=i.apply(b,e||[])).next())})};class vt{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 pe(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 pe(this,void 0,void 0,function*(){return(yield this.listVideoInputDevices()).map(n=>new ie(n.deviceId,n.label))})}findDeviceById(e){return pe(this,void 0,void 0,function*(){const n=yield this.listVideoInputDevices();return n?n.find(i=>i.deviceId===e):null})}decodeFromInputVideoDevice(e,n){return pe(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(e,n)})}decodeOnceFromVideoDevice(e,n){return pe(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 pe(this,void 0,void 0,function*(){const i=yield navigator.mediaDevices.getUserMedia(e);return yield this.decodeOnceFromStream(i,n)})}decodeOnceFromStream(e,n){return pe(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 pe(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(e,n,i)})}decodeFromVideoDevice(e,n,i){return pe(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 pe(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 pe(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 pe(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 pe(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 A(`element with id '${e}' not found`);if(i.nodeName.toLowerCase()!==n.toLowerCase())throw new A(`element with id '${e}' must be an ${n} element`);return i}decodeFromImage(e,n){if(!e&&!n)throw new A("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 A("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 A("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 A("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 A("A video element must be provided.");this.reset();const n=this.prepareVideoElement(e);return this.videoElement=n,n}decodeFromImageUrl(e){if(!e)throw new A("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 A("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 A("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 pe(this,void 0,void 0,function*(){return yield this.playVideoOnLoadAsync(e),yield this.decodeOnce(e)})}_decodeOnLoadVideoContinuously(e,n){return pe(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 $("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 $,y=(d instanceof O||d instanceof z)&&i;if(h||y)return setTimeout(s,this._timeBetweenDecodingAttempts,a,l);l(d)}};return new Promise((a,l)=>s(a,l))}decodeContinuously(e,n){this._stopContinuousDecode=!1;const i=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=void 0;return}try{const s=this.decode(e);n(s,null),setTimeout(i,this.timeBetweenScansMillis)}catch(s){n(null,s);const a=s instanceof O||s instanceof z,l=s instanceof $;(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 fe(n),s=new ne(i);return new P(s)}getCaptureCanvasContext(e){if(!this.captureCanvasContext){const i=this.getCaptureCanvas(e).getContext("2d");this.captureCanvasContext=i}return this.captureCanvasContext}getCaptureCanvas(e){if(!this.captureCanvas){const n=this.createCaptureCanvas(e);this.captureCanvas=n}return this.captureCanvas}decodeBitmap(e){return this.reader.decode(e,this._hints)}createCaptureCanvas(e){if(typeof document>"u")return this._destroyCaptureCanvas(),null;const n=document.createElement("canvas");let i,s;return typeof e<"u"&&(e instanceof HTMLVideoElement?(i=e.videoWidth,s=e.videoHeight):e instanceof HTMLImageElement&&(i=e.naturalWidth||e.width,s=e.naturalHeight||e.height)),n.style.width=i+"px",n.style.height=s+"px",n.width=i,n.height=s,n}stopStreams(){this.stream&&(this.stream.getVideoTracks().forEach(e=>e.stop()),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()}reset(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()}_destroyVideoElement(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)}_destroyImageElement(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)}_destroyCaptureCanvas(){this.captureCanvasContext=void 0,this.captureCanvas=void 0}addVideoSource(e,n){try{e.srcObject=n}catch{e.src=URL.createObjectURL(n)}}cleanVideoSource(e){try{e.srcObject=null}catch{e.src=""}this.videoElement.removeAttribute("src")}}class Ee{constructor(e,n,i=n==null?0:8*n.length,s,a,l=D.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=D.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);D.arraycopy(n,0,i,0,n.length),D.arraycopy(e,0,i,n.length,e.length),this.resultPoints=i}}getTimestamp(){return this.timestamp}toString(){return this.text}}var Tt;(function(b){b[b.AZTEC=0]="AZTEC",b[b.CODABAR=1]="CODABAR",b[b.CODE_39=2]="CODE_39",b[b.CODE_93=3]="CODE_93",b[b.CODE_128=4]="CODE_128",b[b.DATA_MATRIX=5]="DATA_MATRIX",b[b.EAN_8=6]="EAN_8",b[b.EAN_13=7]="EAN_13",b[b.ITF=8]="ITF",b[b.MAXICODE=9]="MAXICODE",b[b.PDF_417=10]="PDF_417",b[b.QR_CODE=11]="QR_CODE",b[b.RSS_14=12]="RSS_14",b[b.RSS_EXPANDED=13]="RSS_EXPANDED",b[b.UPC_A=14]="UPC_A",b[b.UPC_E=15]="UPC_E",b[b.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION"})(Tt||(Tt={}));var Ce=Tt,sn;(function(b){b[b.OTHER=0]="OTHER",b[b.ORIENTATION=1]="ORIENTATION",b[b.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",b[b.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",b[b.ISSUE_NUMBER=4]="ISSUE_NUMBER",b[b.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",b[b.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",b[b.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",b[b.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",b[b.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",b[b.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY"})(sn||(sn={}));var Ue=sn;class Ht{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 de{exp(e){return this.expTable[e]}log(e){if(e===0)throw new v;return this.logTable[e]}static addOrSubtract(e,n){return e^n}}class Oe{constructor(e,n){if(n.length===0)throw new v;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),D.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=de.addOrSubtract(i,h)}return i}i=n[0];const s=n.length,a=this.field;for(let l=1;l<s;l++)i=de.addOrSubtract(a.multiply(e,i),n[l]);return i}addOrSubtract(e){if(!this.field.equals(e.field))throw new v("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;D.arraycopy(i,0,s,0,a);for(let l=a;l<i.length;l++)s[l]=de.addOrSubtract(n[l-a],i[l]);return new Oe(this.field,s)}multiply(e){if(!this.field.equals(e.field))throw new v("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]=de.addOrSubtract(l[h+y],d.multiply(p,s[y]))}return new Oe(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 Oe(i,s)}multiplyByMonomial(e,n){if(e<0)throw new v;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 Oe(l,a)}divide(e){if(!this.field.equals(e.field))throw new v("GenericGFPolys do not have same GenericGF field");if(e.isZero())throw new v("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 yt extends x{}yt.kind="ArithmeticException";class be extends de{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 Oe(this,Int32Array.from([0])),this.one=new Oe(this,Int32Array.from([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new v;if(n===0)return this.zero;const i=new Int32Array(e+1);return i[0]=n,new Oe(this,i)}inverse(e){if(e===0)throw new yt;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"+U.toHexString(this.primitive)+","+this.size+")"}equals(e){return e===this}}be.AZTEC_DATA_12=new be(4201,4096,1),be.AZTEC_DATA_10=new be(1033,1024,1),be.AZTEC_DATA_6=new be(67,64,1),be.AZTEC_PARAM=new be(19,16,1),be.QR_CODE_FIELD_256=new be(285,256,0),be.DATA_MATRIX_FIELD_256=new be(301,256,1),be.AZTEC_DATA_8=be.DATA_MATRIX_FIELD_256,be.MAXICODE_FIELD_64=be.AZTEC_DATA_6;class Xt extends x{}Xt.kind="ReedSolomonException";class Wt extends x{}Wt.kind="IllegalStateException";class In{constructor(e){this.field=e}decode(e,n){const i=this.field,s=new Oe(i,e),a=new Int32Array(n);let l=!0;for(let k=0;k<n;k++){const L=s.evaluateAt(i.exp(k+i.getGeneratorBase()));a[a.length-1-k]=L,L!==0&&(l=!1)}if(l)return;const d=new Oe(i,a),h=this.runEuclideanAlgorithm(i.buildMonomial(n,1),d,n),p=h[0],y=h[1],E=this.findErrorLocations(p),I=this.findErrorMagnitudes(y,E);for(let k=0;k<E.length;k++){const L=e.length-1-i.log(E[k]);if(L<0)throw new Xt("Bad error location");e[L]=be.addOrSubtract(e[L],I[k])}}runEuclideanAlgorithm(e,n,i){if(e.getDegree()<n.getDegree()){const k=e;e=n,n=k}const s=this.field;let a=e,l=n,d=s.getZero(),h=s.getOne();for(;l.getDegree()>=(i/2|0);){let k=a,L=d;if(a=l,d=h,a.isZero())throw new Xt("r_{i-1} was zero");l=k;let F=s.getZero();const H=a.getCoefficient(a.getDegree()),Y=s.inverse(H);for(;l.getDegree()>=a.getDegree()&&!l.isZero();){const le=l.getDegree()-a.getDegree(),ce=s.multiply(l.getCoefficient(l.getDegree()),Y);F=F.addOrSubtract(s.buildMonomial(le,ce)),l=l.addOrSubtract(a.multiplyByMonomial(le,ce))}if(h=F.multiply(d).addOrSubtract(L),l.getDegree()>=a.getDegree())throw new Wt("Division algorithm failed to reduce polynomial?")}const p=h.getCoefficient(0);if(p===0)throw new Xt("sigmaTilde(0) was zero");const y=s.inverse(p),E=h.multiplyScalar(y),I=l.multiplyScalar(y);return[E,I]}findErrorLocations(e){const n=e.getDegree();if(n===1)return Int32Array.from([e.getCoefficient(1)]);const i=new Int32Array(n);let s=0;const a=this.field;for(let l=1;l<a.getSize()&&s<n;l++)e.evaluateAt(l)===0&&(i[s]=a.inverse(l),s++);if(s!==n)throw new Xt("Error locator degree does not match number of roots");return i}findErrorMagnitudes(e,n){const i=n.length,s=new Int32Array(i),a=this.field;for(let l=0;l<i;l++){const d=a.inverse(n[l]);let h=1;for(let p=0;p<i;p++)if(l!==p){const y=a.multiply(n[p],d),E=(y&1)===0?y|1:y&-2;h=a.multiply(h,E)}s[l]=a.multiply(e.evaluateAt(d),a.inverse(h)),a.getGeneratorBase()!==0&&(s[l]=a.multiply(s[l],d))}return s}}var Ct;(function(b){b[b.UPPER=0]="UPPER",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.DIGIT=3]="DIGIT",b[b.PUNCT=4]="PUNCT",b[b.BINARY=5]="BINARY"})(Ct||(Ct={}));class Xe{decode(e){this.ddata=e;let n=e.getBits(),i=this.extractBits(n),s=this.correctBits(i),a=Xe.convertBoolArrayToByteArray(s),l=Xe.getEncodedData(s),d=new Ht(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=Ct.UPPER,s=Ct.UPPER,a="",l=0;for(;l<n;)if(s===Ct.BINARY){if(n-l<5)break;let d=Xe.readCode(e,l,5);if(l+=5,d===0){if(n-l<11)break;d=Xe.readCode(e,l,11)+31,l+=11}for(let h=0;h<d;h++){if(n-l<8){l=n;break}const p=Xe.readCode(e,l,8);a+=re.castAsNonUtf8Char(p),l+=8}s=i}else{let d=s===Ct.DIGIT?4:5;if(n-l<d)break;let h=Xe.readCode(e,l,d);l+=d;let p=Xe.getCharacter(s,h);p.startsWith("CTRL_")?(i=s,s=Xe.getTable(p.charAt(5)),p.charAt(6)==="L"&&(i=s)):(a+=p,s=i)}return a}static getTable(e){switch(e){case"L":return Ct.LOWER;case"P":return Ct.PUNCT;case"M":return Ct.MIXED;case"D":return Ct.DIGIT;case"B":return Ct.BINARY;case"U":default:return Ct.UPPER}}static getCharacter(e,n){switch(e){case Ct.UPPER:return Xe.UPPER_TABLE[n];case Ct.LOWER:return Xe.LOWER_TABLE[n];case Ct.MIXED:return Xe.MIXED_TABLE[n];case Ct.PUNCT:return Xe.PUNCT_TABLE[n];case Ct.DIGIT:return Xe.DIGIT_TABLE[n];default:throw new Wt("Bad table")}}correctBits(e){let n,i;this.ddata.getNbLayers()<=2?(i=6,n=be.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(i=8,n=be.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(i=10,n=be.AZTEC_DATA_10):(i=12,n=be.AZTEC_DATA_12);let s=this.ddata.getNbDatablocks(),a=e.length/i;if(a<s)throw new z;let l=e.length%i,d=new Int32Array(a);for(let I=0;I<a;I++,l+=i)d[I]=Xe.readCode(e,l,i);try{new In(n).decode(d,a-s)}catch(I){throw new z(I)}let h=(1<<i)-1,p=0;for(let I=0;I<s;I++){let k=d[I];if(k===0||k===h)throw new z;(k===1||k===h-1)&&p++}let y=new Array(s*i-p),E=0;for(let I=0;I<s;I++){let k=d[I];if(k===1||k===h-1)y.fill(k>1,E,E+i-1),E+=i-1;else for(let L=i-1;L>=0;--L)y[E++]=(k&1<<L)!==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*U.truncDivision(U.truncDivision(s,2)-1,15),h=s/2,p=U.truncDivision(d,2);for(let y=0;y<h;y++){let E=y+U.truncDivision(y,15);a[h-y-1]=p-E-1,a[h+y]=p+E+1}}for(let d=0,h=0;d<i;d++){let p=(i-d)*4+(n?9:12),y=d*2,E=s-1-y;for(let I=0;I<p;I++){let k=I*2;for(let L=0;L<2;L++)l[h+k+L]=e.get(a[y+L],a[y+I]),l[h+2*p+k+L]=e.get(a[y+I],a[E-L]),l[h+4*p+k+L]=e.get(a[E-L],a[E-I]),l[h+6*p+k+L]=e.get(a[E-I],a[y+L])}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?Xe.readCode(e,n,8):Xe.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]=Xe.readByte(e,8*i);return n}totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Xe.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"],Xe.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"],Xe.MIXED_TABLE=["CTRL_PS"," ","\\1","\\2","\\3","\\4","\\5","\\6","\\7","\b"," ",`
|
|
61
|
+
`,"\\13","\f","\r","\\33","\\34","\\35","\\36","\\37","@","\\","^","_","`","|","~","\\177","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],Xe.PUNCT_TABLE=["","\r",`\r
|
|
62
|
+
`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],Xe.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"];class Ze{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 Sn{static floatToIntBits(e){return e}}Sn.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ve{constructor(e,n){this.x=e,this.y=n}getX(){return this.x}getY(){return this.y}equals(e){if(e instanceof ve){const n=e;return this.x===n.x&&this.y===n.y}return!1}hashCode(){return 31*Sn.floatToIntBits(this.x)+Sn.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 Ze.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 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,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 Jt{constructor(e,n,i,s){this.image=e,this.height=e.getHeight(),this.width=e.getWidth(),n==null&&(n=Jt.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 $}detect(){let e=this.leftInit,n=this.rightInit,i=this.upInit,s=this.downInit,a=!1,l=!0,d=!1,h=!1,p=!1,y=!1,E=!1;const I=this.width,k=this.height;for(;l;){l=!1;let L=!0;for(;(L||!h)&&n<I;)L=this.containsBlackPoint(i,s,n,!1),L?(n++,l=!0,h=!0):h||n++;if(n>=I){a=!0;break}let F=!0;for(;(F||!p)&&s<k;)F=this.containsBlackPoint(e,n,s,!0),F?(s++,l=!0,p=!0):p||s++;if(s>=k){a=!0;break}let H=!0;for(;(H||!y)&&e>=0;)H=this.containsBlackPoint(i,s,e,!1),H?(e--,l=!0,y=!0):y||e--;if(e<0){a=!0;break}let Y=!0;for(;(Y||!E)&&i>=0;)Y=this.containsBlackPoint(e,n,i,!0),Y?(i--,l=!0,E=!0):E||i--;if(i<0){a=!0;break}l&&(d=!0)}if(!a&&d){const L=n-e;let F=null;for(let ce=1;F===null&&ce<L;ce++)F=this.getBlackPointOnSegment(e,s-ce,e+ce,s);if(F==null)throw new $;let H=null;for(let ce=1;H===null&&ce<L;ce++)H=this.getBlackPointOnSegment(e,i+ce,e+ce,i);if(H==null)throw new $;let Y=null;for(let ce=1;Y===null&&ce<L;ce++)Y=this.getBlackPointOnSegment(n,i+ce,n-ce,i);if(Y==null)throw new $;let le=null;for(let ce=1;le===null&&ce<L;ce++)le=this.getBlackPointOnSegment(n,s-ce,n-ce,s);if(le==null)throw new $;return this.centerEdges(le,F,Y,H)}else throw new $}getBlackPointOnSegment(e,n,i,s){const a=Ze.round(Ze.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=Ze.round(e+p*l),E=Ze.round(n+p*d);if(h.get(y,E))return new ve(y,E)}return null}centerEdges(e,n,i,s){const a=e.getX(),l=e.getY(),d=n.getX(),h=n.getY(),p=i.getX(),y=i.getY(),E=s.getX(),I=s.getY(),k=Jt.CORR;return a<this.width/2?[new ve(E-k,I+k),new ve(d+k,h+k),new ve(p-k,y-k),new ve(a+k,l-k)]:[new ve(E+k,I+k),new ve(d+k,h-k),new ve(p-k,y+k),new ve(a-k,l-k)]}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}}Jt.INIT_SIZE=10,Jt.CORR=1;class Hn{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 $;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 $;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 Bt{constructor(e,n,i,s,a,l,d,h,p){this.a11=e,this.a21=n,this.a31=i,this.a12=s,this.a22=a,this.a32=l,this.a13=d,this.a23=h,this.a33=p}static quadrilateralToQuadrilateral(e,n,i,s,a,l,d,h,p,y,E,I,k,L,F,H){const Y=Bt.quadrilateralToSquare(e,n,i,s,a,l,d,h);return Bt.squareToQuadrilateral(p,y,E,I,k,L,F,H).times(Y)}transformPoints(e){const n=e.length,i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33;for(let I=0;I<n;I+=2){const k=e[I],L=e[I+1],F=a*k+h*L+E;e[I]=(i*k+l*L+p)/F,e[I+1]=(s*k+d*L+y)/F}}transformPointsWithValues(e,n){const i=this.a11,s=this.a12,a=this.a13,l=this.a21,d=this.a22,h=this.a23,p=this.a31,y=this.a32,E=this.a33,I=e.length;for(let k=0;k<I;k++){const L=e[k],F=n[k],H=a*L+h*F+E;e[k]=(i*L+l*F+p)/H,n[k]=(s*L+d*F+y)/H}}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 Bt(i-e,a-i,e,s-n,l-s,n,0,0,1);{const E=i-a,I=d-a,k=s-l,L=h-l,F=E*L-I*k,H=(p*L-I*y)/F,Y=(E*y-p*k)/F;return new Bt(i-e+H*i,d-e+Y*d,e,s-n+H*s,h-n+Y*h,n,H,Y,1)}}static quadrilateralToSquare(e,n,i,s,a,l,d,h){return Bt.squareToQuadrilateral(e,n,i,s,a,l,d,h).buildAdjoint()}buildAdjoint(){return new Bt(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 Bt(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 Hn{sampleGrid(e,n,i,s,a,l,d,h,p,y,E,I,k,L,F,H,Y,le,ce){const ae=Bt.quadrilateralToQuadrilateral(s,a,l,d,h,p,y,E,I,k,L,F,H,Y,le,ce);return this.sampleGridWithTransform(e,n,i,ae)}sampleGridWithTransform(e,n,i,s){if(n<=0||i<=0)throw new $;const a=new Me(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),Hn.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 $}}return a}}class R{static setGridSampler(e){R.gridSampler=e}static getInstance(){return R.gridSampler}}R.gridSampler=new rr;class oe{constructor(e,n){this.x=e,this.y=n}toResultPoint(){return new ve(this.getX(),this.getY())}getX(){return this.x}getY(){return this.y}}class qe{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 $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 $;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(U.bitCount(i^this.EXPECTED_CORNER_BITS[s])<=2)return s;throw new $}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 In(be.AZTEC_PARAM).decode(l,a)}catch{throw new $}let d=0;for(let h=0;h<s;h++)d=(d<<4)+l[h];return d}getBullsEyeCorners(e){let n=e,i=e,s=e,a=e,l=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let E=this.getFirstDifferent(n,l,1,-1),I=this.getFirstDifferent(i,l,1,1),k=this.getFirstDifferent(s,l,-1,1),L=this.getFirstDifferent(a,l,-1,-1);if(this.nbCenterLayers>2){let F=this.distancePoint(L,E)*this.nbCenterLayers/(this.distancePoint(a,n)*(this.nbCenterLayers+2));if(F<.75||F>1.25||!this.isWhiteOrBlackRectangle(E,I,k,L))break}n=E,i=I,s=k,a=L,l=!l}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new $;this.compact=this.nbCenterLayers===5;let d=new ve(n.getX()+.5,n.getY()-.5),h=new ve(i.getX()+.5,i.getY()+.5),p=new ve(s.getX()-.5,s.getY()+.5),y=new ve(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 Jt(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 oe(h+7,p-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new oe(h+7,p+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new oe(h-7,p+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new oe(h-7,p-7),!1,-1,-1).toResultPoint()}let a=Ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=Ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4);try{let d=new Jt(this.image,15,a,l).detect();e=d[0],n=d[1],i=d[2],s=d[3]}catch{e=this.getFirstDifferent(new oe(a+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new oe(a+7,l+7),!1,1,1).toResultPoint(),i=this.getFirstDifferent(new oe(a-7,l+7),!1,-1,1).toResultPoint(),s=this.getFirstDifferent(new oe(a-7,l-7),!1,-1,-1).toResultPoint()}return a=Ze.round((e.getX()+s.getX()+n.getX()+i.getX())/4),l=Ze.round((e.getY()+s.getY()+n.getY()+i.getY())/4),new oe(a,l)}getMatrixCornerPoints(e){return this.expandSquare(e,2*this.nbCenterLayers,this.getDimension())}sampleGrid(e,n,i,s,a){let l=R.getInstance(),d=this.getDimension(),h=d/2-this.nbCenterLayers,p=d/2+this.nbCenterLayers;return l.sampleGrid(e,d,d,h,h,p,h,p,p,h,p,n.getX(),n.getY(),i.getX(),i.getY(),s.getX(),s.getY(),a.getX(),a.getY())}sampleLine(e,n,i){let s=0,a=this.distanceResultPoint(e,n),l=a/i,d=e.getX(),h=e.getY(),p=l*(n.getX()-e.getX())/a,y=l*(n.getY()-e.getY())/a;for(let E=0;E<i;E++)this.image.get(Ze.round(d+E*p),Ze.round(h+E*y))&&(s|=1<<i-E-1);return s}isWhiteOrBlackRectangle(e,n,i,s){let a=3;e=new oe(e.getX()-a,e.getY()+a),n=new oe(n.getX()-a,n.getY()-a),i=new oe(i.getX()+a,i.getY()-a),s=new oe(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(Ze.round(d),Ze.round(h))!==p&&l++;let E=l/i;return E>.1&&E<.9?0:E<=.1===p?1:-1}getFirstDifferent(e,n,i,s){let a=e.getX()+i,l=e.getY()+s;for(;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i,l+=s;for(a-=i,l-=s;this.isValid(a,l)&&this.image.get(a,l)===n;)a+=i;for(a-=i;this.isValid(a,l)&&this.image.get(a,l)===n;)l+=s;return l-=s,new oe(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 ve(d+s*a,h+s*l),y=new ve(d-s*a,h-s*l);a=e[1].getX()-e[3].getX(),l=e[1].getY()-e[3].getY(),d=(e[1].getX()+e[3].getX())/2,h=(e[1].getY()+e[3].getY())/2;let E=new ve(d+s*a,h+s*l),I=new ve(d-s*a,h-s*l);return[p,E,y,I]}isValid(e,n){return e>=0&&e<this.image.getWidth()&&n>0&&n<this.image.getHeight()}isValidPoint(e){let n=Ze.round(e.getX()),i=Ze.round(e.getY());return this.isValid(n,i)}distancePoint(e,n){return Ze.distance(e.getX(),e.getY(),n.getX(),n.getY())}distanceResultPoint(e,n){return Ze.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*(U.truncDivision(this.nbLayers-4,8)+1)+15}}class lt{decode(e,n=null){let i=null,s=new qe(e.getBlackMatrix()),a=null,l=null;try{let y=s.detectMirror(!1);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Xe().decode(y)}catch(y){i=y}if(l==null)try{let y=s.detectMirror(!0);a=y.getPoints(),this.reportFoundResultPoints(n,a),l=new Xe().decode(y)}catch(y){throw i??y}let d=new Ee(l.getText(),l.getRawBytes(),l.getNumBits(),a,Ce.AZTEC,D.currentTimeMillis()),h=l.getByteSegments();h!=null&&d.putMetadata(Ue.BYTE_SEGMENTS,h);let p=l.getECLevel();return p!=null&&d.putMetadata(Ue.ERROR_CORRECTION_LEVEL,p),d}reportFoundResultPoints(e,n){if(e!=null){let i=e.get(V.NEED_RESULT_POINT_CALLBACK);i!=null&&n.forEach((s,a,l)=>{i.foundPossibleResultPoint(s)})}}reset(){}}class xr extends vt{constructor(e=500){super(new lt,e)}}class bt{decode(e,n){try{return this.doDecode(e,n)}catch{if(n&&n.get(V.TRY_HARDER)===!0&&e.isRotateSupported()){const a=e.rotateCounterClockwise(),l=this.doDecode(a,n),d=l.getResultMetadata();let h=270;d!==null&&d.get(Ue.ORIENTATION)===!0&&(h=h+d.get(Ue.ORIENTATION)%360),l.putMetadata(Ue.ORIENTATION,h);const p=l.getResultPoints();if(p!==null){const y=a.getHeight();for(let E=0;E<p.length;E++)p[E]=new ve(y-p[E].getY()-1,p[E].getX())}return l}else throw new $}}reset(){}doDecode(e,n){const i=e.getWidth(),s=e.getHeight();let a=new Q(i);const l=n&&n.get(V.TRY_HARDER)===!0,d=Math.max(1,s>>(l?8:5));let h;l?h=s:h=15;const p=Math.trunc(s/2);for(let y=0;y<h;y++){const E=Math.trunc((y+1)/2),I=(y&1)===0,k=p+d*(I?E:-E);if(k<0||k>=s)break;try{a=e.getBlackRow(k,a)}catch{continue}for(let L=0;L<2;L++){if(L===1&&(a.reverse(),n&&n.get(V.NEED_RESULT_POINT_CALLBACK)===!0)){const F=new Map;n.forEach((H,Y)=>F.set(Y,H)),F.delete(V.NEED_RESULT_POINT_CALLBACK),n=F}try{const F=this.decodeRow(k,a,n);if(L===1){F.putMetadata(Ue.ORIENTATION,180);const H=F.getResultPoints();H!==null&&(H[0]=new ve(i-H[0].getX()-1,H[0].getY()),H[1]=new ve(i-H[1].getX()-1,H[1].getY()))}return F}catch{}}}throw new $}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 $;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 $}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 $;bt.recordPattern(e,n+1,i)}static patternMatchVariance(e,n,i){const s=e.length;let a=0,l=0;for(let p=0;p<s;p++)a+=e[p],l+=n[p];if(a<l)return Number.POSITIVE_INFINITY;const d=a/l;i*=d;let h=0;for(let p=0;p<s;p++){const y=e[p],E=n[p]*d,I=y>E?y-E:E-y;if(I>i)return Number.POSITIVE_INFINITY;h+=I}return h/a}}class he extends bt{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=he.MAX_AVG_VARIANCE,E=-1;for(let I=he.CODE_START_A;I<=he.CODE_START_C;I++){const k=bt.patternMatchVariance(a,he.CODE_PATTERNS[I],he.MAX_INDIVIDUAL_VARIANCE);k<y&&(y=k,E=I)}if(E>=0&&e.isRange(Math.max(0,l-(p-l)/2),l,!1))return Int32Array.from([l,p,E]);l+=a[0]+a[1],a=a.slice(2,a.length-1),a[s-1]=0,a[s]=0,s--}else s++;a[s]=1,d=!d}throw new $}static decodeCode(e,n,i){bt.recordPattern(e,i,n);let s=he.MAX_AVG_VARIANCE,a=-1;for(let l=0;l<he.CODE_PATTERNS.length;l++){const d=he.CODE_PATTERNS[l],h=this.patternMatchVariance(n,d,he.MAX_INDIVIDUAL_VARIANCE);h<s&&(s=h,a=l)}if(a>=0)return a;throw new $}decodeRow(e,n,i){const s=i&&i.get(V.ASSUME_GS1)===!0,a=he.findStartPattern(n),l=a[2];let d=0;const h=new Uint8Array(20);h[d++]=l;let p;switch(l){case he.CODE_START_A:p=he.CODE_CODE_A;break;case he.CODE_START_B:p=he.CODE_CODE_B;break;case he.CODE_START_C:p=he.CODE_CODE_C;break;default:throw new z}let y=!1,E=!1,I="",k=a[0],L=a[1];const F=Int32Array.from([0,0,0,0,0,0]);let H=0,Y=0,le=l,ce=0,ae=!0,We=!1,Fe=!1;for(;!y;){const Ir=E;switch(E=!1,H=Y,Y=he.decodeCode(n,F,L),h[d++]=Y,Y!==he.CODE_STOP&&(ae=!0),Y!==he.CODE_STOP&&(ce++,le+=ce*Y),k=L,L+=F.reduce((ud,dd)=>ud+dd,0),Y){case he.CODE_START_A:case he.CODE_START_B:case he.CODE_START_C:throw new z}switch(p){case he.CODE_CODE_A:if(Y<64)Fe===We?I+=String.fromCharCode(32+Y):I+=String.fromCharCode(32+Y+128),Fe=!1;else if(Y<96)Fe===We?I+=String.fromCharCode(Y-64):I+=String.fromCharCode(Y+64),Fe=!1;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_FNC_2:case he.CODE_FNC_3:break;case he.CODE_FNC_4_A:!We&&Fe?(We=!0,Fe=!1):We&&Fe?(We=!1,Fe=!1):Fe=!0;break;case he.CODE_SHIFT:E=!0,p=he.CODE_CODE_B;break;case he.CODE_CODE_B:p=he.CODE_CODE_B;break;case he.CODE_CODE_C:p=he.CODE_CODE_C;break;case he.CODE_STOP:y=!0;break}break;case he.CODE_CODE_B:if(Y<96)Fe===We?I+=String.fromCharCode(32+Y):I+=String.fromCharCode(32+Y+128),Fe=!1;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_FNC_2:case he.CODE_FNC_3:break;case he.CODE_FNC_4_B:!We&&Fe?(We=!0,Fe=!1):We&&Fe?(We=!1,Fe=!1):Fe=!0;break;case he.CODE_SHIFT:E=!0,p=he.CODE_CODE_A;break;case he.CODE_CODE_A:p=he.CODE_CODE_A;break;case he.CODE_CODE_C:p=he.CODE_CODE_C;break;case he.CODE_STOP:y=!0;break}break;case he.CODE_CODE_C:if(Y<100)Y<10&&(I+="0"),I+=Y;else switch(Y!==he.CODE_STOP&&(ae=!1),Y){case he.CODE_FNC_1:s&&(I.length===0?I+="]C1":I+="");break;case he.CODE_CODE_A:p=he.CODE_CODE_A;break;case he.CODE_CODE_B:p=he.CODE_CODE_B;break;case he.CODE_STOP:y=!0;break}break}Ir&&(p=p===he.CODE_CODE_A?he.CODE_CODE_B:he.CODE_CODE_A)}const nn=L-k;if(L=n.getNextUnset(L),!n.isRange(L,Math.min(n.getSize(),L+(L-k)/2),!1))throw new $;if(le-=ce*H,le%103!==H)throw new O;const yn=I.length;if(yn===0)throw new $;yn>0&&ae&&(p===he.CODE_CODE_C?I=I.substring(0,yn-2):I=I.substring(0,yn-1));const rn=(a[1]+a[0])/2,st=k+nn/2,$t=h.length,an=new Uint8Array($t);for(let Ir=0;Ir<$t;Ir++)an[Ir]=h[Ir];const Ar=[new ve(rn,e),new ve(st,e)];return new Ee(I,an,0,Ar,Ce.CODE_128,new Date().getTime())}}he.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])],he.MAX_AVG_VARIANCE=.25,he.MAX_INDIVIDUAL_VARIANCE=.7,he.CODE_SHIFT=98,he.CODE_CODE_C=99,he.CODE_CODE_B=100,he.CODE_CODE_A=101,he.CODE_FNC_1=102,he.CODE_FNC_2=97,he.CODE_FNC_3=96,he.CODE_FNC_4_A=101,he.CODE_FNC_4_B=100,he.CODE_START_A=103,he.CODE_START_B=104,he.CODE_START_C=105,he.CODE_STOP=106;class Nt extends bt{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=Nt.findAsteriskPattern(n,s),l=n.getNextSet(a[1]),d=n.getSize(),h,p;do{Nt.recordPattern(n,l,s);let F=Nt.toNarrowWidePattern(s);if(F<0)throw new $;h=Nt.patternToChar(F),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 F of s)y+=F;let E=l-p-y;if(l!==d&&E*2<y)throw new $;if(this.usingCheckDigit){let F=this.decodeRowResult.length-1,H=0;for(let Y=0;Y<F;Y++)H+=Nt.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(Y));if(this.decodeRowResult.charAt(F)!==Nt.ALPHABET_STRING.charAt(H%43))throw new O;this.decodeRowResult=this.decodeRowResult.substring(0,F)}if(this.decodeRowResult.length===0)throw new $;let I;this.extendedMode?I=Nt.decodeExtended(this.decodeRowResult):I=this.decodeRowResult;let k=(a[1]+a[0])/2,L=p+y/2;return new Ee(I,null,0,[new ve(k,e),new ve(L,e)],Ce.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)===Nt.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 $}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<Nt.CHARACTER_ENCODINGS.length;n++)if(Nt.CHARACTER_ENCODINGS[n]===e)return Nt.ALPHABET_STRING.charAt(n);if(e===Nt.ASTERISK_ENCODING)return"*";throw new $}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 z;break;case"$":if(l>="A"&&l<="Z")d=String.fromCharCode(l.charCodeAt(0)-64);else throw new z;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 z;break;case"/":if(l>="A"&&l<="O")d=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")d=":";else throw new z;break}i+=d,s++}else i+=a}return i}}Nt.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",Nt.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],Nt.ASTERISK_ENCODING=148;class nt extends bt{constructor(){super(...arguments),this.narrowLineWidth=-1}decodeRow(e,n,i){let s=this.decodeStart(n),a=this.decodeEnd(n),l=new xe;nt.decodeMiddle(n,s[1],a[0],l);let d=l.toString(),h=null;i!=null&&(h=i.get(V.ALLOWED_LENGTHS)),h==null&&(h=nt.DEFAULT_ALLOWED_LENGTHS);let p=d.length,y=!1,E=0;for(let L of h){if(p===L){y=!0;break}L>E&&(E=L)}if(!y&&p>E&&(y=!0),!y)throw new z;const I=[new ve(s[1],e),new ve(a[0],e)];return new Ee(d,null,0,I,Ce.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;){bt.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=nt.decodeDigit(l);s.append(h.toString()),h=this.decodeDigit(d),s.append(h.toString()),a.forEach(function(p){n+=p})}}decodeStart(e){let n=nt.skipWhiteSpace(e),i=nt.findGuardPattern(e,n,nt.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 $}static skipWhiteSpace(e){const n=e.getSize(),i=e.getNextSet(0);if(i===n)throw new $;return i}decodeEnd(e){e.reverse();try{let n=nt.skipWhiteSpace(e),i;try{i=nt.findGuardPattern(e,n,nt.END_PATTERN_REVERSED[0])}catch(a){a instanceof $&&(i=nt.findGuardPattern(e,n,nt.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(bt.patternMatchVariance(a,i,nt.MAX_INDIVIDUAL_VARIANCE)<nt.MAX_AVG_VARIANCE)return[p,y];p+=a[0]+a[1],D.arraycopy(a,2,a,0,h-1),a[h-1]=0,a[h]=0,h--}else h++;a[h]=1,d=!d}throw new $}static decodeDigit(e){let n=nt.MAX_AVG_VARIANCE,i=-1,s=nt.PATTERNS.length;for(let a=0;a<s;a++){let l=nt.PATTERNS[a],d=bt.patternMatchVariance(e,l,nt.MAX_INDIVIDUAL_VARIANCE);d<n?(n=d,i=a):d===n&&(i=-1)}if(i>=0)return i%10;throw new $}}nt.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])],nt.MAX_AVG_VARIANCE=.38,nt.MAX_INDIVIDUAL_VARIANCE=.5,nt.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],nt.START_PATTERN=Int32Array.from([1,1,1,1]),nt.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class mt extends bt{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=mt.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 mt.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return mt.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 z;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 z;i+=a}return(1e3-i)%10}static decodeEnd(e,n){return mt.findGuardPattern(e,n,!1,mt.START_END_PATTERN,new Int32Array(mt.START_END_PATTERN.length).fill(0))}static findGuardPatternWithoutCounters(e,n,i,s){return this.findGuardPattern(e,n,i,s,new Int32Array(s.length))}static findGuardPattern(e,n,i,s,a){let l=e.getSize();n=i?e.getNextUnset(n):e.getNextSet(n);let d=0,h=n,p=s.length,y=i;for(let E=n;E<l;E++)if(e.get(E)!==y)a[d]++;else{if(d===p-1){if(bt.patternMatchVariance(a,s,mt.MAX_INDIVIDUAL_VARIANCE)<mt.MAX_AVG_VARIANCE)return Int32Array.from([h,E]);h+=a[0]+a[1];let I=a.slice(2,a.length-1);for(let k=0;k<d-1;k++)a[k]=I[k];a[d-1]=0,a[d]=0,d--}else d++;a[d]=1,y=!y}throw new $}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=bt.patternMatchVariance(n,p,mt.MAX_INDIVIDUAL_VARIANCE);y<a&&(a=y,l=h)}if(l>=0)return l;throw new $}}mt.MAX_AVG_VARIANCE=.48,mt.MAX_INDIVIDUAL_VARIANCE=.7,mt.START_END_PATTERN=Int32Array.from([1,1,1]),mt.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),mt.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),mt.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 $e{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=$e.parseExtensionString(l),h=[new ve((i[0]+i[1])/2,e),new ve(a,e)],p=new Ee(l,null,0,h,Ce.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=mt.decodeDigit(e,s,l,mt.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<4-p),p!==4&&(l=e.getNextSet(l),l=e.getNextUnset(l))}if(i.length!==5)throw new $;let h=this.determineCheckDigit(d);if($e.extensionChecksum(i.toString())!==h)throw new $;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 $}static parseExtensionString(e){if(e.length!==5)return null;let n=$e.parseExtension5String(e);return n==null?null:new Map([[Ue.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 ke{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=ke.parseExtensionString(l),h=[new ve((i[0]+i[1])/2,e),new ve(a,e)],p=new Ee(l,null,0,h,Ce.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=mt.decodeDigit(e,s,l,mt.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 $;if(parseInt(i.toString())%4!==d)throw new $;return l}static parseExtensionString(e){return e.length!==2?null:new Map([[Ue.ISSUE_NUMBER,parseInt(e)]])}}class Ye{static decodeRow(e,n,i){let s=mt.findGuardPattern(n,i,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{return new $e().decodeRow(e,n,s)}catch{return new ke().decodeRow(e,n,s)}}}Ye.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class He extends mt{constructor(){super(),this.decodeRowStringBuffer="",He.L_AND_G_PATTERNS=He.L_PATTERNS.map(e=>Int32Array.from(e));for(let e=10;e<20;e++){let n=He.L_PATTERNS[e-10],i=new Int32Array(n.length);for(let s=0;s<n.length;s++)i[s]=n[n.length-s-1];He.L_AND_G_PATTERNS[e]=i}}decodeRow(e,n,i){let s=He.findStartGuardPattern(n),a=i==null?null:i.get(V.NEED_RESULT_POINT_CALLBACK);if(a!=null){const ae=new ve((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 ve(d,e);a.foundPossibleResultPoint(ae)}let p=this.decodeEnd(n,d);if(a!=null){const ae=new ve((p[0]+p[1])/2,e);a.foundPossibleResultPoint(ae)}let y=p[1],E=y+(y-p[0]);if(E>=n.getSize()||!n.isRange(y,E,!1))throw new $;let I=h.toString();if(I.length<8)throw new z;if(!He.checkChecksum(I))throw new O;let k=(s[1]+s[0])/2,L=(p[1]+p[0])/2,F=this.getBarcodeFormat(),H=[new ve(k,e),new ve(L,e)],Y=new Ee(I,null,0,H,F,new Date().getTime()),le=0;try{let ae=Ye.decodeRow(e,n,p[1]);Y.putMetadata(Ue.UPC_EAN_EXTENSION,ae.getText()),Y.putAllMetadata(ae.getResultMetadata()),Y.addResultPoints(ae.getResultPoints()),le=ae.getText().length}catch{}let ce=i==null?null:i.get(V.ALLOWED_EAN_EXTENSIONS);if(ce!=null){let ae=!1;for(let We in ce)if(le.toString()===We){ae=!0;break}if(!ae)throw new $}return Y}decodeEnd(e,n){return He.findGuardPattern(e,n,!1,He.START_END_PATTERN,new Int32Array(He.START_END_PATTERN.length).fill(0))}static checkChecksum(e){return He.checkStandardUPCEANChecksum(e)}static checkStandardUPCEANChecksum(e){let n=e.length;if(n===0)return!1;let i=parseInt(e.charAt(n-1),10);return He.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 z;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 z;i+=a}return(1e3-i)%10}}class Ln extends He{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=He.decodeDigit(e,s,l,He.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}i=Ln.determineFirstDigit(i,d),l=He.findGuardPattern(e,l,!0,He.MIDDLE_PATTERN,new Int32Array(He.MIDDLE_PATTERN.length).fill(0))[1];for(let p=0;p<6&&l<a;p++){let y=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+y);for(let E of s)l+=E}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return Ce.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 $}}Ln.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26];class rs extends He{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=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}l=He.findGuardPattern(e,l,!0,He.MIDDLE_PATTERN,new Int32Array(He.MIDDLE_PATTERN.length).fill(0))[1];for(let h=0;h<4&&l<a;h++){let p=He.decodeDigit(e,s,l,He.L_PATTERNS);i+=String.fromCharCode(48+p);for(let y of s)l+=y}return{rowOffset:l,resultString:i}}getBarcodeFormat(){return Ce.EAN_8}}class is extends He{constructor(){super(...arguments),this.ean13Reader=new Ln}getBarcodeFormat(){return Ce.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 Ee(n.substring(1),null,null,e.getResultPoints(),Ce.UPC_A);return e.getResultMetadata()!=null&&i.putAllMetadata(e.getResultMetadata()),i}else throw new $}reset(){this.ean13Reader.reset()}}class xn extends He{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=xn.decodeDigit(e,s,l,xn.L_AND_G_PATTERNS);i+=String.fromCharCode(48+y%10);for(let E of s)l+=E;y>=10&&(d|=1<<5-p)}let h=xn.determineNumSysAndCheckDigit(i,d);return{rowOffset:l,resultString:h}}decodeEnd(e,n){return xn.findGuardPatternWithoutCounters(e,n,!0,xn.MIDDLE_END_PATTERN)}checkChecksum(e){return He.checkChecksum(xn.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 $.getNotFoundInstance()}getBarcodeFormat(){return Ce.UPC_E}static convertUPCEtoUPCA(e){const n=e.slice(1,7).split("").map(a=>a.charCodeAt(0)),i=new xe;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()}}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 Ui extends bt{constructor(e){super();let n=e==null?null:e.get(V.POSSIBLE_FORMATS),i=[];c(n)?(i.push(new Ln),i.push(new is),i.push(new rs),i.push(new xn)):(n.indexOf(Ce.EAN_13)>-1&&i.push(new Ln),n.indexOf(Ce.UPC_A)>-1&&i.push(new is),n.indexOf(Ce.EAN_8)>-1&&i.push(new rs),n.indexOf(Ce.UPC_E)>-1&&i.push(new xn)),this.readers=i}decodeRow(e,n,i){for(let s of this.readers)try{const a=s.decodeRow(e,n,i),l=a.getBarcodeFormat()===Ce.EAN_13&&a.getText().charAt(0)==="0",d=i==null?null:i.get(V.POSSIBLE_FORMATS),h=d==null||d.includes(Ce.UPC_A);if(l&&h){const p=a.getRawBytes(),y=new Ee(a.getText().substring(1),p,p?p.length:null,a.getResultPoints(),Ce.UPC_A);return y.putAllMetadata(a.getResultMetadata()),y}return a}catch{}throw new $}reset(){for(let e of this.readers)e.reset()}}class jt extends bt{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(bt.patternMatchVariance(e,n[i],jt.MAX_INDIVIDUAL_VARIANCE)<jt.MAX_AVG_VARIANCE)return i;throw new $}static count(e){return Ze.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>=jt.MIN_FINDER_PATTERN_RATIO&&s<=jt.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}}jt.MAX_AVG_VARIANCE=.2,jt.MAX_INDIVIDUAL_VARIANCE=.45,jt.MIN_FINDER_PATTERN_RATIO=9.5/12,jt.MAX_FINDER_PATTERN_RATIO=12.5/14;class yr{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 yr))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 ve(i,a)),this.resultPoints.push(new ve(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 Tn{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=Tn.combins(s-p-1,d-h-2);if(i&&l===0&&s-p-(d-h-1)>=d-h-1&&(y-=Tn.combins(s-p-(d-h),d-h-2)),d-h-1>1){let E=0;for(let I=s-p-(d-h-2);I>n;I--)E+=Tn.combins(s-p-I-1,d-h-3);y-=E*(d-1-h)}else s-p>n&&y--;a+=y}s-=p}return a}static combins(e,n){let i,s;e-n>n?(s=n,i=e-n):(s=e-n,i=n);let a=1,l=1;for(let d=e;d>i;d--)a*=d,l<=s&&(a/=l,l++);for(;l<=s;)a/=l,l++;return a}}class Bu{static buildBitArray(e){let n=e.length*2-1;e[e.length-1].getRightChar()==null&&(n-=1);let i=12*n,s=new Q(i),a=0,d=e[0].getRightChar().getValue();for(let h=11;h>=0;--h)(d&1<<h)!=0&&s.set(a),a++;for(let h=1;h<e.length;++h){let p=e[h],y=p.getLeftChar().getValue();for(let E=11;E>=0;--E)(y&1<<E)!=0&&s.set(a),a++;if(p.getRightChar()!=null){let E=p.getRightChar().getValue();for(let I=11;I>=0;--I)(E&1<<I)!=0&&s.set(a),a++}}return s}}class ir{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 Qt extends zi{constructor(e,n){super(e),this.value=n}getValue(){return this.value}isFNC1(){return this.value===Qt.FNC1}}Qt.FNC1="$";class or 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 hn extends zi{constructor(e,n,i){if(super(e),n<0||n>10||i<0||i>10)throw new z;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===hn.FNC1}isSecondDigitFNC1(){return this.secondDigit===hn.FNC1}isAnyFNC1(){return this.firstDigit===hn.FNC1||this.secondDigit===hn.FNC1}}hn.FNC1=10;class we{constructor(){}static parseFieldsInGeneralPurpose(e){if(!e)return null;if(e.length<2)throw new $;let n=e.substring(0,2);for(let a of we.TWO_DIGIT_DATA_LENGTH)if(a[0]===n)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(2,a[2],e):we.processFixedAI(2,a[1],e);if(e.length<3)throw new $;let i=e.substring(0,3);for(let a of we.THREE_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(3,a[2],e):we.processFixedAI(3,a[1],e);for(let a of we.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH)if(a[0]===i)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(4,a[2],e):we.processFixedAI(4,a[1],e);if(e.length<4)throw new $;let s=e.substring(0,4);for(let a of we.FOUR_DIGIT_DATA_LENGTH)if(a[0]===s)return a[1]===we.VARIABLE_LENGTH?we.processVariableAI(4,a[2],e):we.processFixedAI(4,a[1],e);throw new $}static processFixedAI(e,n,i){if(i.length<e)throw new $;let s=i.substring(0,e);if(i.length<e+n)throw new $;let a=i.substring(e,e+n),l=i.substring(e+n),d="("+s+")"+a,h=we.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=we.parseFieldsInGeneralPurpose(d);return p==null?h:h+p}}we.VARIABLE_LENGTH=[],we.TWO_DIGIT_DATA_LENGTH=[["00",18],["01",14],["02",14],["10",we.VARIABLE_LENGTH,20],["11",6],["12",6],["13",6],["15",6],["17",6],["20",2],["21",we.VARIABLE_LENGTH,20],["22",we.VARIABLE_LENGTH,29],["30",we.VARIABLE_LENGTH,8],["37",we.VARIABLE_LENGTH,8],["90",we.VARIABLE_LENGTH,30],["91",we.VARIABLE_LENGTH,30],["92",we.VARIABLE_LENGTH,30],["93",we.VARIABLE_LENGTH,30],["94",we.VARIABLE_LENGTH,30],["95",we.VARIABLE_LENGTH,30],["96",we.VARIABLE_LENGTH,30],["97",we.VARIABLE_LENGTH,3],["98",we.VARIABLE_LENGTH,30],["99",we.VARIABLE_LENGTH,30]],we.THREE_DIGIT_DATA_LENGTH=[["240",we.VARIABLE_LENGTH,30],["241",we.VARIABLE_LENGTH,30],["242",we.VARIABLE_LENGTH,6],["250",we.VARIABLE_LENGTH,30],["251",we.VARIABLE_LENGTH,30],["253",we.VARIABLE_LENGTH,17],["254",we.VARIABLE_LENGTH,20],["400",we.VARIABLE_LENGTH,30],["401",we.VARIABLE_LENGTH,30],["402",17],["403",we.VARIABLE_LENGTH,30],["410",13],["411",13],["412",13],["413",13],["414",13],["420",we.VARIABLE_LENGTH,20],["421",we.VARIABLE_LENGTH,15],["422",3],["423",we.VARIABLE_LENGTH,15],["424",3],["425",3],["426",3]],we.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",we.VARIABLE_LENGTH,15],["391",we.VARIABLE_LENGTH,18],["392",we.VARIABLE_LENGTH,15],["393",we.VARIABLE_LENGTH,18],["703",we.VARIABLE_LENGTH,30]],we.FOUR_DIGIT_DATA_LENGTH=[["7001",13],["7002",we.VARIABLE_LENGTH,30],["7003",10],["8001",14],["8002",we.VARIABLE_LENGTH,20],["8003",we.VARIABLE_LENGTH,30],["8004",we.VARIABLE_LENGTH,30],["8005",6],["8006",18],["8007",we.VARIABLE_LENGTH,30],["8008",we.VARIABLE_LENGTH,12],["8018",18],["8020",we.VARIABLE_LENGTH,25],["8100",6],["8101",10],["8102",2],["8110",we.VARIABLE_LENGTH,70],["8200",we.VARIABLE_LENGTH,70]];class wr{constructor(e){this.buffer=new xe,this.information=e}decodeAllCodes(e,n){let i=n,s=null;do{let a=this.decodeGeneralPurposeField(i,s),l=we.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 hn(this.information.getSize(),hn.FNC1,hn.FNC1):new hn(this.information.getSize(),a-1,hn.FNC1)}let n=this.extractNumericValueFromBitArray(e,7),i=(n-8)/11,s=(n-8)%11;return new hn(e+7,i,s)}extractNumericValueFromBitArray(e,n){return wr.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 or(this.current.getPosition(),this.buffer.toString(),i.getRemainingValue()):new or(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 or(this.current.getPosition(),this.buffer.toString()):n=new or(this.current.getPosition(),this.buffer.toString(),e.getSecondDigit()),new ir(!0,n)}if(this.buffer.append(e.getFirstDigit()),e.isSecondDigitFNC1()){let n=new or(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 or(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 or(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 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 Qt(e+5,Qt.FNC1);if(n>=5&&n<15)return new Qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,7);if(i>=64&&i<90)return new Qt(e+7,""+(i+1));if(i>=90&&i<116)return new Qt(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 z}return new Qt(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 Qt(e+5,Qt.FNC1);if(n>=5&&n<15)return new Qt(e+5,"0"+(n-5));let i=this.extractNumericValueFromBitArray(e,6);if(i>=32&&i<58)return new Qt(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 Wt("Decoding invalid alphanumeric value: "+i)}return new Qt(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 wr(e)}getInformation(){return this.information}getGeneralDecoder(){return this.generalDecoder}}class en 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)}en.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)}}en.GTIN_SIZE=40;class _r extends en{constructor(e){super(e)}parseInformation(){let e=new xe;e.append("(01)");let n=e.length(),i=this.getGeneralDecoder().extractNumericValueFromBitArray(_r.HEADER_SIZE,4);return e.append(i),this.encodeCompressedGtinWithoutAI(e,_r.HEADER_SIZE+4,n),this.getGeneralDecoder().decodeAllCodes(e,_r.HEADER_SIZE+44)}}_r.HEADER_SIZE=4;class ai extends Vi{constructor(e){super(e)}parseInformation(){let e=new xe;return this.getGeneralDecoder().decodeAllCodes(e,ai.HEADER_SIZE)}}ai.HEADER_SIZE=5;class li extends en{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 Nn extends li{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()!=Nn.HEADER_SIZE+li.GTIN_SIZE+Nn.WEIGHT_SIZE)throw new $;let e=new xe;return this.encodeCompressedGtin(e,Nn.HEADER_SIZE),this.encodeCompressedWeight(e,Nn.HEADER_SIZE+li.GTIN_SIZE,Nn.WEIGHT_SIZE),e.toString()}}Nn.HEADER_SIZE=5,Nn.WEIGHT_SIZE=15;class Lu extends Nn{constructor(e){super(e)}addWeightCode(e,n){e.append("(3103)")}checkWeight(e){return e}}class Fu extends Nn{constructor(e){super(e)}addWeightCode(e,n){n<1e4?e.append("(3202)"):e.append("(3203)")}checkWeight(e){return e<1e4?e:e-1e4}}class On extends en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<On.HEADER_SIZE+en.GTIN_SIZE)throw new $;let e=new xe;this.encodeCompressedGtin(e,On.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(On.HEADER_SIZE+en.GTIN_SIZE,On.LAST_DIGIT_SIZE);e.append("(392"),e.append(n),e.append(")");let i=this.getGeneralDecoder().decodeGeneralPurposeField(On.HEADER_SIZE+en.GTIN_SIZE+On.LAST_DIGIT_SIZE,null);return e.append(i.getNewString()),e.toString()}}On.HEADER_SIZE=8,On.LAST_DIGIT_SIZE=2;class qt extends en{constructor(e){super(e)}parseInformation(){if(this.getInformation().getSize()<qt.HEADER_SIZE+en.GTIN_SIZE)throw new $;let e=new xe;this.encodeCompressedGtin(e,qt.HEADER_SIZE);let n=this.getGeneralDecoder().extractNumericValueFromBitArray(qt.HEADER_SIZE+en.GTIN_SIZE,qt.LAST_DIGIT_SIZE);e.append("(393"),e.append(n),e.append(")");let i=this.getGeneralDecoder().extractNumericValueFromBitArray(qt.HEADER_SIZE+en.GTIN_SIZE+qt.LAST_DIGIT_SIZE,qt.FIRST_THREE_DIGITS_SIZE);i/100==0&&e.append("0"),i/10==0&&e.append("0"),e.append(i);let s=this.getGeneralDecoder().decodeGeneralPurposeField(qt.HEADER_SIZE+en.GTIN_SIZE+qt.LAST_DIGIT_SIZE+qt.FIRST_THREE_DIGITS_SIZE,null);return e.append(s.getNewString()),e.toString()}}qt.HEADER_SIZE=8,qt.LAST_DIGIT_SIZE=2,qt.FIRST_THREE_DIGITS_SIZE=10;class gt extends li{constructor(e,n,i){super(e),this.dateCode=i,this.firstAIdigits=n}parseInformation(){if(this.getInformation().getSize()!=gt.HEADER_SIZE+gt.GTIN_SIZE+gt.WEIGHT_SIZE+gt.DATE_SIZE)throw new $;let e=new xe;return this.encodeCompressedGtin(e,gt.HEADER_SIZE),this.encodeCompressedWeight(e,gt.HEADER_SIZE+gt.GTIN_SIZE,gt.WEIGHT_SIZE),this.encodeCompressedDate(e,gt.HEADER_SIZE+gt.GTIN_SIZE+gt.WEIGHT_SIZE),e.toString()}encodeCompressedDate(e,n){let i=this.getGeneralDecoder().extractNumericValueFromBitArray(n,gt.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}}gt.HEADER_SIZE=8,gt.WEIGHT_SIZE=20,gt.DATE_SIZE=16;function os(b){try{if(b.get(1))return new _r(b);if(!b.get(2))return new ai(b);switch(wr.extractNumericValueFromBitArray(b,1,4)){case 4:return new Lu(b);case 5:return new Fu(b)}switch(wr.extractNumericValueFromBitArray(b,1,5)){case 12:return new On(b);case 13:return new qt(b)}switch(wr.extractNumericValueFromBitArray(b,1,7)){case 56:return new gt(b,"310","11");case 57:return new gt(b,"320","11");case 58:return new gt(b,"310","13");case 59:return new gt(b,"320","13");case 60:return new gt(b,"310","15");case 61:return new gt(b,"320","15");case 62:return new gt(b,"310","17");case 63:return new gt(b,"320","17")}}catch(e){throw console.log(e),new Wt("unknown decoder: "+b)}}class Wn{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 Wn?Wn.equalsOrNull(e.leftchar,n.leftchar)&&Wn.equalsOrNull(e.rightchar,n.rightchar)&&Wn.equalsOrNull(e.finderpattern,n.finderpattern):!1}static equalsOrNull(e,n){return e===null?n===null:Wn.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 se extends jt{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,i){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 i=!1;for(;!i;)try{this.pairs.push(this.retrieveNextPair(n,this.pairs,e))}catch(a){if(a instanceof $){if(!this.pairs.length)throw new $;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 $}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()),!se.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 $}static isValidSequence(e){for(let n of se.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||se.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(Wn.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=Bu.buildBitArray(e),s=os(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 Ee(s,null,null,d,Ce.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=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 $;let p;try{p=this.decodeDataCharacter(e,a,s,!1)}catch(y){p=null,this.verbose&&console.log(y)}return new Wn(h,p,a,!0)}isEmptyPair(e){return e.length===0}findNextPair(e,n,i){let s=this.getDecodeFinderCounters();s[0]=0,s[1]=0,s[2]=0,s[3]=0;let a=e.getSize(),l;i>=0?l=i:this.isEmptyPair(n)?l=0:l=n[n.length-1].getFinderPattern().getStartEnd()[1];let d=n.length%2!=0;this.startFromEven&&(d=!d);let h=!1;for(;l<a&&(h=!e.get(l),!!h);)l++;let p=0,y=l;for(let E=l;E<a;E++)if(e.get(E)!=h)s[p]++;else{if(p==3){if(d&&se.reverseCounters(s),se.isFinderPattern(s)){this.startEnd[0]=y,this.startEnd[1]=E;return}d&&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 $}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();D.arraycopy(d,0,d,1,d.length-1),d[0]=s;let h;try{h=this.parseFinderValue(d,se.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 st=0;st<a.length;st++)a[st]=0;if(s)se.recordPatternInReverse(e,n.getStartEnd()[0],a);else{se.recordPattern(e,n.getStartEnd()[1],a);for(let st=0,$t=a.length-1;st<$t;st++,$t--){let an=a[st];a[st]=a[$t],a[$t]=an}}let l=17,d=Ze.sum(new Int32Array(a))/l,h=(n.getStartEnd()[1]-n.getStartEnd()[0])/15;if(Math.abs(d-h)/h>.3)throw new $;let p=this.getOddCounts(),y=this.getEvenCounts(),E=this.getOddRoundingErrors(),I=this.getEvenRoundingErrors();for(let st=0;st<a.length;st++){let $t=1*a[st]/d,an=$t+.5;if(an<1){if($t<.3)throw new $;an=1}else if(an>8){if($t>8.7)throw new $;an=8}let Ar=st/2;(st&1)==0?(p[Ar]=an,E[Ar]=$t-an):(y[Ar]=an,I[Ar]=$t-an)}this.adjustOddEvenCounts(l);let k=4*n.getValue()+(i?0:2)+(s?0:1)-1,L=0,F=0;for(let st=p.length-1;st>=0;st--){if(se.isNotA1left(n,i,s)){let $t=se.WEIGHTS[k][2*st];F+=p[st]*$t}L+=p[st]}let H=0;for(let st=y.length-1;st>=0;st--)if(se.isNotA1left(n,i,s)){let $t=se.WEIGHTS[k][2*st+1];H+=y[st]*$t}let Y=F+H;if((L&1)!=0||L>13||L<4)throw new $;let le=(13-L)/2,ce=se.SYMBOL_WIDEST[le],ae=9-ce,We=Tn.getRSSvalue(p,ce,!0),Fe=Tn.getRSSvalue(y,ae,!1),nn=se.EVEN_TOTAL_SUBSET[le],yn=se.GSUM[le],rn=We*nn+Fe+yn;return new yr(rn,Y)}static isNotA1left(e,n,i){return!(e.getValue()==0&&n&&i)}adjustOddEvenCounts(e){let n=Ze.sum(new Int32Array(this.getOddCounts())),i=Ze.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 $;a=!0}else{if(!y)throw new $;d=!0}else if(h==-1)if(p){if(y)throw new $;s=!0}else{if(!y)throw new $;l=!0}else if(h==0){if(p){if(!y)throw new $;n<i?(s=!0,d=!0):(a=!0,l=!0)}else if(y)throw new $}else throw new $;if(s){if(a)throw new $;se.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(a&&se.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(d)throw new $;se.increment(this.getEvenCounts(),this.getOddRoundingErrors())}d&&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 Uu extends yr{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 Et extends jt{constructor(){super(...arguments),this.possibleLeftPairs=[],this.possibleRightPairs=[]}decodeRow(e,n,i){const s=this.decodePair(n,!1,e,i);Et.addOrTally(this.possibleLeftPairs,s),n.reverse();let a=this.decodePair(n,!0,e,i);Et.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&&Et.checkChecksum(l,d))return Et.constructResult(l,d)}throw new $}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 xe;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 Ee(a.toString(),null,0,[d[0],d[1],h[0],h[1]],Ce.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(V.NEED_RESULT_POINT_CALLBACK);if(d!=null){let y=(a[0]+a[1])/2;n&&(y=e.getSize()-1-y),d.foundPossibleResultPoint(new ve(y,i))}let h=this.decodeDataCharacter(e,l,!0),p=this.decodeDataCharacter(e,l,!1);return new Uu(1597*h.getValue()+p.getValue(),h.getChecksumPortion()+4*p.getChecksumPortion(),l)}catch{return null}}decodeDataCharacter(e,n,i){let s=this.getDataCharacterCounters();for(let H=0;H<s.length;H++)s[H]=0;if(i)bt.recordPatternInReverse(e,n.getStartEnd()[0],s);else{bt.recordPattern(e,n.getStartEnd()[1]+1,s);for(let H=0,Y=s.length-1;H<Y;H++,Y--){let le=s[H];s[H]=s[Y],s[Y]=le}}let a=i?16:15,l=Ze.sum(new Int32Array(s))/a,d=this.getOddCounts(),h=this.getEvenCounts(),p=this.getOddRoundingErrors(),y=this.getEvenRoundingErrors();for(let H=0;H<s.length;H++){let Y=s[H]/l,le=Math.floor(Y+.5);le<1?le=1:le>8&&(le=8);let ce=Math.floor(H/2);(H&1)===0?(d[ce]=le,p[ce]=Y-le):(h[ce]=le,y[ce]=Y-le)}this.adjustOddEvenCounts(i,a);let E=0,I=0;for(let H=d.length-1;H>=0;H--)I*=9,I+=d[H],E+=d[H];let k=0,L=0;for(let H=h.length-1;H>=0;H--)k*=9,k+=h[H],L+=h[H];let F=I+3*k;if(i){if((E&1)!==0||E>12||E<4)throw new $;let H=(12-E)/2,Y=Et.OUTSIDE_ODD_WIDEST[H],le=9-Y,ce=Tn.getRSSvalue(d,Y,!1),ae=Tn.getRSSvalue(h,le,!0),We=Et.OUTSIDE_EVEN_TOTAL_SUBSET[H],Fe=Et.OUTSIDE_GSUM[H];return new yr(ce*We+ae+Fe,F)}else{if((L&1)!==0||L>10||L<4)throw new $;let H=(10-L)/2,Y=Et.INSIDE_ODD_WIDEST[H],le=9-Y,ce=Tn.getRSSvalue(d,Y,!0),ae=Tn.getRSSvalue(h,le,!1),We=Et.INSIDE_ODD_TOTAL_SUBSET[H],Fe=Et.INSIDE_GSUM[H];return new yr(ae*We+ce+Fe,F)}}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(jt.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 $}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);D.arraycopy(h,0,p,1,h.length-1),p[0]=d;const y=this.parseFinderValue(p,Et.FINDER_PATTERNS);let E=l,I=s[1];return i&&(E=e.getSize()-1-E,I=e.getSize()-1-I),new si(y,[l,s[1]],E,I,n)}adjustOddEvenCounts(e,n){let i=Ze.sum(new Int32Array(this.getOddCounts())),s=Ze.sum(new Int32Array(this.getEvenCounts())),a=!1,l=!1,d=!1,h=!1;e?(i>12?l=!0:i<4&&(a=!0),s>12?h=!0:s<4&&(d=!0)):(i>11?l=!0:i<5&&(a=!0),s>10?h=!0:s<4&&(d=!0));let p=i+s-n,y=(i&1)===(e?1:0),E=(s&1)===1;if(p===1)if(y){if(E)throw new $;l=!0}else{if(!E)throw new $;h=!0}else if(p===-1)if(y){if(E)throw new $;a=!0}else{if(!E)throw new $;d=!0}else if(p===0){if(y){if(!E)throw new $;i<s?(a=!0,h=!0):(l=!0,d=!0)}else if(E)throw new $}else throw new $;if(a){if(l)throw new $;jt.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&jt.decrement(this.getOddCounts(),this.getOddRoundingErrors()),d){if(h)throw new $;jt.increment(this.getEvenCounts(),this.getOddRoundingErrors())}h&&jt.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())}}Et.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],Et.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],Et.OUTSIDE_GSUM=[0,161,961,2015,2715],Et.INSIDE_GSUM=[0,336,1036,1516],Et.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],Et.INSIDE_ODD_WIDEST=[2,4,6,8],Et.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 vr extends bt{constructor(e,n){super(),this.readers=[],this.verbose=n===!0;const i=e?e.get(V.POSSIBLE_FORMATS):null,s=e&&e.get(V.ASSUME_CODE_39_CHECK_DIGIT)!==void 0;i?((i.includes(Ce.EAN_13)||i.includes(Ce.UPC_A)||i.includes(Ce.EAN_8)||i.includes(Ce.UPC_E))&&this.readers.push(new Ui(e)),i.includes(Ce.CODE_39)&&this.readers.push(new Nt(s)),i.includes(Ce.CODE_128)&&this.readers.push(new he),i.includes(Ce.ITF)&&this.readers.push(new nt),i.includes(Ce.RSS_14)&&this.readers.push(new Et),i.includes(Ce.RSS_EXPANDED)&&this.readers.push(new se(this.verbose))):(this.readers.push(new Ui(e)),this.readers.push(new Nt),this.readers.push(new Ui(e)),this.readers.push(new he),this.readers.push(new nt),this.readers.push(new Et),this.readers.push(new se(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 $}reset(){this.readers.forEach(e=>e.reset())}}class zu extends vt{constructor(e=500,n){super(new vr(n),e,n)}}class et{constructor(e,n,i){this.ecCodewords=e,this.ecBlocks=[n],i&&this.ecBlocks.push(i)}getECCodewords(){return this.ecCodewords}getECBlocks(){return this.ecBlocks}}class Ke{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class je{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 z;for(let i of je.VERSIONS)if(i.symbolSizeRows===e&&i.symbolSizeColumns===n)return i;throw new z}toString(){return""+this.versionNumber}static buildVersions(){return[new je(1,10,10,8,8,new et(5,new Ke(1,3))),new je(2,12,12,10,10,new et(7,new Ke(1,5))),new je(3,14,14,12,12,new et(10,new Ke(1,8))),new je(4,16,16,14,14,new et(12,new Ke(1,12))),new je(5,18,18,16,16,new et(14,new Ke(1,18))),new je(6,20,20,18,18,new et(18,new Ke(1,22))),new je(7,22,22,20,20,new et(20,new Ke(1,30))),new je(8,24,24,22,22,new et(24,new Ke(1,36))),new je(9,26,26,24,24,new et(28,new Ke(1,44))),new je(10,32,32,14,14,new et(36,new Ke(1,62))),new je(11,36,36,16,16,new et(42,new Ke(1,86))),new je(12,40,40,18,18,new et(48,new Ke(1,114))),new je(13,44,44,20,20,new et(56,new Ke(1,144))),new je(14,48,48,22,22,new et(68,new Ke(1,174))),new je(15,52,52,24,24,new et(42,new Ke(2,102))),new je(16,64,64,14,14,new et(56,new Ke(2,140))),new je(17,72,72,16,16,new et(36,new Ke(4,92))),new je(18,80,80,18,18,new et(48,new Ke(4,114))),new je(19,88,88,20,20,new et(56,new Ke(4,144))),new je(20,96,96,22,22,new et(68,new Ke(4,174))),new je(21,104,104,24,24,new et(56,new Ke(6,136))),new je(22,120,120,18,18,new et(68,new Ke(6,175))),new je(23,132,132,20,20,new et(62,new Ke(8,163))),new je(24,144,144,22,22,new et(62,new Ke(8,156),new Ke(2,155))),new je(25,8,18,6,16,new et(7,new Ke(1,5))),new je(26,8,32,6,14,new et(11,new Ke(1,10))),new je(27,12,26,10,24,new et(14,new Ke(1,16))),new je(28,12,36,10,16,new et(18,new Ke(1,22))),new je(29,16,36,14,16,new et(24,new Ke(1,32))),new je(30,16,48,14,22,new et(28,new Ke(1,49)))]}}je.VERSIONS=je.buildVersions();class $i{constructor(e){const n=e.getHeight();if(n<8||n>144||(n&1)!==0)throw new z;this.version=$i.readVersion(e),this.mappingBitMatrix=this.extractDataRegion(e),this.readMappingMatrix=new Me(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}getVersion(){return this.version}static readVersion(e){const n=e.getHeight(),i=e.getWidth();return je.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 z;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 v("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 Me(p,h);for(let E=0;E<l;++E){const I=E*s;for(let k=0;k<d;++k){const L=k*a;for(let F=0;F<s;++F){const H=E*(s+2)+1+F,Y=I+F;for(let le=0;le<a;++le){const ce=k*(a+2)+1+le;if(e.get(ce,H)){const ae=L+le;y.set(ae,Y)}}}}}return y}}class Hi{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 F of a)s+=F.getCount();const l=new Array(s);let d=0;for(let F of a)for(let H=0;H<F.getCount();H++){const Y=F.getDataCodewords(),le=i.getECCodewords()+Y;l[d++]=new Hi(Y,new Uint8Array(le))}const p=l[0].codewords.length-i.getECCodewords(),y=p-1;let E=0;for(let F=0;F<y;F++)for(let H=0;H<d;H++)l[H].codewords[F]=e[E++];const I=n.getVersionNumber()===24,k=I?8:d;for(let F=0;F<k;F++)l[F].codewords[p-1]=e[E++];const L=l[0].codewords.length;for(let F=p;F<L;F++)for(let H=0;H<d;H++){const Y=I?(H+8)%d:H,le=I&&Y>7?F-1:F;l[Y].codewords[le]=e[E++]}if(E!==e.length)throw new v;return l}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}class Wi{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 v(""+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 Mt;(function(b){b[b.PAD_ENCODE=0]="PAD_ENCODE",b[b.ASCII_ENCODE=1]="ASCII_ENCODE",b[b.C40_ENCODE=2]="C40_ENCODE",b[b.TEXT_ENCODE=3]="TEXT_ENCODE",b[b.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",b[b.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",b[b.BASE256_ENCODE=6]="BASE256_ENCODE"})(Mt||(Mt={}));class jn{static decode(e){const n=new Wi(e),i=new xe,s=new xe,a=new Array;let l=Mt.ASCII_ENCODE;do if(l===Mt.ASCII_ENCODE)l=this.decodeAsciiSegment(n,i,s);else{switch(l){case Mt.C40_ENCODE:this.decodeC40Segment(n,i);break;case Mt.TEXT_ENCODE:this.decodeTextSegment(n,i);break;case Mt.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,i);break;case Mt.EDIFACT_ENCODE:this.decodeEdifactSegment(n,i);break;case Mt.BASE256_ENCODE:this.decodeBase256Segment(n,i,a);break;default:throw new z}l=Mt.ASCII_ENCODE}while(l!==Mt.PAD_ENCODE&&n.available()>0);return s.length()>0&&i.append(s.toString()),new Ht(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 z;if(a<=128)return s&&(a+=128),n.append(String.fromCharCode(a-1)),Mt.ASCII_ENCODE;if(a===129)return Mt.PAD_ENCODE;if(a<=229){const l=a-130;l<10&&n.append("0"),n.append(""+l)}else switch(a){case 230:return Mt.C40_ENCODE;case 231:return Mt.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 Mt.ANSIX12_ENCODE;case 239:return Mt.TEXT_ENCODE;case 240:return Mt.EDIFACT_ENCODE;case 241:break;default:if(a!==254||e.available()!==0)throw new z;break}}while(e.available()>0);return Mt.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 z;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 z}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 z}}}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 z;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 z}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 z;break;default:throw new z}}}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 z;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 z;const d=new Uint8Array(l);for(let h=0;h<l;h++){if(e.available()<8)throw new z;d[h]=this.unrandomize255State(e.readBits(8),s++)}i.push(d);try{n.append(ye.decode(d,re.ISO88591))}catch(h){throw new Wt("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}}jn.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"],jn.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],jn.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"],jn.TEXT_SHIFT2_SET_CHARS=jn.C40_SHIFT2_SET_CHARS,jn.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 Vu{constructor(){this.rsDecoder=new In(be.DATA_MATRIX_FIELD_256)}decode(e){const n=new $i(e),i=n.getVersion(),s=n.readCodewords(),a=Hi.getDataBlocks(s,i);let l=0;for(let p of a)l+=p.getNumDataCodewords();const d=new Uint8Array(l),h=a.length;for(let p=0;p<h;p++){const y=a[p],E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let k=0;k<I;k++)d[k*h+p]=E[k]}return jn.decode(d)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Ot{constructor(e){this.image=e,this.rectangleDetector=new Jt(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 $;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=Ot.sampleGrid(this.image,i,s,a,l,d,h);return new Bn(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 ve(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 ve(s,a)}detectSolid1(e){let n=e[0],i=e[1],s=e[3],a=e[2],l=this.transitionsBetween(n,i),d=this.transitionsBetween(i,s),h=this.transitionsBetween(s,a),p=this.transitionsBetween(a,n),y=l,E=[a,n,i,s];return y>d&&(y=d,E[0]=n,E[1]=i,E[2]=s,E[3]=a),y>h&&(y=h,E[0]=i,E[1]=s,E[2]=a,E[3]=n),y>p&&(E[0]=s,E[1]=a,E[2]=n,E[3]=i),E}detectSolid2(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a),d=Ot.shiftPoint(i,s,(l+1)*4),h=Ot.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=Ot.shiftPoint(n,i,(d+1)*4),p=Ot.shiftPoint(s,i,(l+1)*4);l=this.transitionsBetween(h,a),d=this.transitionsBetween(p,a);let y=new ve(a.getX()+(s.getX()-i.getX())/(l+1),a.getY()+(s.getY()-i.getY())/(l+1)),E=new ve(a.getX()+(n.getX()-i.getX())/(d+1),a.getY()+(n.getY()-i.getY())/(d+1));if(!this.isValid(y))return this.isValid(E)?E:null;if(!this.isValid(E))return y;let I=this.transitionsBetween(h,y)+this.transitionsBetween(p,y),k=this.transitionsBetween(h,E)+this.transitionsBetween(p,E);return I>k?y:E}shiftToModuleCenter(e){let n=e[0],i=e[1],s=e[2],a=e[3],l=this.transitionsBetween(n,a)+1,d=this.transitionsBetween(s,a)+1,h=Ot.shiftPoint(n,i,d*4),p=Ot.shiftPoint(s,i,l*4);l=this.transitionsBetween(h,a)+1,d=this.transitionsBetween(p,a)+1,(l&1)===1&&(l+=1),(d&1)===1&&(d+=1);let y=(n.getX()+i.getX()+s.getX()+a.getX())/4,E=(n.getY()+i.getY()+s.getY()+a.getY())/4;n=Ot.moveAway(n,y,E),i=Ot.moveAway(i,y,E),s=Ot.moveAway(s,y,E),a=Ot.moveAway(a,y,E);let I,k;return h=Ot.shiftPoint(n,i,d*4),h=Ot.shiftPoint(h,a,l*4),I=Ot.shiftPoint(i,n,d*4),I=Ot.shiftPoint(I,s,l*4),p=Ot.shiftPoint(s,a,d*4),p=Ot.shiftPoint(p,i,l*4),k=Ot.shiftPoint(a,s,d*4),k=Ot.shiftPoint(k,n,l*4),[h,I,p,k]}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 R.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 F=i;i=s,s=F,F=a,a=l,l=F}let h=Math.abs(a-i),p=Math.abs(l-s),y=-h/2,E=s<l?1:-1,I=i<a?1:-1,k=0,L=this.image.get(d?s:i,d?i:s);for(let F=i,H=s;F!==a;F+=I){let Y=this.image.get(d?H:F,d?F:H);if(Y!==L&&(k++,L=Y),y+=p,y>0){if(H===l)break;H+=E,y-=h}}return k}}class Gn{constructor(){this.decoder=new Vu}decode(e,n=null){let i,s;if(n!=null&&n.has(V.PURE_BARCODE)){const p=Gn.extractPureBits(e.getBlackMatrix());i=this.decoder.decode(p),s=Gn.NO_POINTS}else{const p=new Ot(e.getBlackMatrix()).detect();i=this.decoder.decode(p.getBits()),s=p.getPoints()}const a=i.getRawBytes(),l=new Ee(i.getText(),a,8*a.length,s,Ce.DATA_MATRIX,D.currentTimeMillis()),d=i.getByteSegments();d!=null&&l.putMetadata(Ue.BYTE_SEGMENTS,d);const h=i.getECLevel();return h!=null&&l.putMetadata(Ue.ERROR_CORRECTION_LEVEL,h),l}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n==null||i==null)throw new $;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 $;const E=s/2;a+=E,d+=E;const I=new Me(p,y);for(let k=0;k<y;k++){const L=a+k*s;for(let F=0;F<p;F++)e.get(d+F*s,L)&&I.set(F,k)}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 $;const l=s-e[0];if(l===0)throw new $;return l}}Gn.NO_POINTS=[];class Zu extends vt{constructor(e=500){super(new Gn,e)}}var Cr;(function(b){b[b.L=0]="L",b[b.M=1]="M",b[b.Q=2]="Q",b[b.H=3]="H"})(Cr||(Cr={}));class ct{constructor(e,n,i){this.value=e,this.stringValue=n,this.bits=i,ct.FOR_BITS.set(i,this),ct.FOR_VALUE.set(e,this)}getValue(){return this.value}getBits(){return this.bits}static fromString(e){switch(e){case"L":return ct.L;case"M":return ct.M;case"Q":return ct.Q;case"H":return ct.H;default:throw new A(e+"not available")}}toString(){return this.stringValue}equals(e){if(!(e instanceof ct))return!1;const n=e;return this.value===n.value}static forBits(e){if(e<0||e>=ct.FOR_BITS.size)throw new v;return ct.FOR_BITS.get(e)}}ct.FOR_BITS=new Map,ct.FOR_VALUE=new Map,ct.L=new ct(Cr.L,"L",1),ct.M=new ct(Cr.M,"M",0),ct.Q=new ct(Cr.Q,"Q",3),ct.H=new ct(Cr.H,"H",2);class Gt{constructor(e){this.errorCorrectionLevel=ct.forBits(e>>3&3),this.dataMask=e&7}static numBitsDiffering(e,n){return U.bitCount(e^n)}static decodeFormatInformation(e,n){const i=Gt.doDecodeFormatInformation(e,n);return i!==null?i:Gt.doDecodeFormatInformation(e^Gt.FORMAT_INFO_MASK_QR,n^Gt.FORMAT_INFO_MASK_QR)}static doDecodeFormatInformation(e,n){let i=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 d=Gt.numBitsDiffering(e,l);d<i&&(s=a[1],i=d),e!==n&&(d=Gt.numBitsDiffering(n,l),d<i&&(s=a[1],i=d))}return i<=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 W{constructor(e,...n){this.ecCodewordsPerBlock=e,this.ecBlocks=n}getECCodewordsPerBlock(){return this.ecCodewordsPerBlock}getNumBlocks(){let e=0;const n=this.ecBlocks;for(const i of n)e+=i.getCount();return e}getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks()}getECBlocks(){return this.ecBlocks}}class N{constructor(e,n){this.count=e,this.dataCodewords=n}getCount(){return this.count}getDataCodewords(){return this.dataCodewords}}class Ie{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 z;try{return this.getVersionForNumber((e-17)/4)}catch{throw new z}}static getVersionForNumber(e){if(e<1||e>40)throw new v;return Ie.VERSIONS[e-1]}static decodeVersionInformation(e){let n=Number.MAX_SAFE_INTEGER,i=0;for(let s=0;s<Ie.VERSION_DECODE_INFO.length;s++){const a=Ie.VERSION_DECODE_INFO[s];if(a===e)return Ie.getVersionForNumber(s+7);const l=Gt.numBitsDiffering(e,a);l<n&&(i=s+7,n=l)}return n<=3?Ie.getVersionForNumber(i):null}buildFunctionPattern(){const e=this.getDimensionForVersion(),n=new Me(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}}Ie.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]),Ie.VERSIONS=[new Ie(1,new Int32Array(0),new W(7,new N(1,19)),new W(10,new N(1,16)),new W(13,new N(1,13)),new W(17,new N(1,9))),new Ie(2,Int32Array.from([6,18]),new W(10,new N(1,34)),new W(16,new N(1,28)),new W(22,new N(1,22)),new W(28,new N(1,16))),new Ie(3,Int32Array.from([6,22]),new W(15,new N(1,55)),new W(26,new N(1,44)),new W(18,new N(2,17)),new W(22,new N(2,13))),new Ie(4,Int32Array.from([6,26]),new W(20,new N(1,80)),new W(18,new N(2,32)),new W(26,new N(2,24)),new W(16,new N(4,9))),new Ie(5,Int32Array.from([6,30]),new W(26,new N(1,108)),new W(24,new N(2,43)),new W(18,new N(2,15),new N(2,16)),new W(22,new N(2,11),new N(2,12))),new Ie(6,Int32Array.from([6,34]),new W(18,new N(2,68)),new W(16,new N(4,27)),new W(24,new N(4,19)),new W(28,new N(4,15))),new Ie(7,Int32Array.from([6,22,38]),new W(20,new N(2,78)),new W(18,new N(4,31)),new W(18,new N(2,14),new N(4,15)),new W(26,new N(4,13),new N(1,14))),new Ie(8,Int32Array.from([6,24,42]),new W(24,new N(2,97)),new W(22,new N(2,38),new N(2,39)),new W(22,new N(4,18),new N(2,19)),new W(26,new N(4,14),new N(2,15))),new Ie(9,Int32Array.from([6,26,46]),new W(30,new N(2,116)),new W(22,new N(3,36),new N(2,37)),new W(20,new N(4,16),new N(4,17)),new W(24,new N(4,12),new N(4,13))),new Ie(10,Int32Array.from([6,28,50]),new W(18,new N(2,68),new N(2,69)),new W(26,new N(4,43),new N(1,44)),new W(24,new N(6,19),new N(2,20)),new W(28,new N(6,15),new N(2,16))),new Ie(11,Int32Array.from([6,30,54]),new W(20,new N(4,81)),new W(30,new N(1,50),new N(4,51)),new W(28,new N(4,22),new N(4,23)),new W(24,new N(3,12),new N(8,13))),new Ie(12,Int32Array.from([6,32,58]),new W(24,new N(2,92),new N(2,93)),new W(22,new N(6,36),new N(2,37)),new W(26,new N(4,20),new N(6,21)),new W(28,new N(7,14),new N(4,15))),new Ie(13,Int32Array.from([6,34,62]),new W(26,new N(4,107)),new W(22,new N(8,37),new N(1,38)),new W(24,new N(8,20),new N(4,21)),new W(22,new N(12,11),new N(4,12))),new Ie(14,Int32Array.from([6,26,46,66]),new W(30,new N(3,115),new N(1,116)),new W(24,new N(4,40),new N(5,41)),new W(20,new N(11,16),new N(5,17)),new W(24,new N(11,12),new N(5,13))),new Ie(15,Int32Array.from([6,26,48,70]),new W(22,new N(5,87),new N(1,88)),new W(24,new N(5,41),new N(5,42)),new W(30,new N(5,24),new N(7,25)),new W(24,new N(11,12),new N(7,13))),new Ie(16,Int32Array.from([6,26,50,74]),new W(24,new N(5,98),new N(1,99)),new W(28,new N(7,45),new N(3,46)),new W(24,new N(15,19),new N(2,20)),new W(30,new N(3,15),new N(13,16))),new Ie(17,Int32Array.from([6,30,54,78]),new W(28,new N(1,107),new N(5,108)),new W(28,new N(10,46),new N(1,47)),new W(28,new N(1,22),new N(15,23)),new W(28,new N(2,14),new N(17,15))),new Ie(18,Int32Array.from([6,30,56,82]),new W(30,new N(5,120),new N(1,121)),new W(26,new N(9,43),new N(4,44)),new W(28,new N(17,22),new N(1,23)),new W(28,new N(2,14),new N(19,15))),new Ie(19,Int32Array.from([6,30,58,86]),new W(28,new N(3,113),new N(4,114)),new W(26,new N(3,44),new N(11,45)),new W(26,new N(17,21),new N(4,22)),new W(26,new N(9,13),new N(16,14))),new Ie(20,Int32Array.from([6,34,62,90]),new W(28,new N(3,107),new N(5,108)),new W(26,new N(3,41),new N(13,42)),new W(30,new N(15,24),new N(5,25)),new W(28,new N(15,15),new N(10,16))),new Ie(21,Int32Array.from([6,28,50,72,94]),new W(28,new N(4,116),new N(4,117)),new W(26,new N(17,42)),new W(28,new N(17,22),new N(6,23)),new W(30,new N(19,16),new N(6,17))),new Ie(22,Int32Array.from([6,26,50,74,98]),new W(28,new N(2,111),new N(7,112)),new W(28,new N(17,46)),new W(30,new N(7,24),new N(16,25)),new W(24,new N(34,13))),new Ie(23,Int32Array.from([6,30,54,78,102]),new W(30,new N(4,121),new N(5,122)),new W(28,new N(4,47),new N(14,48)),new W(30,new N(11,24),new N(14,25)),new W(30,new N(16,15),new N(14,16))),new Ie(24,Int32Array.from([6,28,54,80,106]),new W(30,new N(6,117),new N(4,118)),new W(28,new N(6,45),new N(14,46)),new W(30,new N(11,24),new N(16,25)),new W(30,new N(30,16),new N(2,17))),new Ie(25,Int32Array.from([6,32,58,84,110]),new W(26,new N(8,106),new N(4,107)),new W(28,new N(8,47),new N(13,48)),new W(30,new N(7,24),new N(22,25)),new W(30,new N(22,15),new N(13,16))),new Ie(26,Int32Array.from([6,30,58,86,114]),new W(28,new N(10,114),new N(2,115)),new W(28,new N(19,46),new N(4,47)),new W(28,new N(28,22),new N(6,23)),new W(30,new N(33,16),new N(4,17))),new Ie(27,Int32Array.from([6,34,62,90,118]),new W(30,new N(8,122),new N(4,123)),new W(28,new N(22,45),new N(3,46)),new W(30,new N(8,23),new N(26,24)),new W(30,new N(12,15),new N(28,16))),new Ie(28,Int32Array.from([6,26,50,74,98,122]),new W(30,new N(3,117),new N(10,118)),new W(28,new N(3,45),new N(23,46)),new W(30,new N(4,24),new N(31,25)),new W(30,new N(11,15),new N(31,16))),new Ie(29,Int32Array.from([6,30,54,78,102,126]),new W(30,new N(7,116),new N(7,117)),new W(28,new N(21,45),new N(7,46)),new W(30,new N(1,23),new N(37,24)),new W(30,new N(19,15),new N(26,16))),new Ie(30,Int32Array.from([6,26,52,78,104,130]),new W(30,new N(5,115),new N(10,116)),new W(28,new N(19,47),new N(10,48)),new W(30,new N(15,24),new N(25,25)),new W(30,new N(23,15),new N(25,16))),new Ie(31,Int32Array.from([6,30,56,82,108,134]),new W(30,new N(13,115),new N(3,116)),new W(28,new N(2,46),new N(29,47)),new W(30,new N(42,24),new N(1,25)),new W(30,new N(23,15),new N(28,16))),new Ie(32,Int32Array.from([6,34,60,86,112,138]),new W(30,new N(17,115)),new W(28,new N(10,46),new N(23,47)),new W(30,new N(10,24),new N(35,25)),new W(30,new N(19,15),new N(35,16))),new Ie(33,Int32Array.from([6,30,58,86,114,142]),new W(30,new N(17,115),new N(1,116)),new W(28,new N(14,46),new N(21,47)),new W(30,new N(29,24),new N(19,25)),new W(30,new N(11,15),new N(46,16))),new Ie(34,Int32Array.from([6,34,62,90,118,146]),new W(30,new N(13,115),new N(6,116)),new W(28,new N(14,46),new N(23,47)),new W(30,new N(44,24),new N(7,25)),new W(30,new N(59,16),new N(1,17))),new Ie(35,Int32Array.from([6,30,54,78,102,126,150]),new W(30,new N(12,121),new N(7,122)),new W(28,new N(12,47),new N(26,48)),new W(30,new N(39,24),new N(14,25)),new W(30,new N(22,15),new N(41,16))),new Ie(36,Int32Array.from([6,24,50,76,102,128,154]),new W(30,new N(6,121),new N(14,122)),new W(28,new N(6,47),new N(34,48)),new W(30,new N(46,24),new N(10,25)),new W(30,new N(2,15),new N(64,16))),new Ie(37,Int32Array.from([6,28,54,80,106,132,158]),new W(30,new N(17,122),new N(4,123)),new W(28,new N(29,46),new N(14,47)),new W(30,new N(49,24),new N(10,25)),new W(30,new N(24,15),new N(46,16))),new Ie(38,Int32Array.from([6,32,58,84,110,136,162]),new W(30,new N(4,122),new N(18,123)),new W(28,new N(13,46),new N(32,47)),new W(30,new N(48,24),new N(14,25)),new W(30,new N(42,15),new N(32,16))),new Ie(39,Int32Array.from([6,26,54,82,110,138,166]),new W(30,new N(20,117),new N(4,118)),new W(28,new N(40,47),new N(7,48)),new W(30,new N(43,24),new N(22,25)),new W(30,new N(10,15),new N(67,16))),new Ie(40,Int32Array.from([6,30,58,86,114,142,170]),new W(30,new N(19,118),new N(6,119)),new W(28,new N(18,47),new N(31,48)),new W(30,new N(34,24),new N(34,25)),new W(30,new N(20,15),new N(61,16)))];var Lt;(function(b){b[b.DATA_MASK_000=0]="DATA_MASK_000",b[b.DATA_MASK_001=1]="DATA_MASK_001",b[b.DATA_MASK_010=2]="DATA_MASK_010",b[b.DATA_MASK_011=3]="DATA_MASK_011",b[b.DATA_MASK_100=4]="DATA_MASK_100",b[b.DATA_MASK_101=5]="DATA_MASK_101",b[b.DATA_MASK_110=6]="DATA_MASK_110",b[b.DATA_MASK_111=7]="DATA_MASK_111"})(Lt||(Lt={}));class pn{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)}}pn.values=new Map([[Lt.DATA_MASK_000,new pn(Lt.DATA_MASK_000,(b,e)=>(b+e&1)===0)],[Lt.DATA_MASK_001,new pn(Lt.DATA_MASK_001,(b,e)=>(b&1)===0)],[Lt.DATA_MASK_010,new pn(Lt.DATA_MASK_010,(b,e)=>e%3===0)],[Lt.DATA_MASK_011,new pn(Lt.DATA_MASK_011,(b,e)=>(b+e)%3===0)],[Lt.DATA_MASK_100,new pn(Lt.DATA_MASK_100,(b,e)=>(Math.floor(b/2)+Math.floor(e/3)&1)===0)],[Lt.DATA_MASK_101,new pn(Lt.DATA_MASK_101,(b,e)=>b*e%6===0)],[Lt.DATA_MASK_110,new pn(Lt.DATA_MASK_110,(b,e)=>b*e%6<3)],[Lt.DATA_MASK_111,new pn(Lt.DATA_MASK_111,(b,e)=>(b+e+b*e%3&1)===0)]]);class $u{constructor(e){const n=e.getHeight();if(n<21||(n&3)!==1)throw new z;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=Gt.decodeFormatInformation(e,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new z}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 Ie.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=Ie.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=Ie.decodeVersionInformation(i),a!==null&&a.getDimensionForVersion()===e)return this.parsedVersion=a,a;throw new z}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=pn.values.get(e.getDataMask()),s=this.bitMatrix.getHeight();i.unmaskBitMatrix(this.bitMatrix,s);const a=n.buildFunctionPattern();let l=!0;const d=new Uint8Array(n.getTotalCodewords());let h=0,p=0,y=0;for(let E=s-1;E>0;E-=2){E===6&&E--;for(let I=0;I<s;I++){const k=l?s-1-I:I;for(let L=0;L<2;L++)a.get(E-L,k)||(y++,p<<=1,this.bitMatrix.get(E-L,k)&&(p|=1),y===8&&(d[h++]=p,y=0,p=0))}l=!l}if(h!==n.getTotalCodewords())throw new z;return d}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,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 ji{constructor(e,n){this.numDataCodewords=e,this.codewords=n}static getDataBlocks(e,n,i){if(e.length!==n.getTotalCodewords())throw new v;const s=n.getECBlocksForLevel(i);let a=0;const l=s.getECBlocks();for(const L of l)a+=L.getCount();const d=new Array(a);let h=0;for(const L of l)for(let F=0;F<L.getCount();F++){const H=L.getDataCodewords(),Y=s.getECCodewordsPerBlock()+H;d[h++]=new ji(H,new Uint8Array(Y))}const p=d[0].codewords.length;let y=d.length-1;for(;y>=0&&d[y].codewords.length!==p;)y--;y++;const E=p-s.getECCodewordsPerBlock();let I=0;for(let L=0;L<E;L++)for(let F=0;F<h;F++)d[F].codewords[L]=e[I++];for(let L=y;L<h;L++)d[L].codewords[E]=e[I++];const k=d[0].codewords.length;for(let L=E;L<k;L++)for(let F=0;F<h;F++){const H=F<y?L:L+1;d[F].codewords[H]=e[I++]}return d}getNumDataCodewords(){return this.numDataCodewords}getCodewords(){return this.codewords}}var mn;(function(b){b[b.TERMINATOR=0]="TERMINATOR",b[b.NUMERIC=1]="NUMERIC",b[b.ALPHANUMERIC=2]="ALPHANUMERIC",b[b.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",b[b.BYTE=4]="BYTE",b[b.ECI=5]="ECI",b[b.KANJI=6]="KANJI",b[b.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",b[b.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",b[b.HANZI=9]="HANZI"})(mn||(mn={}));class Ne{constructor(e,n,i,s){this.value=e,this.stringValue=n,this.characterCountBitsForVersions=i,this.bits=s,Ne.FOR_BITS.set(s,this),Ne.FOR_VALUE.set(e,this)}static forBits(e){const n=Ne.FOR_BITS.get(e);if(n===void 0)throw new v;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 Ne))return!1;const n=e;return this.value===n.value}toString(){return this.stringValue}}Ne.FOR_BITS=new Map,Ne.FOR_VALUE=new Map,Ne.TERMINATOR=new Ne(mn.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),Ne.NUMERIC=new Ne(mn.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),Ne.ALPHANUMERIC=new Ne(mn.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),Ne.STRUCTURED_APPEND=new Ne(mn.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),Ne.BYTE=new Ne(mn.BYTE,"BYTE",Int32Array.from([8,16,16]),4),Ne.ECI=new Ne(mn.ECI,"ECI",Int32Array.from([0,0,0]),7),Ne.KANJI=new Ne(mn.KANJI,"KANJI",Int32Array.from([8,10,12]),8),Ne.FNC1_FIRST_POSITION=new Ne(mn.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),Ne.FNC1_SECOND_POSITION=new Ne(mn.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),Ne.HANZI=new Ne(mn.HANZI,"HANZI",Int32Array.from([8,10,12]),13);class wt{static decode(e,n,i,s){const a=new Wi(e);let l=new xe;const d=new Array;let h=-1,p=-1;try{let y=null,E=!1,I;do{if(a.available()<4)I=Ne.TERMINATOR;else{const k=a.readBits(4);I=Ne.forBits(k)}switch(I){case Ne.TERMINATOR:break;case Ne.FNC1_FIRST_POSITION:case Ne.FNC1_SECOND_POSITION:E=!0;break;case Ne.STRUCTURED_APPEND:if(a.available()<16)throw new z;h=a.readBits(8),p=a.readBits(8);break;case Ne.ECI:const k=wt.parseECIValue(a);if(y=S.getCharacterSetECIByValue(k),y===null)throw new z;break;case Ne.HANZI:const L=a.readBits(4),F=a.readBits(I.getCharacterCountBits(n));L===wt.GB2312_SUBSET&&wt.decodeHanziSegment(a,l,F);break;default:const H=a.readBits(I.getCharacterCountBits(n));switch(I){case Ne.NUMERIC:wt.decodeNumericSegment(a,l,H);break;case Ne.ALPHANUMERIC:wt.decodeAlphanumericSegment(a,l,H,E);break;case Ne.BYTE:wt.decodeByteSegment(a,l,H,y,d,s);break;case Ne.KANJI:wt.decodeKanjiSegment(a,l,H);break;default:throw new z}break}}while(I!==Ne.TERMINATOR)}catch{throw new z}return new Ht(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 z;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(ye.decode(s,re.GB2312))}catch(l){throw new z(l)}}static decodeKanjiSegment(e,n,i){if(i*13>e.available())throw new z;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(ye.decode(s,re.SHIFT_JIS))}catch(l){throw new z(l)}}static decodeByteSegment(e,n,i,s,a,l){if(8*i>e.available())throw new z;const d=new Uint8Array(i);for(let p=0;p<i;p++)d[p]=e.readBits(8);let h;s===null?h=re.guessEncoding(d,l):h=s.getName();try{n.append(ye.decode(d,h))}catch(p){throw new z(p)}a.push(d)}static toAlphaNumericChar(e){if(e>=wt.ALPHANUMERIC_CHARS.length)throw new z;return wt.ALPHANUMERIC_CHARS[e]}static decodeAlphanumericSegment(e,n,i,s){const a=n.length();for(;i>1;){if(e.available()<11)throw new z;const l=e.readBits(11);n.append(wt.toAlphaNumericChar(Math.floor(l/45))),n.append(wt.toAlphaNumericChar(l%45)),i-=2}if(i===1){if(e.available()<6)throw new z;n.append(wt.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 z;const s=e.readBits(10);if(s>=1e3)throw new z;n.append(wt.toAlphaNumericChar(Math.floor(s/100))),n.append(wt.toAlphaNumericChar(Math.floor(s/10)%10)),n.append(wt.toAlphaNumericChar(s%10)),i-=3}if(i===2){if(e.available()<7)throw new z;const s=e.readBits(7);if(s>=100)throw new z;n.append(wt.toAlphaNumericChar(Math.floor(s/10))),n.append(wt.toAlphaNumericChar(s%10))}else if(i===1){if(e.available()<4)throw new z;const s=e.readBits(4);if(s>=10)throw new z;n.append(wt.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 z}}wt.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",wt.GB2312_SUBSET=1;class ss{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 Hu{constructor(){this.rsDecoder=new In(be.QR_CODE_FIELD_256)}decodeBooleanArray(e,n){return this.decodeBitMatrix(Me.parseFromBooleanArray(e),n)}decodeBitMatrix(e,n){const i=new $u(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 ss(!0)),a}catch(a){throw s!==null?s:a}}decodeBitMatrixParser(e,n){const i=e.readVersion(),s=e.readFormatInformation().getErrorCorrectionLevel(),a=e.readCodewords(),l=ji.getDataBlocks(a,i,s);let d=0;for(const y of l)d+=y.getNumDataCodewords();const h=new Uint8Array(d);let p=0;for(const y of l){const E=y.getCodewords(),I=y.getNumDataCodewords();this.correctErrors(E,I);for(let k=0;k<I;k++)h[p++]=E[k]}return wt.decode(h,i,s,n)}correctErrors(e,n){const i=new Int32Array(e);try{this.rsDecoder.decode(i,e.length-n)}catch{throw new O}for(let s=0;s<n;s++)e[s]=i[s]}}class Gi extends ve{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 E=0;for(;y<s;){if(d.get(y,p))if(E===1)l[1]++;else if(E===2){if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,y);if(I!==null)return I}l[0]=l[2],l[1]=1,l[2]=0,E=1}else l[++E]++;else E===1&&E++,l[E]++;y++}if(this.foundPatternCross(l)){const I=this.handlePossibleCenter(l,p,s);if(I!==null)return I}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new $}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 ve{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 Wu{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 Ft{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(V.TRY_HARDER)!==void 0,i=e!=null&&e.get(V.PURE_BARCODE)!==void 0,s=this.image,a=s.getHeight(),l=s.getWidth();let d=Math.floor(3*a/(4*Ft.MAX_MODULES));(d<Ft.MIN_SKIP||n)&&(d=Ft.MIN_SKIP);let h=!1;const p=new Int32Array(5);for(let E=d-1;E<a&&!h;E+=d){p[0]=0,p[1]=0,p[2]=0,p[3]=0,p[4]=0;let I=0;for(let k=0;k<l;k++)if(s.get(k,E))(I&1)===1&&I++,p[I]++;else if((I&1)===0)if(I===4)if(Ft.foundPatternCross(p)){if(this.handlePossibleCenter(p,E,k,i)===!0)if(d=2,this.hasSkipped===!0)h=this.haveMultiplyConfirmedCenters();else{const F=this.findRowSkip();F>p[2]&&(E+=F-p[2]-d,k=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]++;Ft.foundPatternCross(p)&&this.handlePossibleCenter(p,E,l,i)===!0&&(d=p[0],this.hasSkipped&&(h=this.haveMultiplyConfirmedCenters()))}const y=this.selectBestPatterns();return ve.orderBestPatterns(y),new Wu(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&&Ft.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:Ft.foundPatternCross(d)?Ft.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:Ft.foundPatternCross(d)?Ft.centerFromEnd(d,h):NaN}handlePossibleCenter(e,n,i,s){const a=e[0]+e[1]+e[2]+e[3]+e[4];let l=Ft.centerFromEnd(e,i),d=this.crossCheckVertical(n,Math.floor(l),e[2],a);if(!isNaN(d)&&(l=this.crossCheckHorizontal(Math.floor(l),Math.floor(d),e[2],a),!isNaN(l)&&(!s||this.crossCheckDiagonal(Math.floor(d),Math.floor(l),e[2],a)))){const h=a/7;let p=!1;const y=this.possibleCenters;for(let E=0,I=y.length;E<I;E++){const k=y[E];if(k.aboutEquals(h,d,l)){y[E]=k.combineEstimate(d,l,h),p=!0;break}}if(!p){const E=new Xi(l,d,h);y.push(E),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(E)}return!0}return!1}findRowSkip(){if(this.possibleCenters.length<=1)return 0;let n=null;for(const i of this.possibleCenters)if(i.getCount()>=Ft.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()>=Ft.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 $;const n=this.possibleCenters;let i;if(e>3){let s=0,a=0;for(const h of this.possibleCenters){const p=h.getEstimatedModuleSize();s+=p,a+=p*p}i=s/e;let l=Math.sqrt(a/e-i*i);n.sort((h,p)=>{const y=Math.abs(p.getEstimatedModuleSize()-i),E=Math.abs(h.getEstimatedModuleSize()-i);return y<E?-1:y>E?1:0});const d=Math.max(.2*i,l);for(let h=0;h<n.length&&n.length>3;h++){const p=n[h];Math.abs(p.getEstimatedModuleSize()-i)>d&&(n.splice(h,1),h--)}}if(n.length>3){let s=0;for(const a of n)s+=a.getEstimatedModuleSize();i=s/n.length,n.sort((a,l)=>{if(l.getCount()===a.getCount()){const d=Math.abs(l.getEstimatedModuleSize()-i),h=Math.abs(a.getEstimatedModuleSize()-i);return d<h?1:d>h?-1:0}else return l.getCount()-a.getCount()}),n.splice(3)}return[n[0],n[1],n[2]]}}Ft.CENTER_QUORUM=2,Ft.MIN_SKIP=3,Ft.MAX_MODULES=57;class kr{constructor(e){this.image=e}getImage(){return this.image}getResultPointCallback(){return this.resultPointCallback}detect(e){this.resultPointCallback=e==null?null:e.get(V.NEED_RESULT_POINT_CALLBACK);const i=new Ft(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 $("No pattern found in proccess finder.");const l=kr.computeDimension(n,i,s,a),d=Ie.getProvisionalVersionForDimension(l),h=d.getDimensionForVersion()-7;let p=null;if(d.getAlignmentPatternCenters().length>0){const k=i.getX()-n.getX()+s.getX(),L=i.getY()-n.getY()+s.getY(),F=1-3/h,H=Math.floor(n.getX()+F*(k-n.getX())),Y=Math.floor(n.getY()+F*(L-n.getY()));for(let le=4;le<=16;le<<=1)try{p=this.findAlignmentInRegion(a,H,Y,le);break}catch(ce){if(!(ce instanceof $))throw ce}}const y=kr.createTransform(n,i,s,p,l),E=kr.sampleGrid(this.image,y,l);let I;return p===null?I=[s,n,i]:I=[s,n,i,p],new Bn(E,I)}static createTransform(e,n,i,s,a){const l=a-3.5;let d,h,p,y;return s!==null?(d=s.getX(),h=s.getY(),p=l-3,y=p):(d=n.getX()-e.getX()+i.getX(),h=n.getY()-e.getY()+i.getY(),p=l,y=l),Bt.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 R.getInstance().sampleGridWithTransform(e,i,i,n)}static computeDimension(e,n,i,s){const a=Ze.round(ve.distance(e,n)/s),l=Ze.round(ve.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 $("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 k=e;e=n,n=k,k=i,i=s,s=k}const l=Math.abs(i-e),d=Math.abs(s-n);let h=-l/2;const p=e<i?1:-1,y=n<s?1:-1;let E=0;const I=i+p;for(let k=e,L=n;k!==I;k+=p){const F=a?L:k,H=a?k:L;if(E===1===this.image.get(F,H)){if(E===2)return Ze.distance(k,L,e,n);E++}if(h+=d,h>0){if(L===s)break;L+=y,h-=l}}return E===2?Ze.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 $("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 $("Alignment bottom exceeds estimated module size.");return new ci(this.image,l,h,d-l,p-h,e,this.resultPointCallback).find()}}class Xn{constructor(){this.decoder=new Hu}getDecoder(){return this.decoder}decode(e,n){let i,s;if(n!=null&&n.get(V.PURE_BARCODE)!==void 0){const h=Xn.extractPureBits(e.getBlackMatrix());i=this.decoder.decodeBitMatrix(h,n),s=Xn.NO_POINTS}else{const h=new kr(e.getBlackMatrix()).detect(n);i=this.decoder.decodeBitMatrix(h.getBits(),n),s=h.getPoints()}i.getOther()instanceof ss&&i.getOther().applyMirroredCorrection(s);const a=new Ee(i.getText(),i.getRawBytes(),void 0,s,Ce.QR_CODE,void 0),l=i.getByteSegments();l!==null&&a.putMetadata(Ue.BYTE_SEGMENTS,l);const d=i.getECLevel();return d!==null&&a.putMetadata(Ue.ERROR_CORRECTION_LEVEL,d),i.hasStructuredAppend()&&(a.putMetadata(Ue.STRUCTURED_APPEND_SEQUENCE,i.getStructuredAppendSequenceNumber()),a.putMetadata(Ue.STRUCTURED_APPEND_PARITY,i.getStructuredAppendParity())),a}reset(){}static extractPureBits(e){const n=e.getTopLeftOnBit(),i=e.getBottomRightOnBit();if(n===null||i===null)throw new $;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 $;if(l-a!==h-d&&(h=d+(l-a),h>=e.getWidth()))throw new $;const p=Math.round((h-d+1)/s),y=Math.round((l-a+1)/s);if(p<=0||y<=0)throw new $;if(y!==p)throw new $;const E=Math.floor(s/2);a+=E,d+=E;const I=d+Math.floor((p-1)*s)-h;if(I>0){if(I>E)throw new $;d-=I}const k=a+Math.floor((y-1)*s)-l;if(k>0){if(k>E)throw new $;a-=k}const L=new Me(p,y);for(let F=0;F<y;F++){const H=a+Math.floor(F*s);for(let Y=0;Y<p;Y++)e.get(d+Math.floor(Y*s),H)&&L.set(Y,F)}return L}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 $;return(a-e[0])/7}}Xn.NO_POINTS=new Array;class De{PDF417Common(){}static getBitCountSum(e){return Ze.sum(e)}static toIntArray(e){if(e==null||!e.length)return De.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(De.SYMBOL_TABLE,e&262143);return n<0?-1:(De.CODEWORD_TABLE[n]-1)%De.NUMBER_OF_CODEWORDS}}De.NUMBER_OF_CODEWORDS=929,De.MAX_CODEWORDS_IN_BARCODE=De.NUMBER_OF_CODEWORDS-1,De.MIN_ROWS_IN_BARCODE=3,De.MAX_ROWS_IN_BARCODE=90,De.MODULES_IN_CODEWORD=17,De.MODULES_IN_STOP_PATTERN=18,De.BARS_IN_MODULE=8,De.EMPTY_INT_ARRAY=new Int32Array([]),De.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]),De.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 ju{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 ju(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 E=ze.findGuardPattern(e,a,s,i,!1,l,p);if(E!=null){for(;s>0;){const I=ze.findGuardPattern(e,a,--s,i,!1,l,p);if(I!=null)E=I;else{s++;break}}d[0]=new ve(E[0],s),d[1]=new ve(E[1],s),h=!0;break}}let y=s+1;if(h){let E=0,I=Int32Array.from([Math.trunc(d[0].getX()),Math.trunc(d[1].getX())]);for(;y<n;y++){const k=ze.findGuardPattern(e,I[0],y,i,!1,l,p);if(k!=null&&Math.abs(I[0]-k[0])<ze.MAX_PATTERN_DRIFT&&Math.abs(I[1]-k[1])<ze.MAX_PATTERN_DRIFT)I=k,E=0;else{if(E>ze.SKIPPED_ROW_COUNT_MAX)break;E++}}y-=E+1,d[2]=new ve(I[0],y),d[3]=new ve(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,E=0,I=l.length;for(let k=a;y<s;y++)if(e.get(y,i)!==k)d[E]++;else{if(E===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],D.arraycopy(d,2,d,0,E-1),d[E-1]=0,d[E]=0,E--}else E++;d[E]=1,k=!k}return E===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],E=n[p]*d,I=y>E?y-E:E-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 Vt{constructor(e,n){if(n.length===0)throw new v;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),D.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 v("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;D.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 Vt(this.field,s)}subtract(e){if(!this.field.equals(e.field))throw new v("ModulusPolys do not have same ModulusGF field");return e.isZero()?this:this.add(e.negative())}multiply(e){return e instanceof Vt?this.multiplyOther(e):this.multiplyScalar(e)}multiplyOther(e){if(!this.field.equals(e.field))throw new v("ModulusPolys do not have same ModulusGF field");if(this.isZero()||e.isZero())return new Vt(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 Vt(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 Vt(this.field,n)}multiplyScalar(e){if(e===0)return new Vt(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 Vt(this.field,i)}multiplyByMonomial(e,n){if(e<0)throw new v;if(n===0)return new Vt(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 Vt(this.field,s)}toString(){let e=new xe;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 Gu{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 v;return this.logTable[e]}inverse(e){if(e===0)throw new yt;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 Gu{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 Vt(this,new Int32Array([0])),this.one=new Vt(this,new Int32Array([1]))}getZero(){return this.zero}getOne(){return this.one}buildMonomial(e,n){if(e<0)throw new v;if(n===0)return this.zero;let i=new Int32Array(e+1);return i[0]=n,new Vt(this,i)}}qi.PDF417_GF=new qi(De.NUMBER_OF_CODEWORDS,3);class as{constructor(){this.field=qi.PDF417_GF}decode(e,n,i){let s=new Vt(this.field,e),a=new Int32Array(n),l=!1;for(let L=n;L>0;L--){let F=s.evaluateAt(this.field.exp(L));a[n-L]=F,F!==0&&(l=!0)}if(!l)return 0;let d=this.field.getOne();if(i!=null)for(const L of i){let F=this.field.exp(e.length-1-L),H=new Vt(this.field,new Int32Array([this.field.subtract(0,F),1]));d=d.multiply(H)}let h=new Vt(this.field,a),p=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),h,n),y=p[0],E=p[1],I=this.findErrorLocations(y),k=this.findErrorMagnitudes(E,y,I);for(let L=0;L<I.length;L++){let F=e.length-1-this.field.log(I[L]);if(F<0)throw O.getChecksumInstance();e[F]=this.field.subtract(e[F],k[L])}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,k=l;if(s=a,l=d,s.isZero())throw O.getChecksumInstance();a=I;let L=this.field.getZero(),F=s.getCoefficient(s.getDegree()),H=this.field.inverse(F);for(;a.getDegree()>=s.getDegree()&&!a.isZero();){let Y=a.getDegree()-s.getDegree(),le=this.field.multiply(a.getCoefficient(a.getDegree()),H);L=L.add(this.field.buildMonomial(Y,le)),a=a.subtract(s.multiplyByMonomial(Y,le))}d=L.multiply(l).subtract(k).negative()}let h=d.getCoefficient(0);if(h===0)throw O.getChecksumInstance();let p=this.field.inverse(h),y=d.multiply(p),E=a.multiply(p);return[y,E]}findErrorLocations(e){let n=e.getDegree(),i=new Int32Array(n),s=0;for(let a=1;a<this.field.getSize()&&s<n;a++)e.evaluateAt(a)===0&&(i[s]=this.field.inverse(a),s++);if(s!==n)throw O.getChecksumInstance();return i}findErrorMagnitudes(e,n,i){let s=n.getDegree(),a=new Int32Array(s);for(let p=1;p<=s;p++)a[s-p]=this.field.multiply(p,n.getCoefficient(p));let l=new Vt(this.field,a),d=i.length,h=new Int32Array(d);for(let p=0;p<d;p++){let y=this.field.inverse(i[p]),E=this.field.subtract(0,e.evaluateAt(y)),I=this.field.inverse(l.evaluateAt(y));h[p]=this.field.multiply(E,I)}return h}}class sr{constructor(e,n,i,s,a){e instanceof sr?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 $;l?(n=new ve(0,s.getY()),i=new ve(0,a.getY())):d&&(s=new ve(e.getWidth()-1,n.getY()),a=new ve(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 sr(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 ve(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 ve(h.getX(),p);i?a=y:d=y}return new sr(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 Xu{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 Rr{constructor(){this.buffer=""}static form(e,n){let i=-1;function s(l,d,h,p,y,E){if(l==="%%")return"%";if(n[++i]===void 0)return;l=p?parseInt(p.substr(1)):void 0;let I=y?parseInt(y.substr(1)):void 0,k;switch(E){case"s":k=n[i];break;case"c":k=n[i][0];break;case"f":k=parseFloat(n[i]).toFixed(l);break;case"p":k=parseFloat(n[i]).toPrecision(l);break;case"e":k=parseFloat(n[i]).toExponential(l);break;case"x":k=parseInt(n[i]).toString(I||16);break;case"d":k=parseFloat(parseInt(n[i],I||10).toPrecision(l)).toFixed(0);break}k=typeof k=="object"?JSON.stringify(k):(+k).toString(I);let L=parseInt(h),F=h&&h[0]+""=="0"?"0":" ";for(;k.length<L;)k=d!==void 0?k+F:F+k;return k}let a=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return e.replace(a,s)}format(e,...n){this.buffer+=Rr.form(e,n)}toString(){return this.buffer}}class Mr{constructor(e){this.boundingBox=new sr(e),this.codewords=new Array(e.getMaxY()-e.getMinY()+1)}getCodewordNearby(e){let n=this.getCodeword(e);if(n!=null)return n;for(let i=1;i<Mr.MAX_NEARBY_DISTANCE;i++){let s=this.imageRowToCodewordIndex(e)-i;if(s>=0&&(n=this.codewords[s],n!=null)||(s=this.imageRowToCodewordIndex(e)+i,s<this.codewords.length&&(n=this.codewords[s],n!=null)))return n}return null}imageRowToCodewordIndex(e){return e-this.boundingBox.getMinY()}setCodeword(e,n){this.codewords[this.imageRowToCodewordIndex(e)]=n}getCodeword(e){return this.codewords[this.imageRowToCodewordIndex(e)]}getBoundingBox(){return this.boundingBox}getCodewords(){return this.codewords}toString(){const e=new Rr;let n=0;for(const i of this.codewords){if(i==null){e.format("%3d: | %n",n++);continue}e.format("%3d: %3d|%3d%n",n++,i.getRowNumber(),i.getValue())}return e.toString()}}Mr.MAX_NEARBY_DISTANCE=5;class Dr{constructor(){this.values=new Map}setValue(e){e=Math.trunc(e);let n=this.values.get(e);n==null&&(n=0),n++,this.values.set(e,n)}getValue(){let e=-1,n=new Array;for(const[i,s]of this.values.entries()){const a={getKey:()=>i,getValue:()=>s};a.getValue()>e?(e=a.getValue(),n=[],n.push(a.getKey())):a.getValue()===e&&n.push(a.getKey())}return De.toIntArray(n)}getConfidence(e){return this.values.get(e)}}class ls extends Mr{constructor(e,n){super(e),this._isLeft=n}setRowNumbers(){for(let e of this.getCodewords())e?.setRowNumberAsRowIndicatorColumn()}adjustCompleteIndicatorColumnRowNumbers(e){let n=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(n,e);let i=this.getBoundingBox(),s=this._isLeft?i.getTopLeft():i.getTopRight(),a=this._isLeft?i.getBottomLeft():i.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.imageRowToCodewordIndex(Math.trunc(a.getY())),h=-1,p=1,y=0;for(let E=l;E<d;E++){if(n[E]==null)continue;let I=n[E],k=I.getRowNumber()-h;if(k===0)y++;else if(k===1)p=Math.max(p,y),y=1,h=I.getRowNumber();else if(k<0||I.getRowNumber()>=e.getRowCount()||k>E)n[E]=null;else{let L;p>2?L=(p-2)*k:L=k;let F=L>=E;for(let H=1;H<=L&&!F;H++)F=n[E-H]!=null;F?n[E]=null:(h=I.getRowNumber(),y=1)}}}getRowHeights(){let e=this.getBarcodeMetadata();if(e==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(e);let n=new Int32Array(e.getRowCount());for(let i of this.getCodewords())if(i!=null){let s=i.getRowNumber();if(s>=n.length)continue;n[s]++}return n}adjustIncompleteIndicatorColumnRowNumbers(e){let n=this.getBoundingBox(),i=this._isLeft?n.getTopLeft():n.getTopRight(),s=this._isLeft?n.getBottomLeft():n.getBottomRight(),a=this.imageRowToCodewordIndex(Math.trunc(i.getY())),l=this.imageRowToCodewordIndex(Math.trunc(s.getY())),d=this.getCodewords(),h=-1;for(let p=a;p<l;p++){if(d[p]==null)continue;let y=d[p];y.setRowNumberAsRowIndicatorColumn();let E=y.getRowNumber()-h;E===0||(E===1?h=y.getRowNumber():y.getRowNumber()>=e.getRowCount()?d[p]=null:h=y.getRowNumber())}}getBarcodeMetadata(){let e=this.getCodewords(),n=new Dr,i=new Dr,s=new Dr,a=new Dr;for(let d of e){if(d==null)continue;d.setRowNumberAsRowIndicatorColumn();let h=d.getValue()%30,p=d.getRowNumber();switch(this._isLeft||(p+=2),p%3){case 0:i.setValue(h*3+1);break;case 1:a.setValue(h/3),s.setValue(h%3);break;case 2:n.setValue(h+1);break}}if(n.getValue().length===0||i.getValue().length===0||s.getValue().length===0||a.getValue().length===0||n.getValue()[0]<1||i.getValue()[0]+s.getValue()[0]<De.MIN_ROWS_IN_BARCODE||i.getValue()[0]+s.getValue()[0]>De.MAX_ROWS_IN_BARCODE)return null;let l=new Xu(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+`
|
|
63
|
+
`+super.toString()}}class Pr{constructor(e,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=e,this.barcodeColumnCount=e.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let e=De.MAX_CODEWORDS_IN_BARCODE,n;do n=e,e=this.adjustRowNumbersAndGetCount();while(e>0&&e<n);return this.detectionResultColumns}adjustIndicatorColumnRowNumbers(e){e?.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)}adjustRowNumbersAndGetCount(){let e=this.adjustRowNumbersByRow();if(e===0)return 0;for(let n=1;n<this.barcodeColumnCount+1;n++){let i=this.detectionResultColumns[n].getCodewords();for(let s=0;s<i.length;s++)i[s]!=null&&(i[s].hasValidRowNumber()||this.adjustRowNumbers(n,s,i))}return e}adjustRowNumbersByRow(){return this.adjustRowNumbersFromBothRI(),this.adjustRowNumbersFromLRI()+this.adjustRowNumbersFromRRI()}adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)return;let e=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<e.length;i++)if(e[i]!=null&&n[i]!=null&&e[i].getRowNumber()===n[i].getRowNumber())for(let s=1;s<=this.barcodeColumnCount;s++){let a=this.detectionResultColumns[s].getCodewords()[i];a!=null&&(a.setRowNumber(e[i].getRowNumber()),a.hasValidRowNumber()||(this.detectionResultColumns[s].getCodewords()[i]=null))}}adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;let e=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=this.barcodeColumnCount+1;l>0&&a<this.ADJUST_ROW_NUMBER_SKIP;l--){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null)return 0;let e=0,n=this.detectionResultColumns[0].getCodewords();for(let i=0;i<n.length;i++){if(n[i]==null)continue;let s=n[i].getRowNumber(),a=0;for(let l=1;l<this.barcodeColumnCount+1&&a<this.ADJUST_ROW_NUMBER_SKIP;l++){let d=this.detectionResultColumns[l].getCodewords()[i];d!=null&&(a=Pr.adjustRowNumberIfValid(s,a,d),d.hasValidRowNumber()||e++)}}return e}static adjustRowNumberIfValid(e,n,i){return i==null||i.hasValidRowNumber()||(i.isValidRowNumber(e)?(i.setRowNumber(e),n=0):++n),n}adjustRowNumbers(e,n,i){if(!this.detectionResultColumns[e-1])return;let s=i[n],a=this.detectionResultColumns[e-1].getCodewords(),l=a;this.detectionResultColumns[e+1]!=null&&(l=this.detectionResultColumns[e+1].getCodewords());let d=new Array(14);d[2]=a[n],d[3]=l[n],n>0&&(d[0]=i[n-1],d[4]=a[n-1],d[5]=l[n-1]),n>1&&(d[8]=i[n-2],d[10]=a[n-2],d[11]=l[n-2]),n<i.length-1&&(d[1]=i[n+1],d[6]=a[n+1],d[7]=l[n+1]),n<i.length-2&&(d[9]=i[n+2],d[12]=a[n+2],d[13]=l[n+2]);for(let h of d)if(Pr.adjustRowNumber(s,h))return}static adjustRowNumber(e,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===e.getBucket()?(e.setRowNumber(n.getRowNumber()),!0):!1}getBarcodeColumnCount(){return this.barcodeColumnCount}getBarcodeRowCount(){return this.barcodeMetadata.getRowCount()}getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel()}setBoundingBox(e){this.boundingBox=e}getBoundingBox(){return this.boundingBox}setDetectionResultColumn(e,n){this.detectionResultColumns[e]=n}getDetectionResultColumn(e){return this.detectionResultColumns[e]}toString(){let e=this.detectionResultColumns[0];e==null&&(e=this.detectionResultColumns[this.barcodeColumnCount+1]);let n=new Rr;for(let i=0;i<e.getCodewords().length;i++){n.format("CW %3d:",i);for(let s=0;s<this.barcodeColumnCount+2;s++){if(this.detectionResultColumns[s]==null){n.format(" | ");continue}let a=this.detectionResultColumns[s].getCodewords()[i];if(a==null){n.format(" | ");continue}n.format(" %3d|%3d",a.getRowNumber(),a.getValue())}n.format("%n")}return n.toString()}}class Br{constructor(e,n,i,s){this.rowNumber=Br.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(e),this.endX=Math.trunc(n),this.bucket=Math.trunc(i),this.value=Math.trunc(s)}hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber)}isValidRowNumber(e){return e!==Br.BARCODE_ROW_UNKNOWN&&this.bucket===e%3*3}setRowNumberAsRowIndicatorColumn(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))}getWidth(){return this.endX-this.startX}getStartX(){return this.startX}getEndX(){return this.endX}getBucket(){return this.bucket}getValue(){return this.value}getRowNumber(){return this.rowNumber}setRowNumber(e){this.rowNumber=e}toString(){return this.rowNumber+"|"+this.value}}Br.BARCODE_ROW_UNKNOWN=-1;class tn{static initialize(){for(let e=0;e<De.SYMBOL_TABLE.length;e++){let n=De.SYMBOL_TABLE[e],i=n&1;for(let s=0;s<De.BARS_IN_MODULE;s++){let a=0;for(;(n&1)===i;)a+=1,n>>=1;i=n&1,tn.RATIOS_TABLE[e]||(tn.RATIOS_TABLE[e]=new Array(De.BARS_IN_MODULE)),tn.RATIOS_TABLE[e][De.BARS_IN_MODULE-s-1]=Math.fround(a/De.MODULES_IN_CODEWORD)}}this.bSymbolTableReady=!0}static getDecodedValue(e){let n=tn.getDecodedCodewordValue(tn.sampleBitCounts(e));return n!==-1?n:tn.getClosestDecodedValue(e)}static sampleBitCounts(e){let n=Ze.sum(e),i=new Int32Array(De.BARS_IN_MODULE),s=0,a=0;for(let l=0;l<De.MODULES_IN_CODEWORD;l++){let d=n/(2*De.MODULES_IN_CODEWORD)+l*n/De.MODULES_IN_CODEWORD;a+e[s]<=d&&(a+=e[s],s++),i[s]++}return i}static getDecodedCodewordValue(e){let n=tn.getBitValue(e);return De.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=Ze.sum(e),i=new Array(De.BARS_IN_MODULE);if(n>1)for(let l=0;l<i.length;l++)i[l]=Math.fround(e[l]/n);let s=Sn.MAX_VALUE,a=-1;this.bSymbolTableReady||tn.initialize();for(let l=0;l<tn.RATIOS_TABLE.length;l++){let d=0,h=tn.RATIOS_TABLE[l];for(let p=0;p<De.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=De.SYMBOL_TABLE[l])}return a}}tn.bSymbolTableReady=!1,tn.RATIOS_TABLE=new Array(De.SYMBOL_TABLE.length).map(b=>new Array(De.BARS_IN_MODULE));class cs{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 us{static parseLong(e,n=void 0){return parseInt(e,n)}}class ds extends x{}ds.kind="NullPointerException";class qu{writeBytes(e){this.writeBytesOffset(e,0,e.length)}writeBytesOffset(e,n,i){if(e==null)throw new ds;if(n<0||n>e.length||i<0||n+i>e.length||n+i<0)throw new B;if(i===0)return;for(let s=0;s<i;s++)this.write(e[n+s])}flush(){}close(){}}class Yu extends x{}class Ku extends qu{constructor(e=32){if(super(),this.count=0,e<0)throw new v("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 Yu;i=U.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 B;this.ensureCapacity(this.count+i),D.arraycopy(e,n,this.buf,this.count,i),this.count+=i}writeTo(e){e.writeBytesOffset(this.buf,0,this.count)}reset(){this.count=0}toByteArray(){return Z.copyOfUint8Array(this.buf,this.count)}size(){return this.count}toString(e){return e?typeof e=="string"?this.toString_string(e):this.toString_number(e):this.toString_void()}toString_void(){return new String(this.buf).toString()}toString_string(e){return new String(this.buf).toString()}toString_number(e){return new String(this.buf).toString()}close(){}}var it;(function(b){b[b.ALPHA=0]="ALPHA",b[b.LOWER=1]="LOWER",b[b.MIXED=2]="MIXED",b[b.PUNCT=3]="PUNCT",b[b.ALPHA_SHIFT=4]="ALPHA_SHIFT",b[b.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(it||(it={}));function fs(){if(typeof window<"u")return window.BigInt||null;if(typeof Ei<"u")return Ei.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}let ui;function qn(b){if(typeof ui>"u"&&(ui=fs()),ui===null)throw new Error("BigInt is not supported!");return ui(b)}function Ju(){let b=[];b[0]=qn(1);let e=qn(900);b[1]=e;for(let n=2;n<16;n++)b[n]=b[n-1]*e;return b}class q{static decode(e,n){let i=new xe(""),s=S.ISO8859_1;i.enableDecoding(s);let a=1,l=e[a++],d=new cs;for(;a<e[0];){switch(l){case q.TEXT_COMPACTION_MODE_LATCH:a=q.textCompaction(e,a,i);break;case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:a=q.byteCompaction(l,e,s,a,i);break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:i.append(e[a++]);break;case q.NUMERIC_COMPACTION_MODE_LATCH:a=q.numericCompaction(e,a,i);break;case q.ECI_CHARSET:S.getCharacterSetECIByValue(e[a++]);break;case q.ECI_GENERAL_PURPOSE:a+=2;break;case q.ECI_USER_DEFINED:a++;break;case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:a=q.decodeMacroBlock(e,a,d);break;case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:throw new z;default:a--,a=q.textCompaction(e,a,i);break}if(a<e.length)l=e[a++];else throw z.getFormatInstance()}if(i.length()===0)throw z.getFormatInstance();let h=new Ht(null,i.toString(),null,n);return h.setOther(d),h}static decodeMacroBlock(e,n,i){if(n+q.NUMBER_OF_SEQUENCE_CODEWORDS>e[0])throw z.getFormatInstance();let s=new Int32Array(q.NUMBER_OF_SEQUENCE_CODEWORDS);for(let d=0;d<q.NUMBER_OF_SEQUENCE_CODEWORDS;d++,n++)s[d]=e[n];i.setSegmentIndex(U.parseInt(q.decodeBase900toBase10(s,q.NUMBER_OF_SEQUENCE_CODEWORDS)));let a=new xe;n=q.textCompaction(e,n,a),i.setFileId(a.toString());let l=-1;for(e[n]===q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<e[0];)switch(e[n]){case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,e[n]){case q.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let d=new xe;n=q.textCompaction(e,n+1,d),i.setFileName(d.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let h=new xe;n=q.textCompaction(e,n+1,h),i.setSender(h.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let p=new xe;n=q.textCompaction(e,n+1,p),i.setAddressee(p.toString());break;case q.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let y=new xe;n=q.numericCompaction(e,n+1,y),i.setSegmentCount(U.parseInt(y.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let E=new xe;n=q.numericCompaction(e,n+1,E),i.setTimestamp(us.parseLong(E.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let I=new xe;n=q.numericCompaction(e,n+1,I),i.setChecksum(U.parseInt(I.toString()));break;case q.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let k=new xe;n=q.numericCompaction(e,n+1,k),i.setFileSize(us.parseLong(k.toString()));break;default:throw z.getFormatInstance()}break;case q.MACRO_PDF417_TERMINATOR:n++,i.setLastSegment(!0);break;default:throw z.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<q.TEXT_COMPACTION_MODE_LATCH)s[l]=h/30,s[l+1]=h%30,l+=2;else switch(h){case q.TEXT_COMPACTION_MODE_LATCH:s[l++]=q.TEXT_COMPACTION_MODE_LATCH;break;case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:n--,d=!0;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s[l]=q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,h=e[n++],a[l]=h,l++;break}}return q.decodeTextCompaction(s,a,l,i),n}static decodeTextCompaction(e,n,i,s){let a=it.ALPHA,l=it.ALPHA,d=0;for(;d<i;){let h=e[d],p="";switch(a){case it.ALPHA:if(h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case q.LL:a=it.LOWER;break;case q.ML:a=it.MIXED;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.LOWER:if(h<26)p=String.fromCharCode(97+h);else switch(h){case 26:p=" ";break;case q.AS:l=a,a=it.ALPHA_SHIFT;break;case q.ML:a=it.MIXED;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.MIXED:if(h<q.PL)p=q.MIXED_CHARS[h];else switch(h){case q.PL:a=it.PUNCT;break;case 26:p=" ";break;case q.LL:a=it.LOWER;break;case q.AL:a=it.ALPHA;break;case q.PS:l=a,a=it.PUNCT_SHIFT;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT:if(h<q.PAL)p=q.PUNCT_CHARS[h];else switch(h){case q.PAL:a=it.ALPHA;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.ALPHA_SHIFT:if(a=l,h<26)p=String.fromCharCode(65+h);else switch(h){case 26:p=" ";break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break;case it.PUNCT_SHIFT:if(a=l,h<q.PAL)p=q.PUNCT_CHARS[h];else switch(h){case q.PAL:a=it.ALPHA;break;case q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:s.append(n[d]);break;case q.TEXT_COMPACTION_MODE_LATCH:a=it.ALPHA;break}break}p!==""&&s.append(p),d++}}static byteCompaction(e,n,i,s,a){let l=new Ku,d=0,h=0,p=!1;switch(e){case q.BYTE_COMPACTION_MODE_LATCH:let y=new Int32Array(6),E=n[s++];for(;s<n[0]&&!p;)switch(y[d++]=E,h=900*h+E,E=n[s++],E){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:s--,p=!0;break;default:if(d%5===0&&d>0){for(let I=0;I<6;++I)l.write(Number(qn(h)>>qn(8*(5-I))));h=0,d=0}break}s===n[0]&&E<q.TEXT_COMPACTION_MODE_LATCH&&(y[d++]=E);for(let I=0;I<d;I++)l.write(y[I]);break;case q.BYTE_COMPACTION_MODE_LATCH_6:for(;s<n[0]&&!p;){let I=n[s++];if(I<q.TEXT_COMPACTION_MODE_LATCH)d++,h=900*h+I;else switch(I){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.NUMERIC_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:s--,p=!0;break}if(d%5===0&&d>0){for(let k=0;k<6;++k)l.write(Number(qn(h)>>qn(8*(5-k))));h=0,d=0}}break}return a.append(ye.decode(l.toByteArray(),i)),s}static numericCompaction(e,n,i){let s=0,a=!1,l=new Int32Array(q.MAX_NUMERIC_CODEWORDS);for(;n<e[0]&&!a;){let d=e[n++];if(n===e[0]&&(a=!0),d<q.TEXT_COMPACTION_MODE_LATCH)l[s]=d,s++;else switch(d){case q.TEXT_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH:case q.BYTE_COMPACTION_MODE_LATCH_6:case q.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case q.MACRO_PDF417_TERMINATOR:n--,a=!0;break}(s%q.MAX_NUMERIC_CODEWORDS===0||d===q.NUMERIC_COMPACTION_MODE_LATCH||a)&&s>0&&(i.append(q.decodeBase900toBase10(l,s)),s=0)}return n}static decodeBase900toBase10(e,n){let i=qn(0);for(let a=0;a<n;a++)i+=q.EXP900[n-a-1]*qn(e[a]);let s=i.toString();if(s.charAt(0)!=="1")throw new z;return s.substring(1)}}q.TEXT_COMPACTION_MODE_LATCH=900,q.BYTE_COMPACTION_MODE_LATCH=901,q.NUMERIC_COMPACTION_MODE_LATCH=902,q.BYTE_COMPACTION_MODE_LATCH_6=924,q.ECI_USER_DEFINED=925,q.ECI_GENERAL_PURPOSE=926,q.ECI_CHARSET=927,q.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,q.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,q.MACRO_PDF417_TERMINATOR=922,q.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,q.MAX_NUMERIC_CODEWORDS=15,q.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,q.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,q.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,q.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,q.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,q.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,q.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,q.PL=25,q.LL=27,q.AS=27,q.ML=28,q.AL=28,q.PS=29,q.PAL=29,q.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,:
|
|
64
|
+
-.$/"|*()?{}'`,q.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",q.EXP900=fs()?Ju():[],q.NUMBER_OF_SEQUENCE_CODEWORDS=2;class Ve{constructor(){}static decode(e,n,i,s,a,l,d){let h=new sr(e,n,i,s,a),p=null,y=null,E;for(let L=!0;;L=!1){if(n!=null&&(p=Ve.getRowIndicatorColumn(e,h,n,!0,l,d)),s!=null&&(y=Ve.getRowIndicatorColumn(e,h,s,!1,l,d)),E=Ve.merge(p,y),E==null)throw $.getNotFoundInstance();let F=E.getBoundingBox();if(L&&F!=null&&(F.getMinY()<h.getMinY()||F.getMaxY()>h.getMaxY()))h=F;else break}E.setBoundingBox(h);let I=E.getBarcodeColumnCount()+1;E.setDetectionResultColumn(0,p),E.setDetectionResultColumn(I,y);let k=p!=null;for(let L=1;L<=I;L++){let F=k?L:I-L;if(E.getDetectionResultColumn(F)!==void 0)continue;let H;F===0||F===I?H=new ls(h,F===0):H=new Mr(h),E.setDetectionResultColumn(F,H);let Y=-1,le=Y;for(let ce=h.getMinY();ce<=h.getMaxY();ce++){if(Y=Ve.getStartColumn(E,F,ce,k),Y<0||Y>h.getMaxX()){if(le===-1)continue;Y=le}let ae=Ve.detectCodeword(e,h.getMinX(),h.getMaxX(),k,Y,ce,l,d);ae!=null&&(H.setCodeword(ce,ae),le=Y,l=Math.min(l,ae.getWidth()),d=Math.max(d,ae.getWidth()))}}return Ve.createDecoderResult(E)}static merge(e,n){if(e==null&&n==null)return null;let i=Ve.getBarcodeMetadata(e,n);if(i==null)return null;let s=sr.merge(Ve.adjustBoundingBox(e),Ve.adjustBoundingBox(n));return new Pr(i,s)}static adjustBoundingBox(e){if(e==null)return null;let n=e.getRowHeights();if(n==null)return null;let i=Ve.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 ls(n,s);for(let h=0;h<2;h++){let p=h===0?1:-1,y=Math.trunc(Math.trunc(i.getX()));for(let E=Math.trunc(Math.trunc(i.getY()));E<=n.getMaxY()&&E>=n.getMinY();E+=p){let I=Ve.detectCodeword(e,0,e.getWidth(),s,y,E,a,l);I!=null&&(d.setCodeword(E,I),s?y=I.getStartX():y=I.getEndX())}}return d}static adjustCodewordCount(e,n){let i=n[0][1],s=i.getValue(),a=e.getBarcodeColumnCount()*e.getBarcodeRowCount()-Ve.getNumberOfECCodeWords(e.getBarcodeECLevel());if(s.length===0){if(a<1||a>De.MAX_CODEWORDS_IN_BARCODE)throw $.getNotFoundInstance();i.setValue(a)}else s[0]!==a&&i.setValue(a)}static createDecoderResult(e){let n=Ve.createBarcodeMatrix(e);Ve.adjustCodewordCount(e,n);let i=new Array,s=new Int32Array(e.getBarcodeRowCount()*e.getBarcodeColumnCount()),a=[],l=new Array;for(let h=0;h<e.getBarcodeRowCount();h++)for(let p=0;p<e.getBarcodeColumnCount();p++){let y=n[h][p+1].getValue(),E=h*e.getBarcodeColumnCount()+p;y.length===0?i.push(E):y.length===1?s[E]=y[0]:(l.push(E),a.push(y))}let d=new Array(a.length);for(let h=0;h<d.length;h++)d[h]=a[h];return Ve.createDecoderResultFromAmbiguousValues(e.getBarcodeECLevel(),s,De.toIntArray(i),De.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 Ve.decodeCodewords(n,e,i)}catch(h){if(!(h instanceof O))throw h}if(l.length===0)throw O.getChecksumInstance();for(let h=0;h<l.length;h++)if(l[h]<a[h].length-1){l[h]++;break}else if(l[h]=0,h===l.length-1)throw O.getChecksumInstance()}throw O.getChecksumInstance()}static createBarcodeMatrix(e){let n=Array.from({length:e.getBarcodeRowCount()},()=>new Array(e.getBarcodeColumnCount()+2));for(let s=0;s<n.length;s++)for(let a=0;a<n[s].length;a++)n[s][a]=new Dr;let i=0;for(let s of e.getDetectionResultColumns()){if(s!=null){for(let a of s.getCodewords())if(a!=null){let l=a.getRowNumber();if(l>=0){if(l>=n.length)continue;n[l][i].setValue(a.getValue())}}}i++}return n}static isValidBarcodeColumn(e,n){return n>=0&&n<=e.getBarcodeColumnCount()+1}static getStartColumn(e,n,i,s){let a=s?1:-1,l=null;if(Ve.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(Ve.isValidBarcodeColumn(e,n-a)&&(l=e.getDetectionResultColumn(n-a).getCodewordNearby(i)),l!=null)return s?l.getEndX():l.getStartX();let d=0;for(;Ve.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=Ve.adjustCodewordStartColumn(e,n,i,s,a,l);let p=Ve.getModuleBitCount(e,n,i,s,a,l);if(p==null)return null;let y,E=Ze.sum(p);if(s)y=a+E;else{for(let L=0;L<p.length/2;L++){let F=p[L];p[L]=p[p.length-1-L],p[p.length-1-L]=F}y=a,a=y-E}if(!Ve.checkCodewordSkew(E,d,h))return null;let I=tn.getDecodedValue(p),k=De.getCodeword(I);return k===-1?null:new Br(a,y,Ve.getCodewordBucketNumber(I),k)}static getModuleBitCount(e,n,i,s,a,l){let d=a,h=new Int32Array(8),p=0,y=s?1:-1,E=s;for(;(s?d<i:d>=n)&&p<h.length;)e.get(d,l)===E?(h[p]++,d+=y):(p++,E=!E);return p===h.length||d===(s?i:n)&&p===h.length-1?h:null}static getNumberOfECCodeWords(e){return 2<<e}static adjustCodewordStartColumn(e,n,i,s,a,l){let d=a,h=s?-1:1;for(let p=0;p<2;p++){for(;(s?d>=n:d<i)&&s===e.get(d,l);){if(Math.abs(a-d)>Ve.CODEWORD_SKEW_SIZE)return a;d+=h}h=-h,s=!s}return d}static checkCodewordSkew(e,n,i){return n-Ve.CODEWORD_SKEW_SIZE<=e&&e<=i+Ve.CODEWORD_SKEW_SIZE}static decodeCodewords(e,n,i){if(e.length===0)throw z.getFormatInstance();let s=1<<n+1,a=Ve.correctErrors(e,i,s);Ve.verifyCodewordCount(e,s);let l=q.decode(e,""+n);return l.setErrorsCorrected(a),l.setErasures(i.length),l}static correctErrors(e,n,i){if(n!=null&&n.length>i/2+Ve.MAX_ERRORS||i<0||i>Ve.MAX_EC_CODEWORDS)throw O.getChecksumInstance();return Ve.errorCorrection.decode(e,i,n)}static verifyCodewordCount(e,n){if(e.length<4)throw z.getFormatInstance();let i=e[0];if(i>e.length)throw z.getFormatInstance();if(i===0)if(n<e.length)e[0]=e.length-n;else throw z.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 Ve.getCodewordBucketNumber(Ve.getBitCountForCodeword(e))}static getCodewordBucketNumber_Int32Array(e){return(e[0]-e[2]+e[4]-e[6]+9)%9}static toString(e){let n=new Rr;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()}}Ve.CODEWORD_SKEW_SIZE=2,Ve.MAX_ERRORS=3,Ve.MAX_EC_CODEWORDS=512,Ve.errorCorrection=new as;class Zt{decode(e,n=null){let i=Zt.decode(e,n,!1);if(i==null||i.length===0||i[0]==null)throw $.getNotFoundInstance();return i[0]}decodeMultiple(e,n=null){try{return Zt.decode(e,n,!0)}catch(i){throw i instanceof z||i instanceof O?$.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=Ve.decode(a.getBits(),l[4],l[5],l[6],l[7],Zt.getMinCodewordWidth(l),Zt.getMaxCodewordWidth(l)),h=new Ee(d.getText(),d.getRawBytes(),void 0,l,Ce.PDF_417);h.putMetadata(Ue.ERROR_CORRECTION_LEVEL,d.getECLevel());const p=d.getOther();p!=null&&h.putMetadata(Ue.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?U.MAX_VALUE:Math.trunc(Math.abs(e.getX()-n.getX()))}static getMaxCodewordWidth(e){return Math.floor(Math.max(Math.max(Zt.getMaxWidth(e[0],e[4]),Zt.getMaxWidth(e[6],e[2])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN),Math.max(Zt.getMaxWidth(e[1],e[5]),Zt.getMaxWidth(e[7],e[3])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN)))}static getMinCodewordWidth(e){return Math.floor(Math.min(Math.min(Zt.getMinWidth(e[0],e[4]),Zt.getMinWidth(e[6],e[2])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN),Math.min(Zt.getMinWidth(e[1],e[5]),Zt.getMinWidth(e[7],e[3])*De.MODULES_IN_CODEWORD/De.MODULES_IN_STOP_PATTERN)))}reset(){}}class di extends x{}di.kind="ReaderException";class hs{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(V.TRY_HARDER)===!0,i=c(e)?null:e.get(V.POSSIBLE_FORMATS),s=new Array;if(!c(i)){const a=i.some(l=>l===Ce.UPC_A||l===Ce.UPC_E||l===Ce.EAN_13||l===Ce.EAN_8||l===Ce.CODABAR||l===Ce.CODE_39||l===Ce.CODE_93||l===Ce.CODE_128||l===Ce.ITF||l===Ce.RSS_14||l===Ce.RSS_EXPANDED);a&&!n&&s.push(new vr(e,this.verbose)),i.includes(Ce.QR_CODE)&&s.push(new Xn),i.includes(Ce.DATA_MATRIX)&&s.push(new Gn),i.includes(Ce.AZTEC)&&s.push(new lt),i.includes(Ce.PDF_417)&&s.push(new Zt),a&&n&&s.push(new vr(e,this.verbose))}s.length===0&&(n||s.push(new vr(e,this.verbose)),s.push(new Xn),s.push(new Gn),s.push(new lt),s.push(new Zt),n&&s.push(new vr(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 $("No MultiFormat Readers were able to detect the code.")}}class Qu extends vt{constructor(e=null,n=500){const i=new hs;i.setHints(e),super(i,n)}decodeBitmap(e){return this.reader.decodeWithState(e)}}class ed extends vt{constructor(e=500){super(new Zt,e)}}class td extends vt{constructor(e=500){super(new Xn,e)}}var Yi;(function(b){b[b.ERROR_CORRECTION=0]="ERROR_CORRECTION",b[b.CHARACTER_SET=1]="CHARACTER_SET",b[b.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",b[b.MIN_SIZE=3]="MIN_SIZE",b[b.MAX_SIZE=4]="MAX_SIZE",b[b.MARGIN=5]="MARGIN",b[b.PDF417_COMPACT=6]="PDF417_COMPACT",b[b.PDF417_COMPACTION=7]="PDF417_COMPACTION",b[b.PDF417_DIMENSIONS=8]="PDF417_DIMENSIONS",b[b.AZTEC_LAYERS=9]="AZTEC_LAYERS",b[b.QR_VERSION=10]="QR_VERSION"})(Yi||(Yi={}));var Dt=Yi;class Ki{constructor(e){this.field=e,this.cachedGenerators=[],this.cachedGenerators.push(new Oe(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 Oe(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 v("No error correction bytes");const i=e.length-n;if(i<=0)throw new v("No data bytes provided");const s=this.buildGenerator(n),a=new Int32Array(i);D.arraycopy(e,0,a,0,i);let l=new Oe(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;D.arraycopy(h,0,e,i+p,h.length)}}class At{constructor(){}static applyMaskPenaltyRule1(e){return At.applyMaskPenaltyRule1Internal(e,!0)+At.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 At.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&&(At.isWhiteHorizontal(h,d-4,d)||At.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&&(At.isWhiteVertical(i,d,l-4,l)||At.isWhiteVertical(i,d,l+7,l+11))&&n++}return n*At.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)*At.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 v("Invalid mask pattern: "+e)}return s===0}static applyMaskPenaltyRule1Internal(e,n){let i=0;const s=n?e.getHeight():e.getWidth(),a=n?e.getWidth():e.getHeight(),l=e.getArray();for(let d=0;d<s;d++){let h=0,p=-1;for(let y=0;y<a;y++){const E=n?l[d][y]:l[y][d];E===p?h++:(h>=5&&(i+=At.N1+(h-5)),h=1,p=E)}h>=5&&(i+=At.N1+(h-5))}return i}}At.N1=3,At.N2=3,At.N3=40,At.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 xe;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(`
|
|
65
|
+
`)}return e.toString()}}class ar{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 xe;return e.append(`<<
|
|
65
66
|
`),e.append(" mode: "),e.append(this.mode?this.mode.toString():"null"),e.append(`
|
|
66
67
|
ecLevel: `),e.append(this.ecLevel?this.ecLevel.toString():"null"),e.append(`
|
|
67
68
|
version: `),e.append(this.version?this.version.toString():"null"),e.append(`
|
|
@@ -70,9 +71,9 @@ ${this.tempPrompt}
|
|
|
70
71
|
`),e.append(this.matrix.toString())):e.append(`
|
|
71
72
|
matrix: null
|
|
72
73
|
`),e.append(`>>
|
|
73
|
-
`),e.toString()}setMode(e){this.mode=e}setECLevel(e){this.ecLevel=e}setVersion(e){this.version=e}setMaskPattern(e){this.maskPattern=e}setMatrix(e){this.matrix=e}static isValidMaskPattern(e){return e>=0&&e<rr.NUM_MASK_PATTERNS}}rr.NUM_MASK_PATTERNS=8;class rt extends x{}rt.kind="WriterException";class Ae{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Ae.clearMatrix(a),Ae.embedBasicPatterns(i,a),Ae.embedTypeInfo(n,s,a),Ae.maybeEmbedVersionInfo(i,a),Ae.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Ae.embedPositionDetectionPatternsAndSeparators(n),Ae.embedDarkDotAtLeftBottomCorner(n),Ae.maybeEmbedPositionAdjustmentPatterns(e,n),Ae.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new W;Ae.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Ae.TYPE_INFO_COORDINATES[a],p=h[0],w=h[1];if(i.setBoolean(p,w,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 W;Ae.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(!Ae.isEmpty(i.get(p,d)))continue;let w;s<e.getSize()?(w=e.get(s),++s):w=!1,n!==255&&_t.getDataMaskBit(n,p,d)&&(w=!w),i.setBoolean(p,d,w)}d+=a}a=-a,d+=a,l-=2}if(s!==e.getSize())throw new rt("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-U.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new A("0 polynomial");const i=Ae.findMSBSet(n);for(e<<=i-1;Ae.findMSBSet(e)>=i;)e^=n<<Ae.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!rr.isValidMaskPattern(n))throw new rt("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Ae.calculateBCHCode(s,Ae.TYPE_INFO_POLY);i.appendBits(a,10);const l=new W;if(l.appendBits(Ae.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new rt("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Ae.calculateBCHCode(e.getVersionNumber(),Ae.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new rt("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;Ae.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Ae.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new rt;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Ae.isEmpty(i.get(e+s,n)))throw new rt;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Ae.isEmpty(i.get(e,n+s)))throw new rt;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Ae.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=Ae.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Ae.POSITION_DETECTION_PATTERN[0].length;Ae.embedPositionDetectionPattern(0,0,e),Ae.embedPositionDetectionPattern(e.getWidth()-n,0,e),Ae.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Ae.embedHorizontalSeparationPattern(0,i-1,e),Ae.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Ae.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Ae.embedVerticalSeparationPattern(s,0,e),Ae.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Ae.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Ae.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&&Ae.isEmpty(n.get(p,d))&&Ae.embedPositionAdjustmentPattern(p-2,d-2,n)}}}}Ae.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])]),Ae.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])]),Ae.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])]),Ae.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])]),Ae.VERSION_INFO_POLY=7973,Ae.TYPE_INFO_POLY=1335,Ae.TYPE_INFO_MASK_PATTERN=21522;class Ku{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class lt{constructor(){}static calculateMaskPenalty(e){return _t.applyMaskPenaltyRule1(e)+_t.applyMaskPenaltyRule2(e)+_t.applyMaskPenaltyRule3(e)+_t.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=lt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Nt.CHARACTER_SET)!==void 0;a&&(s=i.get(Nt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new W;if(l===Ee.BYTE&&(a||lt.DEFAULT_BYTE_MODE_ENCODING!==s)){const ce=M.getCharacterSetECIByName(s);ce!==void 0&&this.appendECI(ce,d)}this.appendModeInfo(l,d);const h=new W;this.appendBytes(e,l,h,s);let p;if(i!==null&&i.get(Nt.QR_VERSION)!==void 0){const ce=Number.parseInt(i.get(Nt.QR_VERSION).toString(),10);p=ve.getVersionForNumber(ce);const se=this.calculateBitsNeeded(l,d,h,p);if(!this.willFit(se,p,n))throw new rt("Data too big for requested version")}else p=this.recommendVersion(n,l,d,h);const w=new W;w.appendBitArray(d);const b=l===Ee.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(b,p,l,w),w.appendBitArray(h);const I=p.getECBlocksForLevel(n),k=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(k,w);const L=this.interleaveWithECBytes(w,p.getTotalCodewords(),k,I.getNumBlocks()),F=new rr;F.setECLevel(n),F.setMode(l),F.setVersion(p);const j=p.getDimensionForVersion(),Q=new di(j,j),ae=this.chooseMaskPattern(L,n,p,Q);return F.setMaskPattern(ae),Ae.buildMatrix(L,n,p,ae,Q),F.setMatrix(Q),F}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,ve.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<lt.ALPHANUMERIC_TABLE.length?lt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(M.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Ee.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(lt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return Ee.BYTE}return s?Ee.ALPHANUMERIC:i?Ee.NUMERIC:Ee.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=me.encode(e,M.SJIS)}catch{return!1}const i=n.length;if(i%2!==0)return!1;for(let s=0;s<i;s+=2){const a=n[s]&255;if((a<129||a>159)&&(a<224||a>235))return!1}return!0}static chooseMaskPattern(e,n,i,s){let a=Number.MAX_SAFE_INTEGER,l=-1;for(let d=0;d<rr.NUM_MASK_PATTERNS;d++){Ae.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=ve.getVersionForNumber(i);if(lt.willFit(e,s,n))return s}throw new rt("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 rt("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 rt("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new rt("Block ID too large");const d=e%i,h=i-d,p=Math.floor(e/i),w=p+1,b=Math.floor(n/i),I=b+1,k=p-b,L=w-I;if(k!==L)throw new rt("EC bytes mismatch");if(i!==h+d)throw new rt("RS blocks mismatch");if(e!==(b+k)*h+(I+L)*d)throw new rt("Total bytes mismatch");s<h?(a[0]=b,l[0]=k):(a[0]=I,l[0]=L)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new rt("Number of bits and data bytes does not match");let a=0,l=0,d=0;const h=new Array;for(let w=0;w<s;++w){const b=new Int32Array(1),I=new Int32Array(1);lt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,w,b,I);const k=b[0],L=new Uint8Array(k);e.toBytes(8*a,L,0,k);const F=lt.generateECBytes(L,I[0]);h.push(new Ku(L,F)),l=Math.max(l,k),d=Math.max(d,F.length),a+=b[0]}if(i!==a)throw new rt("Data bytes does not match offset");const p=new W;for(let w=0;w<l;++w)for(const b of h){const I=b.getDataBytes();w<I.length&&p.appendBits(I[w],8)}for(let w=0;w<d;++w)for(const b of h){const I=b.getErrorCorrectionBytes();w<I.length&&p.appendBits(I[w],8)}if(n!==p.getSizeInBytes())throw new rt("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(Ue.QR_CODE_FIELD_256).encode(s,n);const a=new Uint8Array(n);for(let l=0;l<n;l++)a[l]=s[i+l];return a}static appendModeInfo(e,n){n.appendBits(e.getBits(),4)}static appendLengthInfo(e,n,i,s){const a=i.getCharacterCountBits(n);if(e>=1<<a)throw new rt(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case Ee.NUMERIC:lt.appendNumericBytes(e,i);break;case Ee.ALPHANUMERIC:lt.appendAlphanumericBytes(e,i);break;case Ee.BYTE:lt.append8BitBytes(e,i,s);break;case Ee.KANJI:lt.appendKanjiBytes(e,i);break;default:throw new rt("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=lt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=lt.getDigit(e.charAt(s));if(s+2<i){const l=lt.getDigit(e.charAt(s+1)),d=lt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=lt.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=lt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new rt;if(s+1<i){const l=lt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new rt;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=me.encode(e,i)}catch(a){throw new rt(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=me.encode(e,M.SJIS)}catch(a){throw new rt(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 rt("Invalid byte sequence");const w=(p>>8)*192+(p&255);n.appendBits(w,13)}}static appendECI(e,n){n.appendBits(Ee.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}lt.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]),lt.DEFAULT_BYTE_MODE_ENCODING=M.UTF8.getName();class ir{write(e,n,i,s=null){if(e.length===0)throw new A("Found empty contents");if(n<0||i<0)throw new A("Requested dimensions are too small: "+n+"x"+i);let a=st.L,l=ir.QUIET_ZONE_SIZE;s!==null&&(s.get(Nt.ERROR_CORRECTION)!==void 0&&(a=st.fromString(s.get(Nt.ERROR_CORRECTION).toString())),s.get(Nt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Nt.MARGIN).toString(),10)));const d=lt.encode(e,a,s);return this.renderResult(d,n,i,l)}writeToDom(e,n,i,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,i,s,a);e&&e.appendChild(l)}renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,w=Math.max(n,h),b=Math.max(i,p),I=Math.min(Math.floor(w/h),Math.floor(b/p)),k=Math.floor((w-l*I)/2),L=Math.floor((b-d*I)/2),F=this.createSVGElement(w,b);for(let j=0,Q=L;j<d;j++,Q+=I)for(let ae=0,ce=k;ae<l;ae++,ce+=I)if(a.get(ae,j)===1){const se=this.createSvgRectElement(ce,Q,I,I);F.appendChild(se)}return F}createSVGElement(e,n){const i=document.createElementNS(ir.SVG_NS,"svg");return i.setAttributeNS(null,"height",e.toString()),i.setAttributeNS(null,"width",n.toString()),i}createSvgRectElement(e,n,i,s){const a=document.createElementNS(ir.SVG_NS,"rect");return a.setAttributeNS(null,"x",e.toString()),a.setAttributeNS(null,"y",n.toString()),a.setAttributeNS(null,"height",i.toString()),a.setAttributeNS(null,"width",s.toString()),a.setAttributeNS(null,"fill","#000000"),a}}ir.QUIET_ZONE_SIZE=4,ir.SVG_NS="http://www.w3.org/2000/svg";class yr{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=st.L,d=yr.QUIET_ZONE_SIZE;a!==null&&(a.get(Nt.ERROR_CORRECTION)!==void 0&&(l=st.fromString(a.get(Nt.ERROR_CORRECTION).toString())),a.get(Nt.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Nt.MARGIN).toString(),10)));const h=lt.encode(e,l,a);return yr.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Vt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,w=Math.max(n,h),b=Math.max(i,p),I=Math.min(Math.floor(w/h),Math.floor(b/p)),k=Math.floor((w-l*I)/2),L=Math.floor((b-d*I)/2),F=new re(w,b);for(let j=0,Q=L;j<d;j++,Q+=I)for(let ae=0,ce=k;ae<l;ae++,ce+=I)a.get(ae,j)===1&&F.setRegion(ce,Q,I,I);return F}}yr.QUIET_ZONE_SIZE=4;class Ju{encode(e,n,i,s,a){let l;switch(n){case te.QR_CODE:l=new yr;break;default:throw new A("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class kn extends he{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 D.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 D.arraycopy(this.yuvData,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.arraycopy(this.yuvData,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new kn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/kn.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*kn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|p*65793}a+=this.dataWidth*kn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/kn.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 Ie(this)}}kn.THUMBNAIL_SCALE_FACTOR=2;class Ji extends he{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 w=0;w<h;w++){const b=e[w],I=b>>16&255,k=b>>7&510,L=b&255;p[w]=(I+k+L)/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 D.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 D.arraycopy(this.luminances,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.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 Ie(this)}}class us extends M{static forName(e){return this.getCharacterSetECIByName(e)}}class Qi{}Qi.ISO_8859_1=M.ISO8859_1;class ds{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 fs{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class Qu{constructor(e){this.previous=e}getPrevious(){return this.previous}}class _r extends Qu{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 _r(this,e,n)}addBinaryShift(e,n){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new _r(this,e,n)}toString(){let e=this.value&(1<<this.bitCount)-1;return e|=1<<this.bitCount,"<"+U.toBinaryString(e|1<<this.bitCount).substring(1)+">"}}class eo extends _r{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 ed(C,e,n){return new eo(C,e,n)}function Mr(C,e,n){return new _r(C,e,n)}const td=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],jn=0,fi=1,gn=2,hs=3,Rn=4,nd=new _r(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 rd(C){for(let e of C)$.fill(e,-1);return C[jn][Rn]=0,C[fi][Rn]=0,C[fi][jn]=28,C[hs][Rn]=0,C[gn][Rn]=0,C[gn][jn]=15,C}const ps=rd($.createInt32Array(6,6));class Mn{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=Mr(s,l&65535,l>>16),i+=l>>16}let a=e===gn?4:5;return s=Mr(s,n,a),new Mn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===gn?4:5;return i=Mr(i,ps[this.mode][e],s),i=Mr(i,n,5),new Mn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===Rn||this.mode===gn){let d=to[i][jn];n=Mr(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 Mn(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=ed(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Mn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(to[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Mn.calculateBinaryShiftCost(e)-Mn.calculateBinaryShiftCost(this):this.binaryShiftByteCount>e.binaryShiftByteCount&&e.binaryShiftByteCount>0&&(n+=10),n<=e.bitCount}toBitArray(e){let n=[];for(let s=this.endBinaryShift(e.length).token;s!==null;s=s.getPrevious())n.unshift(s);let i=new W;for(const s of n)s.appendTo(i,e);return i}toString(){return le.format("%s bits=%d bytes=%d",td[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Mn.INITIAL_STATE=new Mn(nd,jn,0,0);function id(C){const e=le.getCharCode(" "),n=le.getCharCode("."),i=le.getCharCode(",");C[jn][e]=1;const s=le.getCharCode("Z"),a=le.getCharCode("A");for(let I=a;I<=s;I++)C[jn][I]=I-a+2;C[fi][e]=1;const l=le.getCharCode("z"),d=le.getCharCode("a");for(let I=d;I<=l;I++)C[fi][I]=I-d+2;C[gn][e]=1;const h=le.getCharCode("9"),p=le.getCharCode("0");for(let I=p;I<=h;I++)C[gn][I]=I-p+2;C[gn][i]=12,C[gn][n]=13;const w=["\0"," ","","","","","","","\x07","\b"," ",`
|
|
74
|
-
`,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<
|
|
75
|
-
`);let i=fs.singletonList(Mn.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 le.getCharCode("\r"):l=d===n?2:0;break;case le.getCharCode("."):l=d===e?3:0;break;case le.getCharCode(","):l=d===e?4:0;break;case le.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Dr.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return fs.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 Dr.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<=Rn;d++){let h=no[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===gn){const p=l.latchAndAppend(d,h);i.push(p)}if(!a&&ps[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(Rn,i)),e.getMode()!==Rn&&s.push(a.shiftAndAppend(Rn,i)),i===3||i===4){let l=a.latchAndAppend(gn,16-i).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 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 He{constructor(){}static encodeBytes(e){return He.encode(e,He.DEFAULT_EC_PERCENT,He.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Dr(e).encode(),a=U.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,p,w,b;if(i!==He.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?He.MAX_NB_BITS_COMPACT:He.MAX_NB_BITS))throw new A(le.format("Illegal value %s for layers",i));p=He.totalBitsInLayer(h,d),w=He.WORD_SIZE[h];let se=p-p%w;if(b=He.stuffBits(s,w),b.getSize()+a>se)throw new A("Data to large for user specified layer");if(d&&b.getSize()>w*64)throw new A("Data to large for user specified layer")}else{w=0,b=null;for(let se=0;;se++){if(se>He.MAX_NB_BITS)throw new A("Data too large for an Aztec code");if(d=se<=3,h=d?se+1:se,p=He.totalBitsInLayer(h,d),l>p)continue;(b==null||w!==He.WORD_SIZE[h])&&(w=He.WORD_SIZE[h],b=He.stuffBits(s,w));let Ze=p-p%w;if(!(d&&b.getSize()>w*64)&&b.getSize()+a<=Ze)break}}let I=He.generateCheckWords(b,p,w),k=b.getSize()/w,L=He.generateModeMessage(d,h,k),F=(d?11:14)+h*4,j=new Int32Array(F),Q;if(d){Q=F;for(let se=0;se<j.length;se++)j[se]=se}else{Q=F+1+2*U.truncDivision(U.truncDivision(F,2)-1,15);let se=U.truncDivision(F,2),Ze=U.truncDivision(Q,2);for(let ke=0;ke<se;ke++){let Jt=ke+U.truncDivision(ke,15);j[se-ke-1]=Ze-Jt-1,j[se+ke]=Ze+Jt+1}}let ae=new re(Q);for(let se=0,Ze=0;se<h;se++){let ke=(h-se)*4+(d?9:12);for(let Jt=0;Jt<ke;Jt++){let wn=Jt*2;for(let Qt=0;Qt<2;Qt++)I.get(Ze+wn+Qt)&&ae.set(j[se*2+Qt],j[se*2+Jt]),I.get(Ze+ke*2+wn+Qt)&&ae.set(j[se*2+Jt],j[F-1-se*2-Qt]),I.get(Ze+ke*4+wn+Qt)&&ae.set(j[F-1-se*2-Qt],j[F-1-se*2-Jt]),I.get(Ze+ke*6+wn+Qt)&&ae.set(j[F-1-se*2-Jt],j[se*2+Qt])}Ze+=ke*8}if(He.drawModeMessage(ae,d,Q,L),d)He.drawBullsEye(ae,U.truncDivision(Q,2),5);else{He.drawBullsEye(ae,U.truncDivision(Q,2),7);for(let se=0,Ze=0;se<U.truncDivision(F,2)-1;se+=15,Ze+=16)for(let ke=U.truncDivision(Q,2)&1;ke<Q;ke+=2)ae.set(U.truncDivision(Q,2)-Ze,ke),ae.set(U.truncDivision(Q,2)+Ze,ke),ae.set(ke,U.truncDivision(Q,2)-Ze),ae.set(ke,U.truncDivision(Q,2)+Ze)}let ce=new ds;return ce.setCompact(d),ce.setSize(Q),ce.setLayers(h),ce.setCodeWords(k),ce.setMatrix(ae),ce}static drawBullsEye(e,n,i){for(let s=0;s<i;s+=2)for(let a=n-s;a<=n+s;a++)e.set(a,n-s),e.set(a,n+s),e.set(n-s,a),e.set(n+s,a);e.set(n-i,n-i),e.set(n-i+1,n-i),e.set(n-i,n-i+1),e.set(n+i,n-i),e.set(n+i,n-i+1),e.set(n+i,n+i-1)}static generateModeMessage(e,n,i){let s=new W;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=He.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=He.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=U.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+U.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(He.getGF(i)),l=U.truncDivision(n,i),d=He.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,p=new W;p.appendBits(0,h);for(const w of Array.from(d))p.appendBits(w,i);return p}static bitsToWords(e,n,i){let s=new Int32Array(i),a,l;for(a=0,l=e.getSize()/n;a<l;a++){let d=0;for(let h=0;h<n;h++)d|=e.get(a*n+h)?1<<n-h-1:0;s[a]=d}return s}static getGF(e){switch(e){case 4:return Ue.AZTEC_PARAM;case 6:return Ue.AZTEC_DATA_6;case 8:return Ue.AZTEC_DATA_8;case 10:return Ue.AZTEC_DATA_10;case 12:return Ue.AZTEC_DATA_12;default:throw new A("Unsupported word size "+e)}}static stuffBits(e,n){let i=new W,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let d=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(d|=1<<n-1-h);(d&a)===a?(i.appendBits(d&a,n),l--):(d&a)===0?(i.appendBits(d|1,n),l--):i.appendBits(d,n)}return i}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}He.DEFAULT_EC_PERCENT=33,He.DEFAULT_AZTEC_LAYERS=0,He.MAX_NB_BITS=32,He.MAX_NB_BITS_COMPACT=4,He.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 hi{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=He.DEFAULT_EC_PERCENT,h=He.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Nt.CHARACTER_SET)&&(l=us.forName(a.get(Nt.CHARACTER_SET).toString())),a.has(Nt.ERROR_CORRECTION)&&(d=U.parseInt(a.get(Nt.ERROR_CORRECTION).toString())),a.has(Nt.AZTEC_LAYERS)&&(h=U.parseInt(a.get(Nt.AZTEC_LAYERS).toString()))),hi.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=He.encode(le.getBytes(e,a),l,d);return hi.renderResult(h,i,s)}static renderResult(e,n,i){let s=e.getMatrix();if(s==null)throw new Vt;let a=s.getWidth(),l=s.getHeight(),d=Math.max(n,a),h=Math.max(i,l),p=Math.min(d/a,h/l),w=(d-a*p)/2,b=(h-l*p)/2,I=new re(d,h);for(let k=0,L=b;k<l;k++,L+=p)for(let F=0,j=w;F<a;F++,j+=p)s.get(F,k)&&I.setRegion(j,L,p,p);return I}}o.AbstractExpandedDecoder=Vi,o.ArgumentException=E,o.ArithmeticException=nn,o.AztecCode=ds,o.AztecCodeReader=hr,o.AztecCodeWriter=hi,o.AztecDecoder=je,o.AztecDetector=ii,o.AztecDetectorResult=dt,o.AztecEncoder=He,o.AztecHighLevelEncoder=Dr,o.AztecPoint=Lt,o.BarcodeFormat=te,o.Binarizer=R,o.BinaryBitmap=B,o.BitArray=W,o.BitMatrix=re,o.BitSource=Hi,o.BrowserAztecCodeReader=Fi,o.BrowserBarcodeReader=Pu,o.BrowserCodeReader=At,o.BrowserDatamatrixCodeReader=Lu,o.BrowserMultiFormatReader=Xu,o.BrowserPDF417Reader=qu,o.BrowserQRCodeReader=Yu,o.BrowserQRCodeSvgWriter=ir,o.CharacterSetECI=M,o.ChecksumException=O,o.Code128Reader=pe,o.Code39Reader=bt,o.DataMatrixDecodedBitStreamParser=Zn,o.DataMatrixReader=$n,o.DecodeHintType=H,o.DecoderResult=Fe,o.DefaultGridSampler=ri,o.DetectorResult=ue,o.EAN13Reader=Qn,o.EncodeHintType=Nt,o.Exception=x,o.FormatException=z,o.GenericGF=Ue,o.GenericGFPoly=St,o.GlobalHistogramBinarizer=de,o.GridSampler=Sn,o.GridSamplerInstance=on,o.HTMLCanvasElementLuminanceSource=Te,o.HybridBinarizer=ee,o.ITFReader=et,o.IllegalArgumentException=A,o.IllegalStateException=Vt,o.InvertedLuminanceSource=Ie,o.LuminanceSource=he,o.MathUtils=ze,o.MultiFormatOneDReader=xr,o.MultiFormatReader=cs,o.MultiFormatWriter=Ju,o.NotFoundException=Z,o.OneDReader=wt,o.PDF417DecodedBitStreamParser=J,o.PDF417DecoderErrorCorrection=rs,o.PDF417Reader=Ut,o.PDF417ResultMetadata=os,o.PerspectiveTransform=rn,o.PlanarYUVLuminanceSource=kn,o.QRCodeByteMatrix=di,o.QRCodeDataMask=hn,o.QRCodeDecodedBitStreamParser=gt,o.QRCodeDecoderErrorCorrectionLevel=st,o.QRCodeDecoderFormatInformation=$t,o.QRCodeEncoder=lt,o.QRCodeEncoderQRCode=rr,o.QRCodeMaskUtil=_t,o.QRCodeMatrixUtil=Ae,o.QRCodeMode=Ee,o.QRCodeReader=Wn,o.QRCodeVersion=ve,o.QRCodeWriter=yr,o.RGBLuminanceSource=Ji,o.RSS14Reader=yt,o.RSSExpandedReader=oe,o.ReaderException=ui,o.ReedSolomonDecoder=An,o.ReedSolomonEncoder=Ki,o.ReedSolomonException=Ht,o.Result=Ye,o.ResultMetadataType=Ne,o.ResultPoint=S,o.StringUtils=le,o.UnsupportedOperationException=Ce,o.VideoInputDevice=ge,o.WhiteRectangleDetector=pt,o.WriterException=rt,o.ZXingArrays=$,o.ZXingCharset=us,o.ZXingInteger=U,o.ZXingStandardCharsets=Qi,o.ZXingStringBuilder=ie,o.ZXingStringEncoding=me,o.ZXingSystem=D,o.createAbstractExpandedDecoder=ts,Object.defineProperty(o,"__esModule",{value:!0})}))})(Zr,Zr.exports)),Zr.exports}var ct=Sw();const Tw=Aw(ct),Nw=ud({__proto__:null,default:Tw},[ct]);var Ja=(function(){function t(r,o,c){if(this.formatMap=new Map([[we.QR_CODE,ct.BarcodeFormat.QR_CODE],[we.AZTEC,ct.BarcodeFormat.AZTEC],[we.CODABAR,ct.BarcodeFormat.CODABAR],[we.CODE_39,ct.BarcodeFormat.CODE_39],[we.CODE_93,ct.BarcodeFormat.CODE_93],[we.CODE_128,ct.BarcodeFormat.CODE_128],[we.DATA_MATRIX,ct.BarcodeFormat.DATA_MATRIX],[we.MAXICODE,ct.BarcodeFormat.MAXICODE],[we.ITF,ct.BarcodeFormat.ITF],[we.EAN_13,ct.BarcodeFormat.EAN_13],[we.EAN_8,ct.BarcodeFormat.EAN_8],[we.PDF_417,ct.BarcodeFormat.PDF_417],[we.RSS_14,ct.BarcodeFormat.RSS_14],[we.RSS_EXPANDED,ct.BarcodeFormat.RSS_EXPANDED],[we.UPC_A,ct.BarcodeFormat.UPC_A],[we.UPC_E,ct.BarcodeFormat.UPC_E],[we.UPC_EAN_EXTENSION,ct.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!Nw)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(ct.DecodeHintType.POSSIBLE_FORMATS,u),f.set(ct.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 ct.MultiFormatReader(this.verbose,this.hints),c=new ct.HTMLCanvasElementLuminanceSource(r),u=new ct.BinaryBitmap(new ct.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:Su.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})(),Ow=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(g){g(f)})}return new(o||(o=Promise))(function(f,g){function m(E){try{x(c.next(E))}catch(A){g(A)}}function v(E){try{x(c.throw(E))}catch(A){g(A)}}function x(E){E.done?f(E.value):u(E.value).then(m,v)}x((c=c.apply(t,r||[])).next())})},kw=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,g;return g={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function m(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;g&&(g=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}}},Qa=(function(){function t(r,o,c){if(this.formatMap=new Map([[we.QR_CODE,"qr_code"],[we.AZTEC,"aztec"],[we.CODABAR,"codabar"],[we.CODE_39,"code_39"],[we.CODE_93,"code_93"],[we.CODE_128,"code_128"],[we.DATA_MATRIX,"data_matrix"],[we.ITF,"itf"],[we.EAN_13,"ean_13"],[we.EAN_8,"ean_8"],[we.PDF_417,"pdf417"],[we.UPC_A,"upc_a"],[we.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 Ow(this,void 0,void 0,function(){var o,c;return kw(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:Su.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 g=f[u],m=g.boundingBox.width*g.boundingBox.height;m>c&&(c=m,o=g)}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})(),el=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(g){g(f)})}return new(o||(o=Promise))(function(f,g){function m(E){try{x(c.next(E))}catch(A){g(A)}}function v(E){try{x(c.throw(E))}catch(A){g(A)}}function x(E){E.done?f(E.value):u(E.value).then(m,v)}x((c=c.apply(t,r||[])).next())})},tl=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,g;return g={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function m(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;g&&(g=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}}},Rw=(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&&Qa.isSupported()?(this.primaryDecoder=new Qa(r,c,u),this.secondaryDecoder=new Ja(r,c,u)):this.primaryDecoder=new Ja(r,c,u)}return t.prototype.decodeAsync=function(r){return el(this,void 0,void 0,function(){var o;return tl(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 el(this,void 0,void 0,function(){var o,c;return tl(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})(),Yo=(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)}})(),ki=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(g){g(f)})}return new(o||(o=Promise))(function(f,g){function m(E){try{x(c.next(E))}catch(A){g(A)}}function v(E){try{x(c.throw(E))}catch(A){g(A)}}function x(E){E.done?f(E.value):u(E.value).then(m,v)}x((c=c.apply(t,r||[])).next())})},Ri=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,g;return g={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function m(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;g&&(g=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}}},Nu=(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})(),Mw=(function(t){Yo(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})(Nu),Dw=(function(t){Yo(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(Mw),Pw=(function(t){Yo(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(Nu),Bw=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new Dw(this.track)},t.prototype.torchFeature=function(){return new Pw(this.track)},t})(),Lw=(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 ki(this,void 0,void 0,function(){var f,g;return Ri(this,function(m){switch(m.label){case 0:return f=new t(r,o,u),c.aspectRatio?(g={aspectRatio:c.aspectRatio},[4,f.getFirstTrackOrFail().applyConstraints(g)]):[3,2];case 1:m.sent(),m.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 ki(this,void 0,void 0,function(){return Ri(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,g=0;r.mediaStream.getVideoTracks().forEach(function(m){r.mediaStream.removeTrack(m),m.stop(),++g,g>=f&&(r.isClosed=!0,r.parentElement.removeChild(r.surface),o())})})},t.prototype.getCapabilities=function(){return new Bw(this.getFirstTrackOrFail())},t})(),Fw=(function(){function t(r){this.mediaStream=r}return t.prototype.render=function(r,o,c){return ki(this,void 0,void 0,function(){return Ri(this,function(u){return[2,Lw.create(r,this.mediaStream,o,c)]})})},t.create=function(r){return ki(this,void 0,void 0,function(){var o,c;return Ri(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})(),nl=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(g){g(f)})}return new(o||(o=Promise))(function(f,g){function m(E){try{x(c.next(E))}catch(A){g(A)}}function v(E){try{x(c.throw(E))}catch(A){g(A)}}function x(E){E.done?f(E.value):u(E.value).then(m,v)}x((c=c.apply(t,r||[])).next())})},rl=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,g;return g={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function m(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;g&&(g=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.failIfNotSupported=function(){return nl(this,void 0,void 0,function(){return rl(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return nl(this,void 0,void 0,function(){return rl(this,function(o){return[2,Fw.create(r)]})})},t})(),zw=function(t,r,o,c){function u(f){return f instanceof o?f:new o(function(g){g(f)})}return new(o||(o=Promise))(function(f,g){function m(E){try{x(c.next(E))}catch(A){g(A)}}function v(E){try{x(c.throw(E))}catch(A){g(A)}}function x(E){E.done?f(E.value):u(E.value).then(m,v)}x((c=c.apply(t,r||[])).next())})},Vw=function(t,r){var o={label:0,sent:function(){if(f[0]&1)throw f[1];return f[1]},trys:[],ops:[]},c,u,f,g;return g={next:m(0),throw:m(1),return:m(2)},typeof Symbol=="function"&&(g[Symbol.iterator]=function(){return this}),g;function m(x){return function(E){return v([x,E])}}function v(x){if(c)throw new TypeError("Generator is already executing.");for(;g&&(g=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}}},Zw=(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=Ar.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Ar.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 zw(this,void 0,void 0,function(){var r,o,c,u,f,g,m;return Vw(this,function(v){switch(v.label){case 0:return r=function(x){for(var E=x.getVideoTracks(),A=0,B=E;A<B.length;A++){var O=B[A];O.enabled=!1,O.stop(),x.removeTrack(O)}},[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,g=c;f<g.length;f++)m=g[f],m.kind==="videoinput"&&u.push({id:m.deviceId,label:m.label});return r(o),[2,u]}})})},t.getCamerasFromMediaStreamTrack=function(){return new Promise(function(r,o){var c=function(f){for(var g=[],m=0,v=f;m<v.length;m++){var x=v[m];x.kind==="video"&&g.push({id:x.id,label:x.label})}r(g)},u=MediaStreamTrack;u.getSources(c)})},t})(),vt;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(vt||(vt={}));var $w=(function(){function t(){this.state=vt.NOT_STARTED,this.onGoingTransactionNewState=vt.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===vt.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=vt.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===vt.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=vt.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==vt.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case vt.UNKNOWN:throw"Transition from unknown is not allowed";case vt.NOT_STARTED:this.failIfNewStateIs(r,[vt.PAUSED]);break;case vt.SCANNING:break;case vt.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})(),Ww=(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()===vt.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==vt.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===vt.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===vt.PAUSED},t})(),Hw=(function(){function t(){}return t.create=function(){return new Ww(new $w)},t})(),jw=(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)}})(),an=(function(t){jw(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})(Cw),Gw=(function(){function t(r,o){this.logger=o,this.fps=an.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=an.DEFAULT_DISABLE_FLIP}return t.prototype.isMediaStreamConstraintsValid=function(){return this.videoConstraints?Tu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Pn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),il=(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 Ew(this.verbose),this.qrcode=new Rw(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 g;u?g=u:g=this.verbose?this.logger.log:function(){};var m=Gw.create(o,this.logger);this.clearElement();var v=!1;m.videoConstraints&&(m.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:an.DEFAULT_WIDTH,E.style.position="relative",this.shouldScan=!0,this.element=E;var A=this,B=this.stateManagerProxy.startTransition(vt.SCANNING);return new Promise(function(O,R){var D=x?m.videoConstraints:A.createVideoConstraints(r);if(!D){B.cancel(),R("videoConstraints should be defined");return}var P={};(!x||m.aspectRatio)&&(P.aspectRatio=m.aspectRatio);var Y={onRenderSurfaceReady:function($,U){A.setupUi($,U,m),A.isScanning=!0,A.foreverScan(m,c,g)}};Uw.failIfNotSupported().then(function($){$.create(D).then(function(U){return U.render(f.element,P,Y).then(function(W){A.renderedCamera=W,B.execute(),O(null)}).catch(function(W){B.cancel(),R(W)})}).catch(function(U){B.cancel(),R(Ar.errorGettingUserMedia(U))})}).catch(function($){B.cancel(),R(Ar.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(vt.PAUSED),this.showPausedState(),(Pn(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(vt.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(vt.NOT_STARTED);this.shouldScan=!1,this.foreverScanTimeout&&clearTimeout(this.foreverScanTimeout);var c=function(){if(r.element){var f=document.getElementById(an.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(Pn(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 g=new Image;g.onload=function(){var m=g.width,v=g.height,x=document.getElementById(c.elementId),E=x.clientWidth?x.clientWidth:an.DEFAULT_WIDTH,A=Math.max(x.clientHeight?x.clientHeight:v,an.FILE_SCAN_MIN_HEIGHT),B=c.computeCanvasDrawConfig(m,v,E,A);if(o){var O=c.createCanvasElement(E,A,"qr-canvas-visible");O.style.display="inline-block",x.appendChild(O);var R=O.getContext("2d");if(!R)throw"Unable to get 2d context from canvas";R.canvas.width=E,R.canvas.height=A,R.drawImage(g,0,0,m,v,B.x,B.y,B.width,B.height)}var D=an.FILE_SCAN_HIDDEN_CANVAS_PADDING,P=Math.max(g.width,B.width),Y=Math.max(g.height,B.height),$=P+2*D,U=Y+2*D,W=c.createCanvasElement($,U);x.appendChild(W);var X=W.getContext("2d");if(!X)throw"Unable to get 2d context from canvas";X.canvas.width=$,X.canvas.height=U,X.drawImage(g,0,0,m,v,D,D,P,Y);try{c.qrcode.decodeRobustlyAsync(W).then(function(H){u(Ya.createFromQrcodeResult(H))}).catch(f)}catch(H){f("QR code parse error, error = ".concat(H))}},g.onerror=f,g.onabort=f,g.onstalled=f,g.onsuspend=f,g.src=URL.createObjectURL(r)})},t.prototype.clear=function(){this.clearElement()},t.getCameras=function(){return Zw.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(!Tu.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=[we.QR_CODE,we.AZTEC,we.CODABAR,we.CODE_39,we.CODE_93,we.CODE_128,we.DATA_MATRIX,we.MAXICODE,we.ITF,we.EAN_13,we.EAN_8,we.PDF_417,we.RSS_14,we.RSS_EXPANDED,we.UPC_A,we.UPC_E,we.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 g=f[u];vw(g)?c.push(g):this.logger.warn("Invalid format: ".concat(g," passed in config, ignoring."))}if(c.length===0)throw"None of formatsToSupport match supported values.";return c},t.prototype.getUseBarCodeDetectorIfSupported=function(r){if(Pn(r))return!0;if(!Pn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Pn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Pn(o.useBarCodeDetectorIfSupported)?!0:o.useBarCodeDetectorIfSupported!==!1},t.prototype.validateQrboxSize=function(r,o,c){var u=this,f=c.qrbox;this.validateQrboxConfig(f);var g=this.toQrdimensions(r,o,f),m=function(x){if(x<an.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(an.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};m(g.width),m(g.height),g.width=v(g.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=Pn(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 g=c.isShadedBoxEnabled()&&f.height<=o,m={x:0,y:0,width:r,height:o},v=g?this.getShadedRegionBounds(r,o,f):m,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),g&&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=Ar.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,Ya.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Ar.codeParseError(u);return o(f,bw.createFrom(f)),!1})},t.prototype.foreverScan=function(r,o,c){var u=this;if(this.shouldScan&&this.renderedCamera){var f=this.renderedCamera.getSurface(),g=f.videoWidth/f.clientWidth,m=f.videoHeight/f.clientHeight;if(!this.qrRegion)throw"qrRegion undefined when localMediaStream is ready.";var v=this.qrRegion.width*g,x=this.qrRegion.height*m,E=this.qrRegion.x*g,A=this.qrRegion.y*m;this.context.drawImage(f,E,A,v,x,0,0,this.qrRegion.width,this.qrRegion.height);var B=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(O){!O&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){B()})):B()}).catch(function(O){u.logger.logError("Error happend while scanning context",O),B()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var o="facingMode",c="deviceId",u={user:!0,environment:!0},f="exact",g=function(R){if(R in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(R,"'")},m=Object.keys(r);if(m.length!==1)throw"'cameraIdOrConfig' object should have exactly 1 key,"+" if passed as an object, found ".concat(m.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(g(x))return{facingMode:x}}else if(typeof x=="object")if(f in x){if(g(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 B=typeof A;throw"Invalid type of 'deviceId' = ".concat(B)}}}var O=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(O)},t.prototype.computeCanvasDrawConfig=function(r,o,c,u){if(r<=c&&o<=u){var f=(c-r)/2,g=(u-o)/2;return{x:f,y:g,width:r,height:o}}else{var m=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(m,"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?an.BORDER_SHADER_MATCH_COLOR:an.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,g=document.createElement("canvas");return g.style.width="".concat(u,"px"),g.style.height="".concat(f,"px"),g.style.display="none",g.id=Pn(c)?"qr-canvas":c,g},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 g=(o-u.width)/2,m=(c-u.height)/2;if(f.style.borderLeft="".concat(g,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderRight="".concat(g,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderTop="".concat(m,"px solid rgba(0, 0, 0, 0.48)"),f.style.borderBottom="".concat(m,"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(an.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,g,m){var v=document.createElement("div");v.style.position="absolute",v.style.backgroundColor=an.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")),m?v.style.left="".concat(g,"px"):v.style.right="".concat(g,"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})(),ol;(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"})(ol||(ol={}));const Xw={class:"scan-code"},qw={class:"btn"},Yw={class:"left-back"},Kw=y.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=cd.IconScan(),u=y.reactive({html5QrCode:null}),f=y.ref(!1),g=()=>{if(!u.html5QrCode){qe("摄像头无访问权限!");return}f.value=!0,u.html5QrCode.start({facingMode:"environment"},{fps:30,aspectRatio:1,supportedScanTypes:[Jr.SCAN_TYPE_CAMERA],showTorchButtonIfSupported:!0,showZoomSliderIfSupported:!0,defaultZoomValueIfSupported:2,useBarCodeDetectorIfSupported:!0},A=>{try{const O=new URL(A).searchParams.get("sessionId");O?o("scanSuccess",O):qe("无效的二维码")}catch{qe("无效的二维码")}E()}).catch(A=>{console.log(A),qe({message:"二维码识别失败",duration:3e3})})},m=()=>{x().then(()=>{g()})},v=()=>{E()},x=()=>il.getCameras().then(A=>{A&&A.length&&(u.html5QrCode=new il("reader"))}).catch(()=>{qe({message:"摄像头无访问权限!",duration:3e3})}),E=()=>{u.html5QrCode&&u.html5QrCode.stop().then(A=>{console.log("停止扫码",A)}).catch(A=>{console.log(A),qe("停止扫码失败")}).finally(()=>{f.value=!1})};return y.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&E()}),(A,B)=>{const O=qo;return y.openBlock(),y.createElementBlock("div",null,[y.createVNode(y.unref(Pt.TrIconButton),{icon:y.unref(c),size:"28",svgSize:"20",onClick:B[0]||(B[0]=R=>m())},null,8,["icon"]),(y.openBlock(),y.createBlock(y.Teleport,{to:"body"},[y.withDirectives(y.createElementVNode("div",Xw,[B[1]||(B[1]=y.createElementVNode("div",{class:"container"},[y.createElementVNode("div",{class:"qrcode"},[y.createElementVNode("div",{id:"reader"})])],-1)),y.createElementVNode("div",qw,[y.createElementVNode("div",Yw,[y.createVNode(O,{name:"arrow-left",onClick:v})])])],512),[[y.vShow,f.value]])]))])}}}),Jw=Kn(Kw,[["__scopeId","data-v-2d988579"]]);function Ko(t,r,o){const c=y.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const E=c.value;if(E.length===0)return"";if(r){const B=typeof r=="string"?r:r.value;if(B&&E.some(O=>O.id===B))return B}const A=E.find(B=>B.isDefault);return A?A.id:E[0].id};let f,g=!1;if(r&&typeof r!="string")f=r,g=!0,(!f.value||!c.value.some(E=>E.id===f.value))&&(f.value=u());else{let E;r&&typeof r=="string"&&(E=r),f=y.ref(E&&c.value.some(A=>A.id===E)?E:u())}(!g||o)&&y.watch(f,E=>{o&&o(E)});const m=y.computed(()=>c.value.find(E=>E.id===f.value)),v=y.computed(()=>c.value);return{selectedModelId:f,selectedModel:m,availableModels:v,setSelectedModel:E=>{c.value.find(B=>B.id===E)?f.value=E:console.warn(`[useModel] Model not found: ${E}`)}}}const Qw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const ey=Object.prototype.toString,ty=t=>ey.call(t)==="[object Object]",Ei=()=>{};function po(t){return Array.isArray(t)?t:[t]}function ny(t,r,o){return y.watch(t,r,{...o,immediate:!0})}const Ou=Qw?window:void 0;function $r(t){var r;const o=y.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function go(...t){const r=(c,u,f,g)=>(c.addEventListener(u,f,g),()=>c.removeEventListener(u,f,g)),o=y.computed(()=>{const c=po(y.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return ny(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>$r(f)))!==null&&c!==void 0?c:[Ou].filter(f=>f!=null),po(y.toValue(o.value?t[1]:t[0])),po(y.unref(o.value?t[2]:t[1])),y.toValue(o.value?t[3]:t[2])]},([c,u,f,g],m,v)=>{if(!c?.length||!u?.length||!f?.length)return;const x=ty(g)?{...g}:g,E=c.flatMap(A=>u.flatMap(B=>f.map(O=>r(A,B,O,x))));v(()=>{E.forEach(A=>A())})},{flush:"post"})}function ry(t,r,o={}){const{window:c=Ou,ignore:u=[],capture:f=!0,detectIframe:g=!1,controls:m=!1}=o;if(!c)return m?{stop:Ei,cancel:Ei,trigger:Ei}:Ei;let v=!0;const x=P=>y.toValue(u).some(Y=>{if(typeof Y=="string")return Array.from(c.document.querySelectorAll(Y)).some($=>$===P.target||P.composedPath().includes($));{const $=$r(Y);return $&&(P.target===$||P.composedPath().includes($))}});function E(P){const Y=y.toValue(P);return Y&&Y.$.subTree.shapeFlag===16}function A(P,Y){const $=y.toValue(P),U=$.$.subTree&&$.$.subTree.children;return U==null||!Array.isArray(U)?!1:U.some(W=>W.el===Y.target||Y.composedPath().includes(W.el))}const B=P=>{const Y=$r(t);if(P.target!=null&&!(!(Y instanceof Element)&&E(t)&&A(t,P))&&!(!Y||Y===P.target||P.composedPath().includes(Y))){if("detail"in P&&P.detail===0&&(v=!x(P)),!v){v=!0;return}r(P)}};let O=!1;const R=[go(c,"click",P=>{O||(O=!0,setTimeout(()=>{O=!1},0),B(P))},{passive:!0,capture:f}),go(c,"pointerdown",P=>{const Y=$r(t);v=!x(P)&&!!(Y&&!P.composedPath().includes(Y))},{passive:!0}),g&&go(c,"blur",P=>{setTimeout(()=>{var Y;const $=$r(t);((Y=c.document.activeElement)===null||Y===void 0?void 0:Y.tagName)==="IFRAME"&&!$?.contains(c.document.activeElement)&&r(P)},0)},{passive:!0})].filter(Boolean),D=()=>R.forEach(P=>P());return m?{stop:D,cancel:()=>{v=!1},trigger:P=>{v=!0,B(P),v=!1}}:D}const iy=["data-active","disabled"],oy=y.defineComponent({__name:"Button",props:{active:{type:Boolean},rounded:{type:Boolean},size:{default:"medium"},disabled:{type:Boolean}},setup(t){return(r,o)=>(y.openBlock(),y.createElementBlock("button",{class:y.normalizeClass(["button",{rounded:t.rounded,[t.size]:!0}]),"data-active":t.active||void 0,disabled:t.disabled||void 0},[y.renderSlot(r.$slots,"default",{},void 0,!0)],10,iy))}}),Jo=Kn(oy,[["__scopeId","data-v-6f582cce"]]),sy={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function ay(t,r){return y.openBlock(),y.createElementBlock("svg",sy,[...r[0]||(r[0]=[y.createElementVNode("rect",{id:"大模型",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000"},null,-1),y.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 ly={render:ay},cy={class:"button-text"},uy={class:"dropdown-menu__items"},dy=["onClick"],fy=y.defineComponent({__name:"ModelSwitch",props:y.mergeModels({modelConfigs:{}},{selectedModelId:{type:String,default:void 0,required:!1},selectedModelIdModifiers:{}}),emits:["update:selectedModelId"],setup(t){const r=t,o=y.useModel(t,"selectedModelId"),c=r.modelConfigs?Array.isArray(r.modelConfigs)?y.shallowRef(r.modelConfigs):r.modelConfigs:void 0,{selectedModel:u,availableModels:f,setSelectedModel:g}=Ko(c,o),m=y.ref(!1),v=O=>{g(O),E()},x=()=>{m.value=!m.value},E=()=>{m.value=!1},A=y.ref(null),B=y.ref(null);return ry(B,()=>{E()},{ignore:[A]}),(O,R)=>(y.openBlock(),y.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:A},[y.createVNode(Jo,{size:"small",class:"action-button",rounded:"",onClick:x},{default:y.withCtx(()=>[(y.openBlock(),y.createBlock(y.resolveDynamicComponent(y.unref(u)?.icon),{width:16,height:16,class:"selected-model__icon"})),y.createElementVNode("span",cy,y.toDisplayString(y.unref(u)?.label),1),y.createVNode(y.unref(ly),{width:16,height:16})]),_:1}),y.createVNode(y.Transition,{name:"dropdown"},{default:y.withCtx(()=>[m.value?(y.openBlock(),y.createElementBlock("div",{key:0,class:"dropdown-menu",ref_key:"dropdownMenuRef",ref:B},[y.createElementVNode("div",uy,[(y.openBlock(!0),y.createElementBlock(y.Fragment,null,y.renderList(y.unref(f),D=>(y.openBlock(),y.createElementBlock("div",{key:D.id,class:y.normalizeClass(["dropdown-menu__item",{"active-menu":D.id===o.value}]),onClick:y.withModifiers(P=>v(D.id),["stop"])},[D.icon?(y.openBlock(),y.createBlock(y.resolveDynamicComponent(D.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):y.createCommentVNode("",!0),y.createElementVNode("span",null,y.toDisplayString(D.label),1)],10,dy))),128))])],512)):y.createCommentVNode("",!0)]),_:1}),m.value?(y.openBlock(),y.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:E})):y.createCommentVNode("",!0)],512))}}),hy=Kn(fy,[["__scopeId","data-v-cee7e07b"]]),py={key:0,class:"active-count"},gy=y.defineComponent({__name:"PluginToggleButton",props:{installedPlugins:{}},emits:["click"],setup(t){const r=t,o=y.computed(()=>r.installedPlugins.filter(c=>c.enabled).length);return(c,u)=>(y.openBlock(),y.createBlock(Jo,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:y.withCtx(()=>[y.createVNode(y.unref(Ir.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=y.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(y.openBlock(),y.createElementBlock("span",py,y.toDisplayString(o.value),1)):y.createCommentVNode("",!0)]),_:1},8,["active"]))}}),my=Kn(gy,[["__scopeId","data-v-c2a16c66"]]),xy={"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 wy(t,r){return y.openBlock(),y.createElementBlock("svg",xy,[...r[0]||(r[0]=[y.createElementVNode("rect",{id:"生成式UI",width:"16.000000",height:"16.000000",x:"0.000000",y:"0.000000",fill:"currentColor","fill-opacity":"0"},null,-1),y.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 yy={render:wy},_y=y.defineComponent({__name:"GenUISwitch",props:{genuiEnabled:{type:Boolean,type:Boolean,default:!1,required:!1},genuiEnabledModifiers:{}},emits:["update:genuiEnabled"],setup(t){const r=y.useModel(t,"genuiEnabled"),o=()=>{r.value=!r.value};return(c,u)=>(y.openBlock(),y.createBlock(Jo,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:y.withCtx(()=>[y.createVNode(y.unref(yy),{width:16,height:16}),u[0]||(u[0]=y.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),vy=Kn(_y,[["__scopeId","data-v-7f3b0372"]]),Cy={class:"bubble-image-wrapper"},by=["src"],Ey=["src"],Ay=y.defineComponent({__name:"BubbleImageRenderer",props:{content:{}},setup(t){const r=y.ref(!1),o=y.ref(null),c=()=>{r.value=!0},u=()=>{r.value=!1};return y.watch(r,f=>{f&&y.nextTick(()=>{o.value?.focus()})}),(f,g)=>(y.openBlock(),y.createElementBlock("div",Cy,[y.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,by),(y.openBlock(),y.createBlock(y.Teleport,{to:"body"},[r.value?(y.openBlock(),y.createElementBlock("div",{key:0,class:"image-preview-modal",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:u,onKeydown:y.withKeys(u,["esc"])},[y.createElementVNode("button",{ref_key:"closeButtonRef",ref:o,class:"preview-close",type:"button","aria-label":"关闭预览",onClick:u},[...g[1]||(g[1]=[y.createElementVNode("svg",{viewBox:"0 0 1024 1024",width:"24",height:"24","aria-hidden":"true"},[y.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),y.createElementVNode("div",{class:"preview-content",onClick:g[0]||(g[0]=y.withModifiers(()=>{},["stop"]))},[y.createElementVNode("img",{src:t.content,alt:"预览图片"},null,8,Ey)])],32)):y.createCommentVNode("",!0)]))]))}}),Iy=Kn(Ay,[["__scopeId","data-v-91c75579"]]),Ur="https://agent.opentiny.design",Sy=[{id:"12306-mcp",name:"12306服务器",description:"12306购票搜索服务器",icon:"https://agent.opentiny.design/public-assets/icons/icon-12306.webp",enabled:!1,addState:"idle",tools:[],url:Ur+"/api/v1/mcp-server/12306/mcp",type:"StreamableHTTP"},{id:"markdown2pdf-mcp",name:"Markdown转PDF MCP服务器",description:"Markdown转PDF MCP服务器,可以将Markdown文件转换为PDF文件",icon:"https://agent.opentiny.design/public-assets/icons/icon-pdf.png",url:Ur+"/servers/markdown2pdf-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"docx-mcp",name:"Word文档MCP服务器",description:"Word文档MCP服务器,可以创建、编辑、保存Word文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-word.png",url:Ur+"/servers/excel-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"excel-mcp",name:"Excel文档MCP服务器",description:"Excel文档MCP服务器,可以创建、编辑、保存Excel文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-excel.png",url:Ur+"/servers/excel-mcp/mcp",type:"StreamableHTTP",enabled:!1,addState:"idle",tools:[]},{id:"doc-tools-mcp",name:"文档工具MCP服务器",description:"文档工具MCP服务器,可以创建、编辑、保存文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-doc.png",url:Ur+"/servers/doc-tools-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]}],Ty=`
|
|
74
|
+
`),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<ar.NUM_MASK_PATTERNS}}ar.NUM_MASK_PATTERNS=8;class ot extends x{}ot.kind="WriterException";class Re{constructor(){}static clearMatrix(e){e.clear(255)}static buildMatrix(e,n,i,s,a){Re.clearMatrix(a),Re.embedBasicPatterns(i,a),Re.embedTypeInfo(n,s,a),Re.maybeEmbedVersionInfo(i,a),Re.embedDataBits(e,s,a)}static embedBasicPatterns(e,n){Re.embedPositionDetectionPatternsAndSeparators(n),Re.embedDarkDotAtLeftBottomCorner(n),Re.maybeEmbedPositionAdjustmentPatterns(e,n),Re.embedTimingPatterns(n)}static embedTypeInfo(e,n,i){const s=new Q;Re.makeTypeInfoBits(e,n,s);for(let a=0,l=s.getSize();a<l;++a){const d=s.get(s.getSize()-1-a),h=Re.TYPE_INFO_COORDINATES[a],p=h[0],y=h[1];if(i.setBoolean(p,y,d),a<8){const E=i.getWidth()-a-1;i.setBoolean(E,8,d)}else{const I=i.getHeight()-7+(a-8);i.setBoolean(8,I,d)}}}static maybeEmbedVersionInfo(e,n){if(e.getVersionNumber()<7)return;const i=new Q;Re.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(!Re.isEmpty(i.get(p,d)))continue;let y;s<e.getSize()?(y=e.get(s),++s):y=!1,n!==255&&At.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 ot("Not all bits consumed: "+s+"/"+e.getSize())}static findMSBSet(e){return 32-U.numberOfLeadingZeros(e)}static calculateBCHCode(e,n){if(n===0)throw new v("0 polynomial");const i=Re.findMSBSet(n);for(e<<=i-1;Re.findMSBSet(e)>=i;)e^=n<<Re.findMSBSet(e)-i;return e}static makeTypeInfoBits(e,n,i){if(!ar.isValidMaskPattern(n))throw new ot("Invalid mask pattern");const s=e.getBits()<<3|n;i.appendBits(s,5);const a=Re.calculateBCHCode(s,Re.TYPE_INFO_POLY);i.appendBits(a,10);const l=new Q;if(l.appendBits(Re.TYPE_INFO_MASK_PATTERN,15),i.xor(l),i.getSize()!==15)throw new ot("should not happen but we got: "+i.getSize())}static makeVersionInfoBits(e,n){n.appendBits(e.getVersionNumber(),6);const i=Re.calculateBCHCode(e.getVersionNumber(),Re.VERSION_INFO_POLY);if(n.appendBits(i,12),n.getSize()!==18)throw new ot("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;Re.isEmpty(e.get(n,6))&&e.setNumber(n,6,i),Re.isEmpty(e.get(6,n))&&e.setNumber(6,n,i)}}static embedDarkDotAtLeftBottomCorner(e){if(e.get(8,e.getHeight()-8)===0)throw new ot;e.setNumber(8,e.getHeight()-8,1)}static embedHorizontalSeparationPattern(e,n,i){for(let s=0;s<8;++s){if(!Re.isEmpty(i.get(e+s,n)))throw new ot;i.setNumber(e+s,n,0)}}static embedVerticalSeparationPattern(e,n,i){for(let s=0;s<7;++s){if(!Re.isEmpty(i.get(e,n+s)))throw new ot;i.setNumber(e,n+s,0)}}static embedPositionAdjustmentPattern(e,n,i){for(let s=0;s<5;++s){const a=Re.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=Re.POSITION_DETECTION_PATTERN[s];for(let l=0;l<7;++l)i.setNumber(e+l,n+s,a[l])}}static embedPositionDetectionPatternsAndSeparators(e){const n=Re.POSITION_DETECTION_PATTERN[0].length;Re.embedPositionDetectionPattern(0,0,e),Re.embedPositionDetectionPattern(e.getWidth()-n,0,e),Re.embedPositionDetectionPattern(0,e.getWidth()-n,e);const i=8;Re.embedHorizontalSeparationPattern(0,i-1,e),Re.embedHorizontalSeparationPattern(e.getWidth()-i,i-1,e),Re.embedHorizontalSeparationPattern(0,e.getWidth()-i,e);const s=7;Re.embedVerticalSeparationPattern(s,0,e),Re.embedVerticalSeparationPattern(e.getHeight()-s-1,0,e),Re.embedVerticalSeparationPattern(s,e.getHeight()-s,e)}static maybeEmbedPositionAdjustmentPatterns(e,n){if(e.getVersionNumber()<2)return;const i=e.getVersionNumber()-1,s=Re.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&&Re.isEmpty(n.get(p,d))&&Re.embedPositionAdjustmentPattern(p-2,d-2,n)}}}}Re.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])]),Re.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])]),Re.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])]),Re.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])]),Re.VERSION_INFO_POLY=7973,Re.TYPE_INFO_POLY=1335,Re.TYPE_INFO_MASK_PATTERN=21522;class nd{constructor(e,n){this.dataBytes=e,this.errorCorrectionBytes=n}getDataBytes(){return this.dataBytes}getErrorCorrectionBytes(){return this.errorCorrectionBytes}}class dt{constructor(){}static calculateMaskPenalty(e){return At.applyMaskPenaltyRule1(e)+At.applyMaskPenaltyRule2(e)+At.applyMaskPenaltyRule3(e)+At.applyMaskPenaltyRule4(e)}static encode(e,n,i=null){let s=dt.DEFAULT_BYTE_MODE_ENCODING;const a=i!==null&&i.get(Dt.CHARACTER_SET)!==void 0;a&&(s=i.get(Dt.CHARACTER_SET).toString());const l=this.chooseMode(e,s),d=new Q;if(l===Ne.BYTE&&(a||dt.DEFAULT_BYTE_MODE_ENCODING!==s)){const ce=S.getCharacterSetECIByName(s);ce!==void 0&&this.appendECI(ce,d)}this.appendModeInfo(l,d);const h=new Q;this.appendBytes(e,l,h,s);let p;if(i!==null&&i.get(Dt.QR_VERSION)!==void 0){const ce=Number.parseInt(i.get(Dt.QR_VERSION).toString(),10);p=Ie.getVersionForNumber(ce);const ae=this.calculateBitsNeeded(l,d,h,p);if(!this.willFit(ae,p,n))throw new ot("Data too big for requested version")}else p=this.recommendVersion(n,l,d,h);const y=new Q;y.appendBitArray(d);const E=l===Ne.BYTE?h.getSizeInBytes():e.length;this.appendLengthInfo(E,p,l,y),y.appendBitArray(h);const I=p.getECBlocksForLevel(n),k=p.getTotalCodewords()-I.getTotalECCodewords();this.terminateBits(k,y);const L=this.interleaveWithECBytes(y,p.getTotalCodewords(),k,I.getNumBlocks()),F=new ar;F.setECLevel(n),F.setMode(l),F.setVersion(p);const H=p.getDimensionForVersion(),Y=new fi(H,H),le=this.chooseMaskPattern(L,n,p,Y);return F.setMaskPattern(le),Re.buildMatrix(L,n,p,le,Y),F.setMatrix(Y),F}static recommendVersion(e,n,i,s){const a=this.calculateBitsNeeded(n,i,s,Ie.getVersionForNumber(1)),l=this.chooseVersion(a,e),d=this.calculateBitsNeeded(n,i,s,l);return this.chooseVersion(d,e)}static calculateBitsNeeded(e,n,i,s){return n.getSize()+e.getCharacterCountBits(s)+i.getSize()}static getAlphanumericCode(e){return e<dt.ALPHANUMERIC_TABLE.length?dt.ALPHANUMERIC_TABLE[e]:-1}static chooseMode(e,n=null){if(S.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(e))return Ne.KANJI;let i=!1,s=!1;for(let a=0,l=e.length;a<l;++a){const d=e.charAt(a);if(dt.isDigit(d))i=!0;else if(this.getAlphanumericCode(d.charCodeAt(0))!==-1)s=!0;else return Ne.BYTE}return s?Ne.ALPHANUMERIC:i?Ne.NUMERIC:Ne.BYTE}static isOnlyDoubleByteKanji(e){let n;try{n=ye.encode(e,S.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<ar.NUM_MASK_PATTERNS;d++){Re.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=Ie.getVersionForNumber(i);if(dt.willFit(e,s,n))return s}throw new ot("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 ot("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 ot("Bits size does not equal capacity")}static getNumDataBytesAndNumECBytesForBlockID(e,n,i,s,a,l){if(s>=i)throw new ot("Block ID too large");const d=e%i,h=i-d,p=Math.floor(e/i),y=p+1,E=Math.floor(n/i),I=E+1,k=p-E,L=y-I;if(k!==L)throw new ot("EC bytes mismatch");if(i!==h+d)throw new ot("RS blocks mismatch");if(e!==(E+k)*h+(I+L)*d)throw new ot("Total bytes mismatch");s<h?(a[0]=E,l[0]=k):(a[0]=I,l[0]=L)}static interleaveWithECBytes(e,n,i,s){if(e.getSizeInBytes()!==i)throw new ot("Number of bits and data bytes does not match");let a=0,l=0,d=0;const h=new Array;for(let y=0;y<s;++y){const E=new Int32Array(1),I=new Int32Array(1);dt.getNumDataBytesAndNumECBytesForBlockID(n,i,s,y,E,I);const k=E[0],L=new Uint8Array(k);e.toBytes(8*a,L,0,k);const F=dt.generateECBytes(L,I[0]);h.push(new nd(L,F)),l=Math.max(l,k),d=Math.max(d,F.length),a+=E[0]}if(i!==a)throw new ot("Data bytes does not match offset");const p=new Q;for(let y=0;y<l;++y)for(const E of h){const I=E.getDataBytes();y<I.length&&p.appendBits(I[y],8)}for(let y=0;y<d;++y)for(const E of h){const I=E.getErrorCorrectionBytes();y<I.length&&p.appendBits(I[y],8)}if(n!==p.getSizeInBytes())throw new ot("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(be.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 ot(e+" is bigger than "+((1<<a)-1));s.appendBits(e,a)}static appendBytes(e,n,i,s){switch(n){case Ne.NUMERIC:dt.appendNumericBytes(e,i);break;case Ne.ALPHANUMERIC:dt.appendAlphanumericBytes(e,i);break;case Ne.BYTE:dt.append8BitBytes(e,i,s);break;case Ne.KANJI:dt.appendKanjiBytes(e,i);break;default:throw new ot("Invalid mode: "+n)}}static getDigit(e){return e.charCodeAt(0)-48}static isDigit(e){const n=dt.getDigit(e);return n>=0&&n<=9}static appendNumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getDigit(e.charAt(s));if(s+2<i){const l=dt.getDigit(e.charAt(s+1)),d=dt.getDigit(e.charAt(s+2));n.appendBits(a*100+l*10+d,10),s+=3}else if(s+1<i){const l=dt.getDigit(e.charAt(s+1));n.appendBits(a*10+l,7),s+=2}else n.appendBits(a,4),s++}}static appendAlphanumericBytes(e,n){const i=e.length;let s=0;for(;s<i;){const a=dt.getAlphanumericCode(e.charCodeAt(s));if(a===-1)throw new ot;if(s+1<i){const l=dt.getAlphanumericCode(e.charCodeAt(s+1));if(l===-1)throw new ot;n.appendBits(a*45+l,11),s+=2}else n.appendBits(a,6),s++}}static append8BitBytes(e,n,i){let s;try{s=ye.encode(e,i)}catch(a){throw new ot(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=ye.encode(e,S.SJIS)}catch(a){throw new ot(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 ot("Invalid byte sequence");const y=(p>>8)*192+(p&255);n.appendBits(y,13)}}static appendECI(e,n){n.appendBits(Ne.ECI.getBits(),4),n.appendBits(e.getValue(),8)}}dt.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),dt.DEFAULT_BYTE_MODE_ENCODING=S.UTF8.getName();class lr{write(e,n,i,s=null){if(e.length===0)throw new v("Found empty contents");if(n<0||i<0)throw new v("Requested dimensions are too small: "+n+"x"+i);let a=ct.L,l=lr.QUIET_ZONE_SIZE;s!==null&&(s.get(Dt.ERROR_CORRECTION)!==void 0&&(a=ct.fromString(s.get(Dt.ERROR_CORRECTION).toString())),s.get(Dt.MARGIN)!==void 0&&(l=Number.parseInt(s.get(Dt.MARGIN).toString(),10)));const d=dt.encode(e,a,s);return this.renderResult(d,n,i,l)}writeToDom(e,n,i,s,a=null){typeof e=="string"&&(e=document.querySelector(e));const l=this.write(n,i,s,a);e&&e.appendChild(l)}renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Wt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),k=Math.floor((y-l*I)/2),L=Math.floor((E-d*I)/2),F=this.createSVGElement(y,E);for(let H=0,Y=L;H<d;H++,Y+=I)for(let le=0,ce=k;le<l;le++,ce+=I)if(a.get(le,H)===1){const ae=this.createSvgRectElement(ce,Y,I,I);F.appendChild(ae)}return F}createSVGElement(e,n){const i=document.createElementNS(lr.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(lr.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}}lr.QUIET_ZONE_SIZE=4,lr.SVG_NS="http://www.w3.org/2000/svg";class br{encode(e,n,i,s,a){if(e.length===0)throw new v("Found empty contents");if(n!==Ce.QR_CODE)throw new v("Can only encode QR_CODE, but got "+n);if(i<0||s<0)throw new v(`Requested dimensions are too small: ${i}x${s}`);let l=ct.L,d=br.QUIET_ZONE_SIZE;a!==null&&(a.get(Dt.ERROR_CORRECTION)!==void 0&&(l=ct.fromString(a.get(Dt.ERROR_CORRECTION).toString())),a.get(Dt.MARGIN)!==void 0&&(d=Number.parseInt(a.get(Dt.MARGIN).toString(),10)));const h=dt.encode(e,l,a);return br.renderResult(h,i,s,d)}static renderResult(e,n,i,s){const a=e.getMatrix();if(a===null)throw new Wt;const l=a.getWidth(),d=a.getHeight(),h=l+s*2,p=d+s*2,y=Math.max(n,h),E=Math.max(i,p),I=Math.min(Math.floor(y/h),Math.floor(E/p)),k=Math.floor((y-l*I)/2),L=Math.floor((E-d*I)/2),F=new Me(y,E);for(let H=0,Y=L;H<d;H++,Y+=I)for(let le=0,ce=k;le<l;le++,ce+=I)a.get(le,H)===1&&F.setRegion(ce,Y,I,I);return F}}br.QUIET_ZONE_SIZE=4;class rd{encode(e,n,i,s,a){let l;switch(n){case Ce.QR_CODE:l=new br;break;default:throw new v("No encoder available for format "+n)}return l.encode(e,n,i,s,a)}}class kn extends J{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 v("Crop rectangle does not fit within image data.");h&&this.reverseHorizontal(l,d)}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("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 D.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 D.arraycopy(this.yuvData,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.arraycopy(this.yuvData,a,s,d,e),a+=this.dataWidth}return s}isCropSupported(){return!0}crop(e,n,i,s){return new kn(this.yuvData,this.dataWidth,this.dataHeight,this.left+e,this.top+n,i,s,!1)}renderThumbnail(){const e=this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR,n=this.getHeight()/kn.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*kn.THUMBNAIL_SCALE_FACTOR]&255;i[d+h]=4278190080|p*65793}a+=this.dataWidth*kn.THUMBNAIL_SCALE_FACTOR}return i}getThumbnailWidth(){return this.getWidth()/kn.THUMBNAIL_SCALE_FACTOR}getThumbnailHeight(){return this.getHeight()/kn.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 me(this)}}kn.THUMBNAIL_SCALE_FACTOR=2;class Ji extends J{constructor(e,n,i,s,a,l,d){if(super(n,i),this.dataWidth=s,this.dataHeight=a,this.left=l,this.top=d,e.BYTES_PER_ELEMENT===4){const h=n*i,p=new Uint8ClampedArray(h);for(let y=0;y<h;y++){const E=e[y],I=E>>16&255,k=E>>7&510,L=E&255;p[y]=(I+k+L)/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 v("Crop rectangle does not fit within image data.")}getRow(e,n){if(e<0||e>=this.getHeight())throw new v("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 D.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 D.arraycopy(this.luminances,a,s,0,i),s;for(let l=0;l<n;l++){const d=l*e;D.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 me(this)}}class ps extends S{static forName(e){return this.getCharacterSetECIByName(e)}}class Qi{}Qi.ISO_8859_1=S.ISO8859_1;class ms{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 gs{static singletonList(e){return[e]}static min(e,n){return e.sort(n)[0]}}class id{constructor(e){this.previous=e}getPrevious(){return this.previous}}class Er extends id{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,"<"+U.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 od(b,e,n){return new eo(b,e,n)}function Lr(b,e,n){return new Er(b,e,n)}const sd=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],Yn=0,hi=1,gn=2,xs=3,Rn=4,ad=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 ld(b){for(let e of b)Z.fill(e,-1);return b[Yn][Rn]=0,b[hi][Rn]=0,b[hi][Yn]=28,b[xs][Rn]=0,b[gn][Rn]=0,b[gn][Yn]=15,b}const ys=ld(Z.createInt32Array(6,6));class Mn{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=Lr(s,l&65535,l>>16),i+=l>>16}let a=e===gn?4:5;return s=Lr(s,n,a),new Mn(s,e,0,i+a)}shiftAndAppend(e,n){let i=this.token,s=this.mode===gn?4:5;return i=Lr(i,ys[this.mode][e],s),i=Lr(i,n,5),new Mn(i,this.mode,0,this.bitCount+s+5)}addBinaryShiftChar(e){let n=this.token,i=this.mode,s=this.bitCount;if(this.mode===Rn||this.mode===gn){let d=to[i][Yn];n=Lr(n,d&65535,d>>16),s+=d>>16,i=Yn}let a=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new Mn(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=od(n,e-this.binaryShiftByteCount,this.binaryShiftByteCount),new Mn(n,this.mode,0,this.bitCount)}isBetterThanOrEqualTo(e){let n=this.bitCount+(to[this.mode][e.mode]>>16);return this.binaryShiftByteCount<e.binaryShiftByteCount?n+=Mn.calculateBinaryShiftCost(e)-Mn.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 Q;for(const s of n)s.appendTo(i,e);return i}toString(){return re.format("%s bits=%d bytes=%d",sd[this.mode],this.bitCount,this.binaryShiftByteCount)}static calculateBinaryShiftCost(e){return e.binaryShiftByteCount>62?21:e.binaryShiftByteCount>31?20:e.binaryShiftByteCount>0?10:0}}Mn.INITIAL_STATE=new Mn(ad,Yn,0,0);function cd(b){const e=re.getCharCode(" "),n=re.getCharCode("."),i=re.getCharCode(",");b[Yn][e]=1;const s=re.getCharCode("Z"),a=re.getCharCode("A");for(let I=a;I<=s;I++)b[Yn][I]=I-a+2;b[hi][e]=1;const l=re.getCharCode("z"),d=re.getCharCode("a");for(let I=d;I<=l;I++)b[hi][I]=I-d+2;b[gn][e]=1;const h=re.getCharCode("9"),p=re.getCharCode("0");for(let I=p;I<=h;I++)b[gn][I]=I-p+2;b[gn][i]=12,b[gn][n]=13;const y=["\0"," ","","","","","","","\x07","\b"," ",`
|
|
75
|
+
`,"\v","\f","\r","\x1B","","","","","@","\\","^","_","`","|","~",""];for(let I=0;I<y.length;I++)b[xs][re.getCharCode(y[I])]=I;const E=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"];for(let I=0;I<E.length;I++)re.getCharCode(E[I])>0&&(b[Rn][re.getCharCode(E[I])]=I);return b}const no=cd(Z.createInt32Array(5,256));class Fr{constructor(e){this.text=e}encode(){const e=re.getCharCode(" "),n=re.getCharCode(`
|
|
76
|
+
`);let i=gs.singletonList(Mn.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 re.getCharCode("\r"):l=d===n?2:0;break;case re.getCharCode("."):l=d===e?3:0;break;case re.getCharCode(","):l=d===e?4:0;break;case re.getCharCode(":"):l=d===e?5:0;break;default:l=0}l>0?(i=Fr.updateStateListForPair(i,a,l),a++):i=this.updateStateListForChar(i,a)}return gs.min(i,(a,l)=>a.getBitCount()-l.getBitCount()).toBitArray(this.text)}updateStateListForChar(e,n){const i=[];for(let s of e)this.updateStateForChar(s,n,i);return Fr.simplifyStates(i)}updateStateForChar(e,n,i){let s=this.text[n]&255,a=no[e.getMode()][s]>0,l=null;for(let d=0;d<=Rn;d++){let h=no[d][s];if(h>0){if(l==null&&(l=e.endBinaryShift(n)),!a||d===e.getMode()||d===gn){const p=l.latchAndAppend(d,h);i.push(p)}if(!a&&ys[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(Rn,i)),e.getMode()!==Rn&&s.push(a.shiftAndAppend(Rn,i)),i===3||i===4){let l=a.latchAndAppend(gn,16-i).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 i of e){let s=!0;for(const a of n){if(a.isBetterThanOrEqualTo(i)){s=!1;break}i.isBetterThanOrEqualTo(a)&&(n=n.filter(l=>l!==a))}s&&n.push(i)}return n}}class Ge{constructor(){}static encodeBytes(e){return Ge.encode(e,Ge.DEFAULT_EC_PERCENT,Ge.DEFAULT_AZTEC_LAYERS)}static encode(e,n,i){let s=new Fr(e).encode(),a=U.truncDivision(s.getSize()*n,100)+11,l=s.getSize()+a,d,h,p,y,E;if(i!==Ge.DEFAULT_AZTEC_LAYERS){if(d=i<0,h=Math.abs(i),h>(d?Ge.MAX_NB_BITS_COMPACT:Ge.MAX_NB_BITS))throw new v(re.format("Illegal value %s for layers",i));p=Ge.totalBitsInLayer(h,d),y=Ge.WORD_SIZE[h];let ae=p-p%y;if(E=Ge.stuffBits(s,y),E.getSize()+a>ae)throw new v("Data to large for user specified layer");if(d&&E.getSize()>y*64)throw new v("Data to large for user specified layer")}else{y=0,E=null;for(let ae=0;;ae++){if(ae>Ge.MAX_NB_BITS)throw new v("Data too large for an Aztec code");if(d=ae<=3,h=d?ae+1:ae,p=Ge.totalBitsInLayer(h,d),l>p)continue;(E==null||y!==Ge.WORD_SIZE[h])&&(y=Ge.WORD_SIZE[h],E=Ge.stuffBits(s,y));let We=p-p%y;if(!(d&&E.getSize()>y*64)&&E.getSize()+a<=We)break}}let I=Ge.generateCheckWords(E,p,y),k=E.getSize()/y,L=Ge.generateModeMessage(d,h,k),F=(d?11:14)+h*4,H=new Int32Array(F),Y;if(d){Y=F;for(let ae=0;ae<H.length;ae++)H[ae]=ae}else{Y=F+1+2*U.truncDivision(U.truncDivision(F,2)-1,15);let ae=U.truncDivision(F,2),We=U.truncDivision(Y,2);for(let Fe=0;Fe<ae;Fe++){let nn=Fe+U.truncDivision(Fe,15);H[ae-Fe-1]=We-nn-1,H[ae+Fe]=We+nn+1}}let le=new Me(Y);for(let ae=0,We=0;ae<h;ae++){let Fe=(h-ae)*4+(d?9:12);for(let nn=0;nn<Fe;nn++){let yn=nn*2;for(let rn=0;rn<2;rn++)I.get(We+yn+rn)&&le.set(H[ae*2+rn],H[ae*2+nn]),I.get(We+Fe*2+yn+rn)&&le.set(H[ae*2+nn],H[F-1-ae*2-rn]),I.get(We+Fe*4+yn+rn)&&le.set(H[F-1-ae*2-rn],H[F-1-ae*2-nn]),I.get(We+Fe*6+yn+rn)&&le.set(H[F-1-ae*2-nn],H[ae*2+rn])}We+=Fe*8}if(Ge.drawModeMessage(le,d,Y,L),d)Ge.drawBullsEye(le,U.truncDivision(Y,2),5);else{Ge.drawBullsEye(le,U.truncDivision(Y,2),7);for(let ae=0,We=0;ae<U.truncDivision(F,2)-1;ae+=15,We+=16)for(let Fe=U.truncDivision(Y,2)&1;Fe<Y;Fe+=2)le.set(U.truncDivision(Y,2)-We,Fe),le.set(U.truncDivision(Y,2)+We,Fe),le.set(Fe,U.truncDivision(Y,2)-We),le.set(Fe,U.truncDivision(Y,2)+We)}let ce=new ms;return ce.setCompact(d),ce.setSize(Y),ce.setLayers(h),ce.setCodeWords(k),ce.setMatrix(le),ce}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 Q;return e?(s.appendBits(n-1,2),s.appendBits(i-1,6),s=Ge.generateCheckWords(s,28,4)):(s.appendBits(n-1,5),s.appendBits(i-1,11),s=Ge.generateCheckWords(s,40,4)),s}static drawModeMessage(e,n,i,s){let a=U.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+U.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(Ge.getGF(i)),l=U.truncDivision(n,i),d=Ge.bitsToWords(e,i,l);a.encode(d,l-s);let h=n%i,p=new Q;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 be.AZTEC_PARAM;case 6:return be.AZTEC_DATA_6;case 8:return be.AZTEC_DATA_8;case 10:return be.AZTEC_DATA_10;case 12:return be.AZTEC_DATA_12;default:throw new v("Unsupported word size "+e)}}static stuffBits(e,n){let i=new Q,s=e.getSize(),a=(1<<n)-2;for(let l=0;l<s;l+=n){let d=0;for(let h=0;h<n;h++)(l+h>=s||e.get(l+h))&&(d|=1<<n-1-h);(d&a)===a?(i.appendBits(d&a,n),l--):(d&a)===0?(i.appendBits(d|1,n),l--):i.appendBits(d,n)}return i}static totalBitsInLayer(e,n){return((n?88:112)+16*e)*e}}Ge.DEFAULT_EC_PERCENT=33,Ge.DEFAULT_AZTEC_LAYERS=0,Ge.MAX_NB_BITS=32,Ge.MAX_NB_BITS_COMPACT=4,Ge.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]);class 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=Ge.DEFAULT_EC_PERCENT,h=Ge.DEFAULT_AZTEC_LAYERS;return a!=null&&(a.has(Dt.CHARACTER_SET)&&(l=ps.forName(a.get(Dt.CHARACTER_SET).toString())),a.has(Dt.ERROR_CORRECTION)&&(d=U.parseInt(a.get(Dt.ERROR_CORRECTION).toString())),a.has(Dt.AZTEC_LAYERS)&&(h=U.parseInt(a.get(Dt.AZTEC_LAYERS).toString()))),pi.encodeLayers(e,n,i,s,l,d,h)}static encodeLayers(e,n,i,s,a,l,d){if(n!==Ce.AZTEC)throw new v("Can only encode AZTEC, but got "+n);let h=Ge.encode(re.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 Wt;let a=s.getWidth(),l=s.getHeight(),d=Math.max(n,a),h=Math.max(i,l),p=Math.min(d/a,h/l),y=(d-a*p)/2,E=(h-l*p)/2,I=new Me(d,h);for(let k=0,L=E;k<l;k++,L+=p)for(let F=0,H=y;F<a;F++,H+=p)s.get(F,k)&&I.setRegion(H,L,p,p);return I}}o.AbstractExpandedDecoder=Vi,o.ArgumentException=A,o.ArithmeticException=yt,o.AztecCode=ms,o.AztecCodeReader=lt,o.AztecCodeWriter=pi,o.AztecDecoder=Xe,o.AztecDetector=qe,o.AztecDetectorResult=$n,o.AztecEncoder=Ge,o.AztecHighLevelEncoder=Fr,o.AztecPoint=oe,o.BarcodeFormat=Ce,o.Binarizer=M,o.BinaryBitmap=P,o.BitArray=Q,o.BitMatrix=Me,o.BitSource=Wi,o.BrowserAztecCodeReader=xr,o.BrowserBarcodeReader=zu,o.BrowserCodeReader=vt,o.BrowserDatamatrixCodeReader=Zu,o.BrowserMultiFormatReader=Qu,o.BrowserPDF417Reader=ed,o.BrowserQRCodeReader=td,o.BrowserQRCodeSvgWriter=lr,o.CharacterSetECI=S,o.ChecksumException=O,o.Code128Reader=he,o.Code39Reader=Nt,o.DataMatrixDecodedBitStreamParser=jn,o.DataMatrixReader=Gn,o.DecodeHintType=V,o.DecoderResult=Ht,o.DefaultGridSampler=rr,o.DetectorResult=Bn,o.EAN13Reader=Ln,o.EncodeHintType=Dt,o.Exception=x,o.FormatException=z,o.GenericGF=be,o.GenericGFPoly=Oe,o.GlobalHistogramBinarizer=ge,o.GridSampler=Hn,o.GridSamplerInstance=R,o.HTMLCanvasElementLuminanceSource=fe,o.HybridBinarizer=ne,o.ITFReader=nt,o.IllegalArgumentException=v,o.IllegalStateException=Wt,o.InvertedLuminanceSource=me,o.LuminanceSource=J,o.MathUtils=Ze,o.MultiFormatOneDReader=vr,o.MultiFormatReader=hs,o.MultiFormatWriter=rd,o.NotFoundException=$,o.OneDReader=bt,o.PDF417DecodedBitStreamParser=q,o.PDF417DecoderErrorCorrection=as,o.PDF417Reader=Zt,o.PDF417ResultMetadata=cs,o.PerspectiveTransform=Bt,o.PlanarYUVLuminanceSource=kn,o.QRCodeByteMatrix=fi,o.QRCodeDataMask=pn,o.QRCodeDecodedBitStreamParser=wt,o.QRCodeDecoderErrorCorrectionLevel=ct,o.QRCodeDecoderFormatInformation=Gt,o.QRCodeEncoder=dt,o.QRCodeEncoderQRCode=ar,o.QRCodeMaskUtil=At,o.QRCodeMatrixUtil=Re,o.QRCodeMode=Ne,o.QRCodeReader=Xn,o.QRCodeVersion=Ie,o.QRCodeWriter=br,o.RGBLuminanceSource=Ji,o.RSS14Reader=Et,o.RSSExpandedReader=se,o.ReaderException=di,o.ReedSolomonDecoder=In,o.ReedSolomonEncoder=Ki,o.ReedSolomonException=Xt,o.Result=Ee,o.ResultMetadataType=Ue,o.ResultPoint=ve,o.StringUtils=re,o.UnsupportedOperationException=Te,o.VideoInputDevice=ie,o.WhiteRectangleDetector=Jt,o.WriterException=ot,o.ZXingArrays=Z,o.ZXingCharset=ps,o.ZXingInteger=U,o.ZXingStandardCharsets=Qi,o.ZXingStringBuilder=xe,o.ZXingStringEncoding=ye,o.ZXingSystem=D,o.createAbstractExpandedDecoder=os,Object.defineProperty(o,"__esModule",{value:!0})}))})(Wr,Wr.exports)),Wr.exports}var ft=Oy();const ky=Ty(ft),Ry=md({__proto__:null,default:ky},[ft]);var nl=(function(){function t(r,o,c){if(this.formatMap=new Map([[_e.QR_CODE,ft.BarcodeFormat.QR_CODE],[_e.AZTEC,ft.BarcodeFormat.AZTEC],[_e.CODABAR,ft.BarcodeFormat.CODABAR],[_e.CODE_39,ft.BarcodeFormat.CODE_39],[_e.CODE_93,ft.BarcodeFormat.CODE_93],[_e.CODE_128,ft.BarcodeFormat.CODE_128],[_e.DATA_MATRIX,ft.BarcodeFormat.DATA_MATRIX],[_e.MAXICODE,ft.BarcodeFormat.MAXICODE],[_e.ITF,ft.BarcodeFormat.ITF],[_e.EAN_13,ft.BarcodeFormat.EAN_13],[_e.EAN_8,ft.BarcodeFormat.EAN_8],[_e.PDF_417,ft.BarcodeFormat.PDF_417],[_e.RSS_14,ft.BarcodeFormat.RSS_14],[_e.RSS_EXPANDED,ft.BarcodeFormat.RSS_EXPANDED],[_e.UPC_A,ft.BarcodeFormat.UPC_A],[_e.UPC_E,ft.BarcodeFormat.UPC_E],[_e.UPC_EAN_EXTENSION,ft.BarcodeFormat.UPC_EAN_EXTENSION]]),this.reverseFormatMap=this.createReverseFormatMap(),!Ry)throw"Use html5qrcode.min.js without edit, ZXing not found.";this.verbose=o,this.logger=c;var u=this.createZXingFormats(r),f=new Map;f.set(ft.DecodeHintType.POSSIBLE_FORMATS,u),f.set(ft.DecodeHintType.TRY_HARDER,!1),this.hints=f}return t.prototype.decodeAsync=function(r){var o=this;return new Promise(function(c,u){try{c(o.decode(r))}catch(f){u(f)}})},t.prototype.decode=function(r){var o=new ft.MultiFormatReader(this.verbose,this.hints),c=new ft.HTMLCanvasElementLuminanceSource(r),u=new ft.BinaryBitmap(new ft.HybridBinarizer(c)),f=o.decode(u);return{text:f.text,format:Ru.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})(),My=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(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},Dy=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(A){return C([x,A])}}function C(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(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},rl=(function(){function t(r,o,c){if(this.formatMap=new Map([[_e.QR_CODE,"qr_code"],[_e.AZTEC,"aztec"],[_e.CODABAR,"codabar"],[_e.CODE_39,"code_39"],[_e.CODE_93,"code_93"],[_e.CODE_128,"code_128"],[_e.DATA_MATRIX,"data_matrix"],[_e.ITF,"itf"],[_e.EAN_13,"ean_13"],[_e.EAN_8,"ean_8"],[_e.PDF_417,"pdf417"],[_e.UPC_A,"upc_a"],[_e.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 My(this,void 0,void 0,function(){var o,c;return Dy(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:Ru.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})(),il=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(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},ol=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(A){return C([x,A])}}function C(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(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Py=(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&&rl.isSupported()?(this.primaryDecoder=new rl(r,c,u),this.secondaryDecoder=new nl(r,c,u)):this.primaryDecoder=new nl(r,c,u)}return t.prototype.decodeAsync=function(r){return il(this,void 0,void 0,function(){var o;return ol(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 il(this,void 0,void 0,function(){var o,c;return ol(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})(),es=(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(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}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(A){return C([x,A])}}function C(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(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Du=(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})(),By=(function(t){es(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})(Du),Ly=(function(t){es(r,t);function r(o){return t.call(this,"zoom",o)||this}return r})(By),Fy=(function(t){es(r,t);function r(o){return t.call(this,"torch",o)||this}return r})(Du),Uy=(function(){function t(r){this.track=r}return t.prototype.zoomFeature=function(){return new Ly(this.track)},t.prototype.torchFeature=function(){return new Fy(this.track)},t})(),zy=(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 Uy(this.getFirstTrackOrFail())},t})(),Vy=(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,zy.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})(),sl=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(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},al=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(A){return C([x,A])}}function C(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(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Zy=(function(){function t(){}return t.failIfNotSupported=function(){return sl(this,void 0,void 0,function(){return al(this,function(r){if(!navigator.mediaDevices)throw"navigator.mediaDevices not supported";return[2,new t]})})},t.prototype.create=function(r){return sl(this,void 0,void 0,function(){return al(this,function(o){return[2,Vy.create(r)]})})},t})(),$y=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(A){try{x(c.next(A))}catch(v){m(v)}}function C(A){try{x(c.throw(A))}catch(v){m(v)}}function x(A){A.done?f(A.value):u(A.value).then(g,C)}x((c=c.apply(t,r||[])).next())})},Hy=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(A){return C([x,A])}}function C(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(A){x=[6,A],u=0}finally{c=f=0}if(x[0]&5)throw x[1];return{value:x[0]?x[1]:void 0,done:!0}}},Wy=(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=Nr.unableToQuerySupportedDevices();return t.isHttpsOrLocalhost()||(r=Nr.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 $y(this,void 0,void 0,function(){var r,o,c,u,f,m,g;return Hy(this,function(C){switch(C.label){case 0:return r=function(x){for(var A=x.getVideoTracks(),v=0,P=A;v<P.length;v++){var O=P[v];O.enabled=!1,O.stop(),x.removeTrack(O)}},[4,navigator.mediaDevices.getUserMedia({audio:!1,video:!0})];case 1:return o=C.sent(),[4,navigator.mediaDevices.enumerateDevices()];case 2:for(c=C.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,C=f;g<C.length;g++){var x=C[g];x.kind==="video"&&m.push({id:x.id,label:x.label})}r(m)},u=MediaStreamTrack;u.getSources(c)})},t})(),It;(function(t){t[t.UNKNOWN=0]="UNKNOWN",t[t.NOT_STARTED=1]="NOT_STARTED",t[t.SCANNING=2]="SCANNING",t[t.PAUSED=3]="PAUSED"})(It||(It={}));var jy=(function(){function t(){this.state=It.NOT_STARTED,this.onGoingTransactionNewState=It.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===It.UNKNOWN)throw"Transaction is already cancelled, cannot execute().";var r=this.onGoingTransactionNewState;this.onGoingTransactionNewState=It.UNKNOWN,this.directTransition(r)},t.prototype.cancel=function(){if(this.onGoingTransactionNewState===It.UNKNOWN)throw"Transaction is already cancelled, cannot cancel().";this.onGoingTransactionNewState=It.UNKNOWN},t.prototype.getState=function(){return this.state},t.prototype.failIfTransitionOngoing=function(){if(this.onGoingTransactionNewState!==It.UNKNOWN)throw"Cannot transition to a new state, already under transition"},t.prototype.validateTransition=function(r){switch(this.state){case It.UNKNOWN:throw"Transition from unknown is not allowed";case It.NOT_STARTED:this.failIfNewStateIs(r,[It.PAUSED]);break;case It.SCANNING:break;case It.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})(),Gy=(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()===It.NOT_STARTED},t.prototype.isScanning=function(){return this.stateManager.getState()!==It.NOT_STARTED},t.prototype.isStrictlyScanning=function(){return this.stateManager.getState()===It.SCANNING},t.prototype.isPaused=function(){return this.stateManager.getState()===It.PAUSED},t})(),Xy=(function(){function t(){}return t.create=function(){return new Gy(new jy)},t})(),qy=(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)}})(),ln=(function(t){qy(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})(Ay),Yy=(function(){function t(r,o){this.logger=o,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?Mu.isMediaStreamConstraintsValid(this.videoConstraints,this.logger):(this.logger.logError("Empty videoConstraints",!0),!1)},t.prototype.isShadedBoxEnabled=function(){return!Fn(this.qrbox)},t.create=function(r,o){return new t(r,o)},t})(),ll=(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 Sy(this.verbose),this.qrcode=new Py(this.getSupportedFormats(o),this.getUseBarCodeDetectorIfSupported(c),this.verbose,this.logger),this.foreverScanTimeout,this.shouldScan=!0,this.stateManagerProxy=Xy.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=Yy.create(o,this.logger);this.clearElement();var C=!1;g.videoConstraints&&(g.isMediaStreamConstraintsValid()?C=!0:this.logger.logError("'videoConstraints' is not valid 'MediaStreamConstraints, it will be ignored.'",!0));var x=C,A=document.getElementById(this.elementId);A.clientWidth?A.clientWidth:ln.DEFAULT_WIDTH,A.style.position="relative",this.shouldScan=!0,this.element=A;var v=this,P=this.stateManagerProxy.startTransition(It.SCANNING);return new Promise(function(O,M){var D=x?g.videoConstraints:v.createVideoConstraints(r);if(!D){P.cancel(),M("videoConstraints should be defined");return}var B={};(!x||g.aspectRatio)&&(B.aspectRatio=g.aspectRatio);var G={onRenderSurfaceReady:function(Z,U){v.setupUi(Z,U,g),v.isScanning=!0,v.foreverScan(g,c,m)}};Zy.failIfNotSupported().then(function(Z){Z.create(D).then(function(U){return U.render(f.element,B,G).then(function(Q){v.renderedCamera=Q,P.execute(),O(null)}).catch(function(Q){P.cancel(),M(Q)})}).catch(function(U){P.cancel(),M(Nr.errorGettingUserMedia(U))})}).catch(function(Z){P.cancel(),M(Nr.cameraStreamingNotSupported())})})},t.prototype.pause=function(r){if(!this.stateManagerProxy.isStrictlyScanning())throw"Cannot pause, scanner is not scanning.";this.stateManagerProxy.directTransition(It.PAUSED),this.showPausedState(),(Fn(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(It.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(It.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)}},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(Fn(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,C=m.height,x=document.getElementById(c.elementId),A=x.clientWidth?x.clientWidth:ln.DEFAULT_WIDTH,v=Math.max(x.clientHeight?x.clientHeight:C,ln.FILE_SCAN_MIN_HEIGHT),P=c.computeCanvasDrawConfig(g,C,A,v);if(o){var O=c.createCanvasElement(A,v,"qr-canvas-visible");O.style.display="inline-block",x.appendChild(O);var M=O.getContext("2d");if(!M)throw"Unable to get 2d context from canvas";M.canvas.width=A,M.canvas.height=v,M.drawImage(m,0,0,g,C,P.x,P.y,P.width,P.height)}var D=ln.FILE_SCAN_HIDDEN_CANVAS_PADDING,B=Math.max(m.width,P.width),G=Math.max(m.height,P.height),Z=B+2*D,U=G+2*D,Q=c.createCanvasElement(Z,U);x.appendChild(Q);var K=Q.getContext("2d");if(!K)throw"Unable to get 2d context from canvas";K.canvas.width=Z,K.canvas.height=U,K.drawImage(m,0,0,g,C,D,D,B,G);try{c.qrcode.decodeRobustlyAsync(Q).then(function(V){u(el.createFromQrcodeResult(V))}).catch(f)}catch(V){f("QR code parse error, error = ".concat(V))}},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 Wy.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(!Mu.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=[_e.QR_CODE,_e.AZTEC,_e.CODABAR,_e.CODE_39,_e.CODE_93,_e.CODE_128,_e.DATA_MATRIX,_e.MAXICODE,_e.ITF,_e.EAN_13,_e.EAN_8,_e.PDF_417,_e.RSS_14,_e.RSS_EXPANDED,_e.UPC_A,_e.UPC_E,_e.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];Ey(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(Fn(r))return!0;if(!Fn(r.useBarCodeDetectorIfSupported))return r.useBarCodeDetectorIfSupported!==!1;if(Fn(r.experimentalFeatures))return!0;var o=r.experimentalFeatures;return Fn(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<ln.MIN_QR_BOX_SIZE)throw"minimum size of 'config.qrbox' dimension value is"+" ".concat(ln.MIN_QR_BOX_SIZE,"px.")},C=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=C(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=Fn(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},C=m?this.getShadedRegionBounds(r,o,f):g,x=this.createCanvasElement(C.width,C.height),A={willReadFrequently:!0},v=x.getContext("2d",A);v.canvas.width=C.width,v.canvas.height=C.height,this.element.append(x),m&&this.possiblyInsertShadingElement(this.element,r,o,f),this.createScannerPausedUiElement(this.element),this.qrRegion=C,this.context=v,this.canvasElement=x},t.prototype.createScannerPausedUiElement=function(r){var o=document.createElement("div");o.innerText=Nr.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,el.createFromQrcodeResult(u)),c.possiblyUpdateShaders(!0),!0}).catch(function(u){c.possiblyUpdateShaders(!1);var f=Nr.codeParseError(u);return o(f,Iy.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 C=this.qrRegion.width*m,x=this.qrRegion.height*g,A=this.qrRegion.x*m,v=this.qrRegion.y*g;this.context.drawImage(f,A,v,C,x,0,0,this.qrRegion.width,this.qrRegion.height);var P=function(){u.foreverScanTimeout=setTimeout(function(){u.foreverScan(r,o,c)},u.getTimeoutFps(r.fps))};this.scanContext(o,c).then(function(O){!O&&r.disableFlip!==!0?(u.context.translate(u.context.canvas.width,0),u.context.scale(-1,1),u.scanContext(o,c).finally(function(){P()})):P()}).catch(function(O){u.logger.logError("Error happend while scanning context",O),P()})}},t.prototype.createVideoConstraints=function(r){if(typeof r=="string")return{deviceId:{exact:r}};if(typeof r=="object"){var o="facingMode",c="deviceId",u={user:!0,environment:!0},f="exact",m=function(M){if(M in u)return!0;throw"config has invalid 'facingMode' value = "+"'".concat(M,"'")},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 C=Object.keys(r)[0];if(C!==o&&C!==c)throw"Only '".concat(o,"' and '").concat(c,"' ")+" are supported for 'cameraIdOrConfig'";if(C===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 A=typeof x;throw"Invalid type of 'facingMode' = ".concat(A)}}else{var v=r.deviceId;if(typeof v=="string")return{deviceId:v};if(typeof v=="object"){if(f in v)return{deviceId:{exact:v["".concat(f)]}};throw"'deviceId' should be string or object with"+" ".concat(f," as key.")}else{var P=typeof v;throw"Invalid type of 'deviceId' = ".concat(P)}}}var O=typeof r;throw"Invalid type of 'cameraIdOrConfig' = ".concat(O)},t.prototype.computeCanvasDrawConfig=function(r,o,c,u){if(r<=c&&o<=u){var f=(c-r)/2,m=(u-o)/2;return{x:f,y:m,width:r,height:o}}else{var g=r,C=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(C)+" 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?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,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=Fn(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(ln.SHADED_REGION_ELEMENT_ID),o-u.width<11||c-u.height<11)this.hasBorderShaders=!1;else{var C=5,x=40;this.insertShaderBorders(f,x,C,-C,null,0,!0),this.insertShaderBorders(f,x,C,-C,null,0,!1),this.insertShaderBorders(f,x,C,null,-C,0,!0),this.insertShaderBorders(f,x,C,null,-C,0,!1),this.insertShaderBorders(f,C,x+C,-C,null,-C,!0),this.insertShaderBorders(f,C,x+C,null,-C,-C,!0),this.insertShaderBorders(f,C,x+C,-C,null,-C,!1),this.insertShaderBorders(f,C,x+C,null,-C,-C,!1),this.hasBorderShaders=!0}r.append(f)}},t.prototype.insertShaderBorders=function(r,o,c,u,f,m,g){var C=document.createElement("div");C.style.position="absolute",C.style.backgroundColor=ln.BORDER_SHADER_DEFAULT_COLOR,C.style.width="".concat(o,"px"),C.style.height="".concat(c,"px"),u!==null&&(C.style.top="".concat(u,"px")),f!==null&&(C.style.bottom="".concat(f,"px")),g?C.style.left="".concat(m,"px"):C.style.right="".concat(m,"px"),this.borderShaders||(this.borderShaders=[]),this.borderShaders.push(C),r.appendChild(C)},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})(),cl;(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"})(cl||(cl={}));const Ky={class:"scan-code"},Jy={class:"btn"},Qy={class:"left-back"},ew=_.defineComponent({name:"QrCodeScan",__name:"QrCodeScan",emits:["scanSuccess"],setup(t,{emit:r}){const o=r,c=pd.IconScan(),u=_.reactive({html5QrCode:null}),f=_.ref(!1),m=()=>{if(!u.html5QrCode){Je("摄像头无访问权限!");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},v=>{try{const O=new URL(v).searchParams.get("sessionId");O?o("scanSuccess",O):Je("无效的二维码")}catch{Je("无效的二维码")}A()}).catch(v=>{console.log(v),Je({message:"二维码识别失败",duration:3e3})})},g=()=>{x().then(()=>{m()})},C=()=>{A()},x=()=>ll.getCameras().then(v=>{v&&v.length&&(u.html5QrCode=new ll("reader"))}).catch(()=>{Je({message:"摄像头无访问权限!",duration:3e3})}),A=()=>{u.html5QrCode&&u.html5QrCode.stop().then(v=>{console.log("停止扫码",v)}).catch(v=>{console.log(v),Je("停止扫码失败")}).finally(()=>{f.value=!1})};return _.onUnmounted(()=>{u.html5QrCode&&u.html5QrCode.isScanning&&A()}),(v,P)=>{const O=Qo;return _.openBlock(),_.createElementBlock("div",null,[_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(c),size:"28",svgSize:"20",onClick:P[0]||(P[0]=M=>g())},null,8,["icon"]),(_.openBlock(),_.createBlock(_.Teleport,{to:"body"},[_.withDirectives(_.createElementVNode("div",Ky,[P[1]||(P[1]=_.createElementVNode("div",{class:"container"},[_.createElementVNode("div",{class:"qrcode"},[_.createElementVNode("div",{id:"reader"})])],-1)),_.createElementVNode("div",Jy,[_.createElementVNode("div",Qy,[_.createVNode(O,{name:"arrow-left",onClick:C})])])],512),[[_.vShow,f.value]])]))])}}}),tw=nr(ew,[["__scopeId","data-v-2d988579"]]);function ts(t,r,o){const c=_.computed(()=>t?Array.isArray(t)?t:t.value:[]),u=()=>{const A=c.value;if(A.length===0)return"";if(r){const P=typeof r=="string"?r:r.value;if(P&&A.some(O=>O.id===P))return P}const v=A.find(P=>P.isDefault);return v?v.id:A[0].id};let f,m=!1;if(r&&typeof r!="string")f=r,m=!0,(!f.value||!c.value.some(A=>A.id===f.value))&&(f.value=u());else{let A;r&&typeof r=="string"&&(A=r),f=_.ref(A&&c.value.some(v=>v.id===A)?A:u())}(!m||o)&&_.watch(f,A=>{o&&o(A)});const g=_.computed(()=>c.value.find(A=>A.id===f.value)),C=_.computed(()=>c.value);return{selectedModelId:f,selectedModel:g,availableModels:C,setSelectedModel:A=>{c.value.find(P=>P.id===A)?f.value=A:console.warn(`[useModel] Model not found: ${A}`)}}}const nw=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const rw=Object.prototype.toString,iw=t=>rw.call(t)==="[object Object]",Ai=()=>{};function mo(t){return Array.isArray(t)?t:[t]}function ow(t,r,o){return _.watch(t,r,{...o,immediate:!0})}const Pu=nw?window:void 0;function jr(t){var r;const o=_.toValue(t);return(r=o?.$el)!==null&&r!==void 0?r:o}function go(...t){const r=(c,u,f,m)=>(c.addEventListener(u,f,m),()=>c.removeEventListener(u,f,m)),o=_.computed(()=>{const c=mo(_.toValue(t[0])).filter(u=>u!=null);return c.every(u=>typeof u!="string")?c:void 0});return ow(()=>{var c,u;return[(c=(u=o.value)===null||u===void 0?void 0:u.map(f=>jr(f)))!==null&&c!==void 0?c:[Pu].filter(f=>f!=null),mo(_.toValue(o.value?t[1]:t[0])),mo(_.unref(o.value?t[2]:t[1])),_.toValue(o.value?t[3]:t[2])]},([c,u,f,m],g,C)=>{if(!c?.length||!u?.length||!f?.length)return;const x=iw(m)?{...m}:m,A=c.flatMap(v=>u.flatMap(P=>f.map(O=>r(v,P,O,x))));C(()=>{A.forEach(v=>v())})},{flush:"post"})}function sw(t,r,o={}){const{window:c=Pu,ignore:u=[],capture:f=!0,detectIframe:m=!1,controls:g=!1}=o;if(!c)return g?{stop:Ai,cancel:Ai,trigger:Ai}:Ai;let C=!0;const x=B=>_.toValue(u).some(G=>{if(typeof G=="string")return Array.from(c.document.querySelectorAll(G)).some(Z=>Z===B.target||B.composedPath().includes(Z));{const Z=jr(G);return Z&&(B.target===Z||B.composedPath().includes(Z))}});function A(B){const G=_.toValue(B);return G&&G.$.subTree.shapeFlag===16}function v(B,G){const Z=_.toValue(B),U=Z.$.subTree&&Z.$.subTree.children;return U==null||!Array.isArray(U)?!1:U.some(Q=>Q.el===G.target||G.composedPath().includes(Q.el))}const P=B=>{const G=jr(t);if(B.target!=null&&!(!(G instanceof Element)&&A(t)&&v(t,B))&&!(!G||G===B.target||B.composedPath().includes(G))){if("detail"in B&&B.detail===0&&(C=!x(B)),!C){C=!0;return}r(B)}};let O=!1;const M=[go(c,"click",B=>{O||(O=!0,setTimeout(()=>{O=!1},0),P(B))},{passive:!0,capture:f}),go(c,"pointerdown",B=>{const G=jr(t);C=!x(B)&&!!(G&&!B.composedPath().includes(G))},{passive:!0}),m&&go(c,"blur",B=>{setTimeout(()=>{var G;const Z=jr(t);((G=c.document.activeElement)===null||G===void 0?void 0:G.tagName)==="IFRAME"&&!Z?.contains(c.document.activeElement)&&r(B)},0)},{passive:!0})].filter(Boolean),D=()=>M.forEach(B=>B());return g?{stop:D,cancel:()=>{C=!1},trigger:B=>{C=!0,P(B),C=!1}}:D}const aw=["data-active","disabled"],lw=_.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,aw))}}),ns=nr(lw,[["__scopeId","data-v-6f582cce"]]),cw={viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",fill:"none"};function uw(t,r){return _.openBlock(),_.createElementBlock("svg",cw,[...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 dw={render:uw},fw={class:"button-text"},hw={class:"dropdown-menu__items"},pw=["onClick"],mw=_.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 O=r.modelConfigs;return O?Array.isArray(O)?O:O.value:[]}),{selectedModel:u,availableModels:f,setSelectedModel:m}=ts(c,o),g=_.ref(!1),C=O=>{m(O),A()},x=()=>{g.value=!g.value},A=()=>{g.value=!1},v=_.ref(null),P=_.ref(null);return sw(P,()=>{A()},{ignore:[v]}),(O,M)=>(_.openBlock(),_.createElementBlock("div",{class:"model-switch-wrapper",ref_key:"wrapperRef",ref:v},[_.createVNode(ns,{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",fw,_.toDisplayString(_.unref(u)?.label),1),_.createVNode(_.unref(dw),{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:P},[_.createElementVNode("div",hw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(_.unref(f),D=>(_.openBlock(),_.createElementBlock("div",{key:D.id,class:_.normalizeClass(["dropdown-menu__item",{"active-menu":D.id===o.value}]),onClick:_.withModifiers(B=>C(D.id),["stop"])},[D.icon?(_.openBlock(),_.createBlock(_.resolveDynamicComponent(D.icon),{key:0,width:16,height:16,class:"dropdown-menu__icon"})):_.createCommentVNode("",!0),_.createElementVNode("span",null,_.toDisplayString(D.label),1)],10,pw))),128))])],512)):_.createCommentVNode("",!0)]),_:1}),g.value?(_.openBlock(),_.createElementBlock("div",{key:0,class:"dropdown-overlay",onClick:A})):_.createCommentVNode("",!0)],512))}}),gw=nr(mw,[["__scopeId","data-v-475491fd"]]),xw={key:0,class:"active-count"},yw=_.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(ns,{size:"small",class:"action-button",active:o.value>0,rounded:"",onClick:u[0]||(u[0]=f=>c.$emit("click"))},{default:_.withCtx(()=>[_.createVNode(_.unref(Or.IconPlugin),{class:"icon",style:{"font-size":"16px"}}),u[1]||(u[1]=_.createElementVNode("span",{class:"button-text"},"扩展",-1)),o.value>0?(_.openBlock(),_.createElementBlock("span",xw,_.toDisplayString(o.value),1)):_.createCommentVNode("",!0)]),_:1},8,["active"]))}}),ww=nr(yw,[["__scopeId","data-v-c2a16c66"]]),_w={"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 vw(t,r){return _.openBlock(),_.createElementBlock("svg",_w,[...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 Cw={render:vw},bw=_.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(ns,{class:"action-button",active:r.value,rounded:"",size:"small",onClick:o},{default:_.withCtx(()=>[_.createVNode(_.unref(Cw),{width:16,height:16}),u[0]||(u[0]=_.createElementVNode("span",{class:"button-text"},"生成式UI",-1))]),_:1},8,["active"]))}}),Ew=nr(bw,[["__scopeId","data-v-7f3b0372"]]),Aw={class:"bubble-image-wrapper"},Iw=["src"],Sw=["src"],Tw=_.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",Aw,[_.createElementVNode("img",{src:t.content,class:"bubble-image",alt:"用户上传的图片",onClick:c},null,8,Iw),(_.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,Sw)])],32)):_.createCommentVNode("",!0)]))]))}}),Nw=nr(Tw,[["__scopeId","data-v-91c75579"]]),$r="https://agent.opentiny.design",Ow=[{id:"12306-mcp",name:"12306服务器",description:"12306购票搜索服务器",icon:"https://agent.opentiny.design/public-assets/icons/icon-12306.webp",enabled:!1,addState:"idle",tools:[],url:$r+"/api/v1/mcp-server/12306/mcp",type:"StreamableHTTP"},{id:"markdown2pdf-mcp",name:"Markdown转PDF MCP服务器",description:"Markdown转PDF MCP服务器,可以将Markdown文件转换为PDF文件",icon:"https://agent.opentiny.design/public-assets/icons/icon-pdf.png",url:$r+"/servers/markdown2pdf-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"docx-mcp",name:"Word文档MCP服务器",description:"Word文档MCP服务器,可以创建、编辑、保存Word文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-word.png",url:$r+"/servers/excel-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]},{id:"excel-mcp",name:"Excel文档MCP服务器",description:"Excel文档MCP服务器,可以创建、编辑、保存Excel文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-excel.png",url:$r+"/servers/excel-mcp/mcp",type:"StreamableHTTP",enabled:!1,addState:"idle",tools:[]},{id:"doc-tools-mcp",name:"文档工具MCP服务器",description:"文档工具MCP服务器,可以创建、编辑、保存文档",icon:"https://agent.opentiny.design/public-assets/icons/icon-doc.png",url:$r+"/servers/doc-tools-mcp/sse",type:"sse",enabled:!1,addState:"idle",tools:[]}],kw=`
|
|
76
77
|
<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">
|
|
77
78
|
<defs>
|
|
78
79
|
<clipPath id="clip657_188316">
|
|
@@ -85,4 +86,4 @@ ${this.tempPrompt}
|
|
|
85
86
|
<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>
|
|
86
87
|
</g>
|
|
87
88
|
</svg>
|
|
88
|
-
`,Ny=btoa(Ty),sl=`data:image/svg+xml;base64,${Ny}`,mo=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},Oy=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(mo)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(mo)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(mo)}],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:y.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:y.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:y.h("span",{style:{fontSize:"18px"}},"📊")}];return{lang:r,pillItems:o,promptItems:c}},al={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},ky=t=>{console.log("message",t);const r=Object.keys(al),o=r.findIndex(u=>t.includes(u));return(o!==-1?al[r[o]]:t)||t},Ry={class:"tr-container__title"},My={style:{flex:"1"}},Dy={class:"chat-input"},Py={class:"chat-input-pills"},By={class:"attachments-container"},Ly={class:"action-buttons"},Fy=y.defineComponent({name:"TinyRemoter",__name:"TinyRobotChat",props:y.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:y.h(Ir.IconUser,{style:{fontSize:"32px"}}),assistant:y.h(Iu,{style:{fontSize:"32px"}})})},mode:{type:String,default:"remoter"},llmConfig:{type:Object,default:()=>({baseURL:"https://agent.opentiny.design/api/v1/ai/",genuiUrl:"https://agent.opentiny.design/api/v1/ai/prompt"})},inBrowserExt:{type:Boolean,default:!1},genUiComponents:{type:Object,default:()=>({})},customMarketMcpServers:{type:Array,default:()=>[]},mcpServers:{type:Object,default:void 0},llmConfigs:{type:Array,default:void 0},skills:{type:Object,default:void 0},layoutMode:{type:String,default:"fixed"},debugStream:{type:Boolean,default:!1},pageToolsOnDemand:{type:Boolean,default:!1},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:y.mergeModels(["before-ai-render"],["update:fullscreen","update:show","update:selectedModelId","update:genUiAble","update:enabledTools"]),setup(t,{expose:r,emit:o}){const c=t,u=o,f=y.useModel(t,"fullscreen"),g=y.useModel(t,"show"),m=y.useModel(t,"selectedModelId"),v=y.useModel(t,"genUiAble"),x=y.useModel(t,"enabledTools"),E=c.llmConfigs?y.toRef(c,"llmConfigs"):void 0,{selectedModel:A}=Ko(E,m),B=y.computed(()=>{const _e=E?.value?.length?A.value:c.llmConfig;return _e?!!(_e.baseURL&&_e.genuiUrl):!1}),{hasMultimodalSupport:O,attachments:R,onFilesSelected:D,checkCanSendAttachments:P,processAttachments:Y,cleanupAttachments:$}=_w({selectedModel:A,selectedModelId:m}),{agent:U,customAgentProvider:W,conversationState:X,messages:H,messageState:z,inputMessage:V,abortRequest:M,senderRef:Ce,sendMessage:me,handleSendMessage:le,addMessage:ie,send:re,createConversation:Z,switchConversation:de,deleteConversation:ee,getCurrentConversation:he}=F2({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:u});y.watch(()=>c.systemPrompt,_e=>{W.promptManager.setStatic(_e)}),W.isGenuiEnabled=v,W.debugStream=c.debugStream,y.watch(()=>c.pageToolsOnDemand,_e=>{W.pageToolsOnDemand=_e},{immediate:!0});const Ie=y.toRef(c,"skills"),{processSkillMentions:Te}=sw({skillsRef:Ie,customAgentProvider:W}),ge=async(_e,be)=>le(_e,be,Te),{welcomeIcon:De,roles:At}=fw({props:c,messages:H,messageState:z,inputMessage:V,handleSendMessage:ge}),{showHistory:Ye,handleCreateConversation:It,handleHistorySelect:te,handleHistoryUpdateTitle:Ve,handleHistoryDelete:Ne}=hw({createConversation:Z,switchConversation:de,deleteConversation:ee,getCurrentConversation:he,abortRequest:M,conversationState:X,customAgentProvider:W}),Fe=()=>{if(A.value){const _e=A.value;W.updateLLMConfig({model:_e.model||"",baseURL:_e.baseURL||"",genuiUrl:_e.genuiUrl||"",apiKey:_e.apiKey||"",providerType:_e.providerType,useReActMode:_e.useReActMode,llm:_e.llm,providerOptions:_e.providerOptions,headers:_e.headers})}else W.updateLLMConfig(W.llmConfig)};c.llmConfigs&&y.watch(A,Fe,{immediate:!0}),y.watch(v,Fe,{immediate:!0});const mn={markdown:new Pt.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":_e=>y.h(ad.GenuiRenderer,{..._e,customActions:{continueChat:{execute:(be,Ge)=>{const Jn=typeof be=="string"?be:be.message,We=`${Jn},相关参数为:${JSON.stringify(Ge?.state||{})}`;ie({role:"user",content:We,uiContent:[{type:"markdown",content:Jn}]}),re()}}},generating:Gn.GeneratingStatus.includes(z.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:Iy};function St(_e,be){mn[_e]=be}const{installedPlugins:nn,marketPlugins:Ue,pluginVisible:Ht,loadMcpServerToPlugin:Vt,togglePlugin:An,toggleTool:xt,deletePlugin:je,addPluginCore:ze,addPluginFromMarket:In,addPluginFromScan:S,handleClientDisconnected:ue,searchPlugin:dt}=ow(U,x,sl);pd({enabled:y.toRef(c,"pageToolsOnDemand"),installedPlugins:nn,customAgentProvider:W}),Ue.value=[...Sy,...c.customMarketMcpServers];const pt=y.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Sn=Oy(c),rn=y.computed(()=>c.pillItems??Sn.pillItems),ri=y.computed(()=>c.promptItems??Sn.promptItems),on=Sn.lang,{handleScanSuccess:Lt,handleSessionIdInput:ii,initialize:hr}=pw({sessionId:y.toRef(c,"sessionId"),agentRoot:c.agentRoot,mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:y.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:g,addPluginFromScan:S,inputMessage:V}),Fi=async _e=>{if(await ii(V.value)||!P())return;const Ge=await Y();try{await ge(_e,Ge),$()}catch(Jn){console.error("发送消息失败:",Jn)}},wt=y.computed(()=>Gn.GeneratingStatus.includes(z.status)?on[c.locale].thinking:on[c.locale].placeholder),pe=y.computed(()=>Gn.GeneratingStatus.includes(z.status)),bt=_e=>{V.value=_e.inputMessage};hr(),y.onMounted(async()=>{It(),U.onError=be=>{be&&qe(ky(be))};const _e=Ue.value.filter(be=>be.addState==="added"&&be.enabled);for(const be of _e)await In(be);if(c.mcpServers)for(const[be,Ge]of Object.entries(c.mcpServers))await Vt(be,Ge)});const{handleCustomAdd:et}=iw(U,nn,sl);return r({agent:U,welcomeIcon:De,messages:H,messageState:z,roles:At,inputMessage:V,senderRef:Ce,abortRequest:M,sendMessage:me,loadMcpServerToPlugin:Vt,handleClientDisconnected:ue,addMessage:ie,installedPlugins:nn,addPluginCore:ze,deletePlugin:je,registerContentRenderer:St}),(_e,be)=>(y.openBlock(),y.createBlock(y.unref(Pt.TrContainer),{show:g.value,"onUpdate:show":be[11]||(be[11]=Ge=>g.value=Ge),fullscreen:f.value,"onUpdate:fullscreen":be[12]||(be[12]=Ge=>f.value=Ge),style:y.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:y.withCtx(()=>[y.createElementVNode("h3",Ry,y.toDisplayString(t.title),1)]),operations:y.withCtx(()=>[y.renderSlot(_e.$slots,"operations",{},()=>[y.createVNode(y.unref(Pt.TrIconButton),{icon:y.unref(Ir.IconNewSession),size:"28",svgSize:"20",onClick:be[0]||(be[0]=Ge=>y.unref(It)())},null,8,["icon"]),y.createVNode(y.unref(Pt.TrIconButton),{icon:y.unref(Ir.IconHistory),size:"28",svgSize:"20",onClick:be[1]||(be[1]=Ge=>Ye.value=!y.unref(Ye))},null,8,["icon"]),y.createVNode(Jw,{onScanSuccess:y.unref(Lt)},null,8,["onScanSuccess"]),y.createVNode(y.Transition,{name:"drawer-slide",appear:""},{default:y.withCtx(()=>[y.unref(Ye)?(y.openBlock(),y.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:be[4]||(be[4]=Ge=>Ye.value=!1)},[y.createElementVNode("div",{class:"drawer-container",onClick:be[3]||(be[3]=y.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[be[13]||(be[13]=y.createElementVNode("h4",null,"历史会话",-1)),y.createVNode(y.unref(Pt.TrHistory),{class:"tr-history-demo",selected:y.unref(X).currentId,data:y.unref(X).conversations,showRenameControls:!0,onClose:be[2]||(be[2]=Ge=>Ye.value=!1),onItemClick:y.unref(te),onItemTitleChange:y.unref(Ve),onItemAction:y.unref(Ne)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):y.createCommentVNode("",!0)]),_:1})],!0)]),footer:y.withCtx(()=>[y.createElementVNode("div",Dy,[y.renderSlot(_e.$slots,"suggestions",{},()=>[y.createElementVNode("div",Py,[(y.openBlock(!0),y.createElementBlock(y.Fragment,null,y.renderList(rn.value,Ge=>(y.openBlock(),y.createBlock(y.unref(Pt.TrDropdownMenu),{key:Ge.id,items:Ge.menus,onItemClick:bt,trigger:"click"},{trigger:y.withCtx(()=>[y.createVNode(y.unref(Pt.TrSuggestionPillButton),null,{default:y.withCtx(()=>[y.createTextVNode(y.toDisplayString(Ge.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),y.createVNode(y.unref(Pt.TrSender),{ref_key:"senderRef",ref:Ce,mode:"multiple",modelValue:y.unref(V),"onUpdate:modelValue":be[9]||(be[9]=Ge=>y.isRef(V)?V.value=Ge:null),placeholder:wt.value,clearable:!!y.unref(V),loading:pe.value,showWordLimit:!0,maxLength:2e4,onSubmit:Fi,onCancel:y.unref(M)},y.createSlots({footer:y.withCtx(()=>[y.createElementVNode("div",Ly,[y.createVNode(my,{"installed-plugins":y.unref(nn),onClick:be[6]||(be[6]=Ge=>Ht.value=!y.unref(Ht))},null,8,["installed-plugins"]),y.unref(E)&&y.unref(E).length>0?(y.openBlock(),y.createBlock(hy,{key:0,"model-configs":y.unref(E),"selected-model-id":m.value,"onUpdate:selectedModelId":be[7]||(be[7]=Ge=>m.value=Ge)},null,8,["model-configs","selected-model-id"])):y.createCommentVNode("",!0),B.value?(y.openBlock(),y.createBlock(vy,{key:1,"genui-enabled":v.value,"onUpdate:genuiEnabled":be[8]||(be[8]=Ge=>v.value=Ge)},null,8,["genui-enabled"])):y.createCommentVNode("",!0),y.unref(O)?(y.openBlock(),y.createBlock(y.unref(Pt.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:y.unref(D)},null,8,["onSelect"])):y.createCommentVNode("",!0)])]),_:2},[y.unref(R).length>0?{name:"header",fn:y.withCtx(()=>[y.createElementVNode("div",By,[y.createVNode(y.unref(Pt.TrAttachments),{items:y.unref(R),"onUpdate:items":be[5]||(be[5]=Ge=>y.isRef(R)?R.value=Ge:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),y.createVNode(y.unref(Pt.TrMcpServerPicker),{visible:y.unref(Ht),"onUpdate:visible":be[10]||(be[10]=Ge=>y.isRef(Ht)?Ht.value=Ge:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:y.unref(nn),marketPlugins:y.unref(Ue),"market-category-options":pt.value,"installed-search-fn":y.unref(dt),"market-search-fn":y.unref(dt),onPluginToggle:y.unref(An),onPluginAdd:y.unref(In),onPluginDelete:y.unref(je),onToolToggle:y.unref(xt),onPluginCreate:y.unref(et)},{"header-actions":y.withCtx(()=>[y.renderSlot(_e.$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:y.withCtx(()=>[y.createVNode(y.unref(Pt.TrBubbleProvider),{"content-renderers":mn},{default:y.withCtx(()=>[y.unref(H).length===0?y.renderSlot(_e.$slots,"welcome",{key:0},()=>[y.createElementVNode("div",My,[y.createVNode(y.unref(Pt.TrWelcome),{title:y.unref(on)[t.locale].title,description:y.unref(on)[t.locale].description,icon:y.unref(De)},null,8,["title","description","icon"]),y.createVNode(y.unref(Pt.TrPrompts),{items:ri.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(y.openBlock(),y.createBlock(y.unref(Pt.TrBubbleList),{key:1,style:{flex:"1"},items:y.unref(H),roles:y.unref(At),"auto-scroll":"",loading:y.unref(z).status===y.unref(Gn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Ro=Kn(Fy,[["__scopeId","data-v-73fa7980"]]);function Uy(t){const r=t.sessionId?ll(t.sessionId,t.agentRoot):[],o=new en.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=y.ref("ready"),u=y.ref([]),f=y.ref("");let g=null;async function m(){const A=f.value;if(!A)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(A)){E(A.slice(1));return}c.value="submitted",g=new AbortController;const B=await o.chatStream({message:A,model:t.model,system:t.systemPrompt||"",abortSignal:g.signal,maxSteps:t.maxSteps||5,onFinish:async()=>{await o.closeAll(),c.value="ready"},onError:()=>c.value="error",onAbort:()=>c.value="ready"});if(f.value="",t.processStream&&typeof t.processStream=="function"){t.processStream(B.fullStream,u,A);return}t.ui==="matechat"?zy(B.fullStream,u,A):t.ui==="antx"?Vy(B.fullStream,u,A):t.ui==="elplusx"?Zy(B.fullStream,u,A):t.ui==="tdchat"?$y(B.fullStream,u,A):console.warn("暂时未实现")}function v(){g&&g.abort()}function x(){u.value=[],o.responseMessages=[]}async function E(A){const O=(await fetch(`${t.agentRoot}client?sessionId=${A}`).then(R=>R.json()))?.data?.sessionId||"";if(O){const R=ll(O,t.agentRoot);Object.assign(o.mcpServers,R)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:m,stopChat:v,newConversation:x,addSessionId:E}}function ll(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 zy(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 Vy(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 Zy(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 $y(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)}Ro.install=function(t){t.component("tiny-remoter",Ro)};exports.TinyRemoter=Ro;exports.useModel=Ko;exports.useNextAgent=Uy;
|
|
89
|
+
`,Rw=btoa(kw),ul=`data:image/svg+xml;base64,${Rw}`,xo=(t,r)=>{const[o,c]=t.split("#");return{id:r,text:o,inputMessage:c}},Mw=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(xo)},{id:"development",text:t.locale==="zh-CN"?"开发支持":"Development Support",menus:["遇到代码问题#请检查当前位置的报错原因。","架构建议#请使用NodeJs实现一个分块上传文件的模块。","最新的技术趋势#请分析Vue与React 框架的优劣分别是什么?"].map(xo)},{id:"management",text:t.locale==="zh-CN"?"项目管理":"Project Management",menus:["项目规划#如何开展品牌推广的活动?","任务分配#将本季度的销售任务分配给三个人,并生成甘特图进行跟踪。","进度跟踪#分析团队的任务完成情况。"].map(xo)}],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}},dl={"No client found for session ID":"受控端页面已关闭请重新打开或者刷新页面","Failed to create MCP client":"创建MCP客户端失败"},Dw=t=>{console.log("message",t);const r=Object.keys(dl),o=r.findIndex(u=>t.includes(u));return(o!==-1?dl[r[o]]:t)||t},Pw={class:"tr-container__title"},Bw={style:{flex:"1"}},Lw={class:"chat-input"},Fw={class:"chat-input-pills"},Uw={class:"attachments-container"},zw={class:"action-buttons"},Vw=_.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(Or.IconUser,{style:{fontSize:"32px"}}),assistant:_.h(ku,{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"],["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"),C=_.useModel(t,"genUiAble"),x=_.useModel(t,"enabledTools"),A=c.llmConfigs?_.toRef(c,"llmConfigs"):void 0,{selectedModel:v}=ts(A,g),P=_.computed(()=>{const $e=A?.value?.length?v.value:c.llmConfig;return $e?!!($e.baseURL&&$e.genuiUrl):!1}),{hasMultimodalSupport:O,attachments:M,onFilesSelected:D,checkCanSendAttachments:B,processAttachments:G,cleanupAttachments:Z}=by({selectedModel:v,selectedModelId:g}),{agent:U,customAgentProvider:Q,conversationState:K,messages:V,messageState:z,inputMessage:te,abortRequest:S,senderRef:Te,sendMessage:ye,handleSendMessage:re,addMessage:xe,send:Me,createConversation:$,switchConversation:ge,deleteConversation:ne,getCurrentConversation:J}=z2({systemPrompt:c.systemPrompt||"",llmConfig:c.llmConfig,emit:u});_.watch(()=>c.systemPrompt,$e=>{Q.promptManager.setStatic($e)}),Q.isGenuiEnabled=C,Q.debugStream=c.debugStream;const me=_.toRef(c,"skills"),{processSkillMentions:fe}=cy({skillsRef:me,customAgentProvider:Q}),ie=async($e,ke)=>re($e,ke,fe),{welcomeIcon:pe,roles:vt}=my({props:c,messages:V,messageState:z,inputMessage:te,handleSendMessage:ie}),{showHistory:Ee,handleCreateConversation:Tt,handleHistorySelect:Ce,handleHistoryUpdateTitle:sn,handleHistoryDelete:Ue}=gy({createConversation:$,switchConversation:ge,deleteConversation:ne,getCurrentConversation:J,abortRequest:S,conversationState:K,customAgentProvider:Q}),Ht=()=>{if(v.value){const $e=v.value;Q.updateLLMConfig({model:$e.model||"",baseURL:$e.baseURL||"",genuiUrl:$e.genuiUrl||"",apiKey:$e.apiKey||"",providerType:$e.providerType,useReActMode:$e.useReActMode,llm:$e.llm,providerOptions:$e.providerOptions,headers:$e.headers})}else Q.updateLLMConfig(Q.llmConfig)};c.llmConfigs&&_.watch(v,Ht,{immediate:!0}),_.watch(C,Ht,{immediate:!0});const de={markdown:new Ut.BubbleMarkdownContentRenderer({mdConfig:{html:!0}}),"schema-card":$e=>_.h(fd.GenuiRenderer,{...$e,customActions:{continueChat:{execute:(ke,Ye)=>{const He=typeof ke=="string"?ke:ke.message,Ln=`${He},相关参数为:${JSON.stringify(Ye?.state||{})}`;xe({role:"user",content:Ln,uiContent:[{type:"markdown",content:He}]}),Me()}}},generating:Kn.GeneratingStatus.includes(z.status),customComponents:c.genUiComponents,requiredCompleteFieldSelectors:["[componentName=TinyUser] > props > modelValue"]}),image:Nw};function Oe($e,ke){de[$e]=ke}const{installedPlugins:yt,marketPlugins:be,pluginVisible:Xt,loadMcpServerToPlugin:Wt,togglePlugin:In,toggleTool:Ct,deletePlugin:Xe,addPluginCore:Ze,addPluginFromMarket:Sn,addPluginFromScan:ve,handleClientDisconnected:Bn,searchPlugin:$n,syncInstalledPluginTools:Jt}=ay(U,x,ul);ly({onToolCatalogChanged:async()=>{await U.refreshTools(),Jt()}}),be.value=[...Ow,...c.customMarketMcpServers];const Hn=_.ref([{value:"",label:"全部分类"},{value:"productivity",label:"生产力工具"},{value:"communication",label:"沟通协作"},{value:"development",label:"开发工具"},{value:"ai",label:"AI 助手"}]),Bt=Mw(c),rr=_.computed(()=>c.pillItems??Bt.pillItems),R=_.computed(()=>c.promptItems??Bt.promptItems),oe=Bt.lang,{handleScanSuccess:qe,handleSessionIdInput:lt,initialize:xr}=xy({sessionId:_.toRef(c,"sessionId"),agentRoot:c.agentRoot,mode:c.mode,qrCodeUrl:c.qrCodeUrl,remoteUrl:c.remoteUrl,menuItems:_.toRef(c,"menuItems"),AILogoUrl:c.AILogoUrl,show:m,addPluginFromScan:ve,inputMessage:te}),bt=async $e=>{if(await lt(te.value)||!B())return;const Ye=await G();try{await ie($e,Ye),Z()}catch(He){console.error("发送消息失败:",He)}},he=_.computed(()=>Kn.GeneratingStatus.includes(z.status)?oe[c.locale].thinking:oe[c.locale].placeholder),Nt=_.computed(()=>Kn.GeneratingStatus.includes(z.status)),nt=$e=>{te.value=$e.inputMessage};xr(),_.onMounted(async()=>{setTimeout(()=>{Tt()},100),U.onError=ke=>{ke&&Je(Dw(ke))};const $e=be.value.filter(ke=>ke.addState==="added"&&ke.enabled);for(const ke of $e)await Sn(ke);if(c.mcpServers)for(const[ke,Ye]of Object.entries(c.mcpServers))await Wt(ke,Ye)});const{handleCustomAdd:mt}=sy(U,yt,ul);return r({agent:U,welcomeIcon:pe,messages:V,messageState:z,roles:vt,inputMessage:te,senderRef:Te,abortRequest:S,sendMessage:ye,loadMcpServerToPlugin:Wt,handleClientDisconnected:Bn,addMessage:xe,installedPlugins:yt,addPluginCore:Ze,deletePlugin:Xe,registerContentRenderer:Oe}),($e,ke)=>(_.openBlock(),_.createBlock(_.unref(Ut.TrContainer),{show:m.value,"onUpdate:show":ke[11]||(ke[11]=Ye=>m.value=Ye),fullscreen:f.value,"onUpdate:fullscreen":ke[12]||(ke[12]=Ye=>f.value=Ye),style:_.normalizeStyle({position:t.layoutMode,width:t.layoutMode!=="fixed"?"unset":void 0,height:t.layoutMode!=="fixed"?"100%":void 0})},{title:_.withCtx(()=>[_.createElementVNode("h3",Pw,_.toDisplayString(t.title),1)]),operations:_.withCtx(()=>[_.renderSlot($e.$slots,"operations",{},()=>[_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(Or.IconNewSession),size:"28",svgSize:"20",onClick:ke[0]||(ke[0]=Ye=>_.unref(Tt)())},null,8,["icon"]),_.createVNode(_.unref(Ut.TrIconButton),{icon:_.unref(Or.IconHistory),size:"28",svgSize:"20",onClick:ke[1]||(ke[1]=Ye=>Ee.value=!_.unref(Ee))},null,8,["icon"]),_.createVNode(tw,{onScanSuccess:_.unref(qe)},null,8,["onScanSuccess"]),_.createVNode(_.Transition,{name:"drawer-slide",appear:""},{default:_.withCtx(()=>[_.unref(Ee)?(_.openBlock(),_.createElementBlock("div",{key:0,class:"drawer-overlay",onClick:ke[4]||(ke[4]=Ye=>Ee.value=!1)},[_.createElementVNode("div",{class:"drawer-container",onClick:ke[3]||(ke[3]=_.withModifiers(()=>{},["stop"])),style:{"--tr-history-item-selected-bg":"#ebeeff"}},[ke[13]||(ke[13]=_.createElementVNode("h4",null,"历史会话",-1)),_.createVNode(_.unref(Ut.TrHistory),{class:"tr-history-demo",selected:_.unref(K).currentId,data:_.unref(K).conversations,showRenameControls:!0,onClose:ke[2]||(ke[2]=Ye=>Ee.value=!1),onItemClick:_.unref(Ce),onItemTitleChange:_.unref(sn),onItemAction:_.unref(Ue)},null,8,["selected","data","onItemClick","onItemTitleChange","onItemAction"])])])):_.createCommentVNode("",!0)]),_:1})],!0)]),footer:_.withCtx(()=>[_.createElementVNode("div",Lw,[_.renderSlot($e.$slots,"suggestions",{},()=>[_.createElementVNode("div",Fw,[(_.openBlock(!0),_.createElementBlock(_.Fragment,null,_.renderList(rr.value,Ye=>(_.openBlock(),_.createBlock(_.unref(Ut.TrDropdownMenu),{key:Ye.id,items:Ye.menus,onItemClick:nt,trigger:"click"},{trigger:_.withCtx(()=>[_.createVNode(_.unref(Ut.TrSuggestionPillButton),null,{default:_.withCtx(()=>[_.createTextVNode(_.toDisplayString(Ye.text),1)]),_:2},1024)]),_:2},1032,["items"]))),128))])],!0),_.createVNode(_.unref(Ut.TrSender),{ref_key:"senderRef",ref:Te,mode:"multiple",modelValue:_.unref(te),"onUpdate:modelValue":ke[9]||(ke[9]=Ye=>_.isRef(te)?te.value=Ye:null),placeholder:he.value,clearable:!!_.unref(te),loading:Nt.value,showWordLimit:!0,maxLength:2e4,onSubmit:bt,onCancel:_.unref(S)},_.createSlots({footer:_.withCtx(()=>[_.createElementVNode("div",zw,[_.createVNode(ww,{"installed-plugins":_.unref(yt),onClick:ke[6]||(ke[6]=Ye=>Xt.value=!_.unref(Xt))},null,8,["installed-plugins"]),_.unref(A)&&_.unref(A).length>0?(_.openBlock(),_.createBlock(gw,{key:0,"model-configs":_.unref(A),"selected-model-id":g.value,"onUpdate:selectedModelId":ke[7]||(ke[7]=Ye=>g.value=Ye)},null,8,["model-configs","selected-model-id"])):_.createCommentVNode("",!0),P.value?(_.openBlock(),_.createBlock(Ew,{key:1,"genui-enabled":C.value,"onUpdate:genuiEnabled":ke[8]||(ke[8]=Ye=>C.value=Ye)},null,8,["genui-enabled"])):_.createCommentVNode("",!0),_.unref(O)?(_.openBlock(),_.createBlock(_.unref(Ut.TrUploadButton),{key:2,accept:"image/*,application/pdf,.doc,.docx,.txt",multiple:!0,onSelect:_.unref(D)},null,8,["onSelect"])):_.createCommentVNode("",!0)])]),_:2},[_.unref(M).length>0?{name:"header",fn:_.withCtx(()=>[_.createElementVNode("div",Uw,[_.createVNode(_.unref(Ut.TrAttachments),{items:_.unref(M),"onUpdate:items":ke[5]||(ke[5]=Ye=>_.isRef(M)?M.value=Ye:null)},null,8,["items"])])]),key:"0"}:void 0]),1032,["modelValue","placeholder","clearable","loading","onCancel"]),_.createVNode(_.unref(Ut.TrMcpServerPicker),{visible:_.unref(Xt),"onUpdate:visible":ke[10]||(ke[10]=Ye=>_.isRef(Xt)?Xt.value=Ye:null),"popup-config":{type:"drawer"},"show-custom-add-button":!0,marketTabTitle:"MCP市场",installedTabTitle:"已添加MCP服务",title:"扩展",installedPlugins:_.unref(yt),marketPlugins:_.unref(be),"market-category-options":Hn.value,"installed-search-fn":_.unref($n),"market-search-fn":_.unref($n),onPluginToggle:_.unref(In),onPluginAdd:_.unref(Sn),onPluginDelete:_.unref(Xe),onToolToggle:_.unref(Ct),onPluginCreate:_.unref(mt)},{"header-actions":_.withCtx(()=>[_.renderSlot($e.$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(Ut.TrBubbleProvider),{"content-renderers":de},{default:_.withCtx(()=>[_.unref(V).length===0?_.renderSlot($e.$slots,"welcome",{key:0},()=>[_.createElementVNode("div",Bw,[_.createVNode(_.unref(Ut.TrWelcome),{title:_.unref(oe)[t.locale].title,description:_.unref(oe)[t.locale].description,icon:_.unref(pe)},null,8,["title","description","icon"]),_.createVNode(_.unref(Ut.TrPrompts),{items:R.value,wrap:!0,class:"tiny-prompts","item-class":"prompt-item"},null,8,["items"])])],!0):(_.openBlock(),_.createBlock(_.unref(Ut.TrBubbleList),{key:1,style:{flex:"1"},items:_.unref(V),roles:_.unref(vt),"auto-scroll":"",loading:_.unref(z).status===_.unref(Kn.STATUS).PROCESSING,"loading-role":"assistant"},null,8,["items","roles","loading"]))]),_:3})]),_:3},8,["show","fullscreen","style"]))}}),Po=nr(Vw,[["__scopeId","data-v-bda25851"]]);function Zw(t){const r=t.sessionId?fl(t.sessionId,t.agentRoot):[],o=new Jn.AgentModelProvider({llmConfig:t.llmConfig,mcpServers:r}),c=_.ref("ready"),u=_.ref([]),f=_.ref("");let m=null;async function g(){const v=f.value;if(!v)return;if(/^\/[A-Za-z0-9-]{6,}$/.test(v)){A(v.slice(1));return}c.value="submitted",m=new AbortController;const P=await o.chatStream({message:v,model:t.model,system:t.systemPrompt||"",abortSignal:m.signal,maxSteps:t.maxSteps||5,onFinish:async()=>{await o.closeAll(),c.value="ready"},onError:()=>c.value="error",onAbort:()=>c.value="ready"});if(f.value="",t.processStream&&typeof t.processStream=="function"){t.processStream(P.fullStream,u,v);return}t.ui==="matechat"?$w(P.fullStream,u,v):t.ui==="antx"?Hw(P.fullStream,u,v):t.ui==="elplusx"?Ww(P.fullStream,u,v):t.ui==="tdchat"?jw(P.fullStream,u,v):console.warn("暂时未实现")}function C(){m&&m.abort()}function x(){u.value=[],o.responseMessages=[]}async function A(v){const O=(await fetch(`${t.agentRoot}client?sessionId=${v}`).then(M=>M.json()))?.data?.sessionId||"";if(O){const M=fl(O,t.agentRoot);Object.assign(o.mcpServers,M)}}return{agent:o,status:c,messages:u,inputValue:f,chatStream:g,stopChat:C,newConversation:x,addSessionId:A}}function fl(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 $w(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 Hw(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 Ww(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 jw(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=ts;exports.useNextAgent=Zw;
|