
/* /web/static/lib/zxing-library/zxing-library.js */
(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,factory(global.ZXing={}));}(this,(function(exports){'use strict';function fixProto(target,prototype){var setPrototypeOf=Object.setPrototypeOf;setPrototypeOf?setPrototypeOf(target,prototype):target.__proto__=prototype;}
function fixStack(target,fn){if(fn===void 0){fn=target.constructor;}
var captureStackTrace=Error.captureStackTrace;captureStackTrace&&captureStackTrace(target,fn);}
var __extends=function(){var _extendStatics=function extendStatics(d,b){_extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b){if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p];}};return _extendStatics(d,b);};return function(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");_extendStatics(d,b);function __(){this.constructor=d;}
d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());};}();var CustomError=function(_super){__extends(CustomError,_super);function CustomError(message,options){var _newTarget=this.constructor;var _this=_super.call(this,message,options)||this;Object.defineProperty(_this,'name',{value:_newTarget.name,enumerable:false,configurable:true});fixProto(_this,_newTarget.prototype);fixStack(_this);return _this;}
return CustomError;}(Error);class Exception extends CustomError{constructor(message=undefined){super(message);this.message=message;}
getKind(){const ex=this.constructor;return ex.kind;}}
Exception.kind='Exception';class ArgumentException extends Exception{}
ArgumentException.kind='ArgumentException';class IllegalArgumentException extends Exception{}
IllegalArgumentException.kind='IllegalArgumentException';class BinaryBitmap{constructor(binarizer){this.binarizer=binarizer;if(binarizer===null){throw new IllegalArgumentException('Binarizer must be non-null.');}}
getWidth(){return this.binarizer.getWidth();}
getHeight(){return this.binarizer.getHeight();}
getBlackRow(y,row){return this.binarizer.getBlackRow(y,row);}
getBlackMatrix(){if(this.matrix===null||this.matrix===undefined){this.matrix=this.binarizer.getBlackMatrix();}
return this.matrix;}
isCropSupported(){return this.binarizer.getLuminanceSource().isCropSupported();}
crop(left,top,width,height){const newSource=this.binarizer.getLuminanceSource().crop(left,top,width,height);return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}
isRotateSupported(){return this.binarizer.getLuminanceSource().isRotateSupported();}
rotateCounterClockwise(){const newSource=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}
rotateCounterClockwise45(){const newSource=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new BinaryBitmap(this.binarizer.createBinarizer(newSource));}
toString(){try{return this.getBlackMatrix().toString();}
catch(e){return'';}}}
class ChecksumException extends Exception{static getChecksumInstance(){return new ChecksumException();}}
ChecksumException.kind='ChecksumException';class Binarizer{constructor(source){this.source=source;}
getLuminanceSource(){return this.source;}
getWidth(){return this.source.getWidth();}
getHeight(){return this.source.getHeight();}}
class System{static arraycopy(src,srcPos,dest,destPos,length){while(length--){dest[destPos++]=src[srcPos++];}}
static currentTimeMillis(){return Date.now();}}
class IndexOutOfBoundsException extends Exception{}
IndexOutOfBoundsException.kind='IndexOutOfBoundsException';class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException{constructor(index=undefined,message=undefined){super(message);this.index=index;this.message=message;}}
ArrayIndexOutOfBoundsException.kind='ArrayIndexOutOfBoundsException';class Arrays{static fill(a,val){for(let i=0,len=a.length;i<len;i++)
a[i]=val;}
static fillWithin(a,fromIndex,toIndex,val){Arrays.rangeCheck(a.length,fromIndex,toIndex);for(let i=fromIndex;i<toIndex;i++)
a[i]=val;}
static rangeCheck(arrayLength,fromIndex,toIndex){if(fromIndex>toIndex){throw new IllegalArgumentException('fromIndex('+fromIndex+') > toIndex('+toIndex+')');}
if(fromIndex<0){throw new ArrayIndexOutOfBoundsException(fromIndex);}
if(toIndex>arrayLength){throw new ArrayIndexOutOfBoundsException(toIndex);}}
static asList(...args){return args;}
static create(rows,cols,value){let arr=Array.from({length:rows});return arr.map(x=>Array.from({length:cols}).fill(value));}
static createInt32Array(rows,cols,value){let arr=Array.from({length:rows});return arr.map(x=>Int32Array.from({length:cols}).fill(value));}
static equals(first,second){if(!first){return false;}
if(!second){return false;}
if(!first.length){return false;}
if(!second.length){return false;}
if(first.length!==second.length){return false;}
for(let i=0,length=first.length;i<length;i++){if(first[i]!==second[i]){return false;}}
return true;}
static hashCode(a){if(a===null){return 0;}
let result=1;for(const element of a){result=31*result+element;}
return result;}
static fillUint8Array(a,value){for(let i=0;i!==a.length;i++){a[i]=value;}}
static copyOf(original,newLength){return original.slice(0,newLength);}
static copyOfUint8Array(original,newLength){if(original.length<=newLength){const newArray=new Uint8Array(newLength);newArray.set(original);return newArray;}
return original.slice(0,newLength);}
static copyOfRange(original,from,to){const newLength=to-from;const copy=new Int32Array(newLength);System.arraycopy(original,from,copy,0,newLength);return copy;}
static binarySearch(ar,el,comparator){if(undefined===comparator){comparator=Arrays.numberComparator;}
let m=0;let n=ar.length-1;while(m<=n){const k=(n+m)>>1;const cmp=comparator(el,ar[k]);if(cmp>0){m=k+1;}
else if(cmp<0){n=k-1;}
else{return k;}}
return-m-1;}
static numberComparator(a,b){return a-b;}}
class Integer{static numberOfTrailingZeros(i){let y;if(i===0)
return 32;let n=31;y=i<<16;if(y!==0){n-=16;i=y;}
y=i<<8;if(y!==0){n-=8;i=y;}
y=i<<4;if(y!==0){n-=4;i=y;}
y=i<<2;if(y!==0){n-=2;i=y;}
return n-((i<<1)>>>31);}
static numberOfLeadingZeros(i){if(i===0){return 32;}
let n=1;if(i>>>16===0){n+=16;i<<=16;}
if(i>>>24===0){n+=8;i<<=8;}
if(i>>>28===0){n+=4;i<<=4;}
if(i>>>30===0){n+=2;i<<=2;}
n-=i>>>31;return n;}
static toHexString(i){return i.toString(16);}
static toBinaryString(intNumber){return String(parseInt(String(intNumber),2));}
static bitCount(i){i=i-((i>>>1)&0x55555555);i=(i&0x33333333)+((i>>>2)&0x33333333);i=(i+(i>>>4))&0x0f0f0f0f;i=i+(i>>>8);i=i+(i>>>16);return i&0x3f;}
static truncDivision(dividend,divisor){return Math.trunc(dividend/divisor);}
static parseInt(num,radix=undefined){return parseInt(num,radix);}}
Integer.MIN_VALUE_32_BITS=-2147483648;Integer.MAX_VALUE=Number.MAX_SAFE_INTEGER;class BitArray{constructor(size,bits){if(undefined===size){this.size=0;this.bits=new Int32Array(1);}
else{this.size=size;if(undefined===bits||null===bits){this.bits=BitArray.makeArray(size);}
else{this.bits=bits;}}}
getSize(){return this.size;}
getSizeInBytes(){return Math.floor((this.size+7)/8);}
ensureCapacity(size){if(size>this.bits.length*32){const newBits=BitArray.makeArray(size);System.arraycopy(this.bits,0,newBits,0,this.bits.length);this.bits=newBits;}}
get(i){return(this.bits[Math.floor(i/32)]&(1<<(i&0x1F)))!==0;}
set(i){this.bits[Math.floor(i/32)]|=1<<(i&0x1F);}
flip(i){this.bits[Math.floor(i/32)]^=1<<(i&0x1F);}
getNextSet(from){const size=this.size;if(from>=size){return size;}
const bits=this.bits;let bitsOffset=Math.floor(from/32);let currentBits=bits[bitsOffset];currentBits&=~((1<<(from&0x1F))-1);const length=bits.length;while(currentBits===0){if(++bitsOffset===length){return size;}
currentBits=bits[bitsOffset];}
const result=(bitsOffset*32)+Integer.numberOfTrailingZeros(currentBits);return result>size?size:result;}
getNextUnset(from){const size=this.size;if(from>=size){return size;}
const bits=this.bits;let bitsOffset=Math.floor(from/32);let currentBits=~bits[bitsOffset];currentBits&=~((1<<(from&0x1F))-1);const length=bits.length;while(currentBits===0){if(++bitsOffset===length){return size;}
currentBits=~bits[bitsOffset];}
const result=(bitsOffset*32)+Integer.numberOfTrailingZeros(currentBits);return result>size?size:result;}
setBulk(i,newBits){this.bits[Math.floor(i/32)]=newBits;}
setRange(start,end){if(end<start||start<0||end>this.size){throw new IllegalArgumentException();}
if(end===start){return;}
end--;const firstInt=Math.floor(start/32);const lastInt=Math.floor(end/32);const bits=this.bits;for(let i=firstInt;i<=lastInt;i++){const firstBit=i>firstInt?0:start&0x1F;const lastBit=i<lastInt?31:end&0x1F;const mask=(2<<lastBit)-(1<<firstBit);bits[i]|=mask;}}
clear(){const max=this.bits.length;const bits=this.bits;for(let i=0;i<max;i++){bits[i]=0;}}
isRange(start,end,value){if(end<start||start<0||end>this.size){throw new IllegalArgumentException();}
if(end===start){return true;}
end--;const firstInt=Math.floor(start/32);const lastInt=Math.floor(end/32);const bits=this.bits;for(let i=firstInt;i<=lastInt;i++){const firstBit=i>firstInt?0:start&0x1F;const lastBit=i<lastInt?31:end&0x1F;const mask=(2<<lastBit)-(1<<firstBit)&0xFFFFFFFF;if((bits[i]&mask)!==(value?mask:0)){return false;}}
return true;}
appendBit(bit){this.ensureCapacity(this.size+1);if(bit){this.bits[Math.floor(this.size/32)]|=1<<(this.size&0x1F);}
this.size++;}
appendBits(value,numBits){if(numBits<0||numBits>32){throw new IllegalArgumentException('Num bits must be between 0 and 32');}
this.ensureCapacity(this.size+numBits);for(let numBitsLeft=numBits;numBitsLeft>0;numBitsLeft--){this.appendBit(((value>>(numBitsLeft-1))&0x01)===1);}}
appendBitArray(other){const otherSize=other.size;this.ensureCapacity(this.size+otherSize);for(let i=0;i<otherSize;i++){this.appendBit(other.get(i));}}
xor(other){if(this.size!==other.size){throw new IllegalArgumentException('Sizes don\'t match');}
const bits=this.bits;for(let i=0,length=bits.length;i<length;i++){bits[i]^=other.bits[i];}}
toBytes(bitOffset,array,offset,numBytes){for(let i=0;i<numBytes;i++){let theByte=0;for(let j=0;j<8;j++){if(this.get(bitOffset)){theByte|=1<<(7-j);}
bitOffset++;}
array[offset+i]=theByte;}}
getBitArray(){return this.bits;}
reverse(){const newBits=new Int32Array(this.bits.length);const len=Math.floor((this.size-1)/32);const oldBitsLen=len+1;const bits=this.bits;for(let i=0;i<oldBitsLen;i++){let x=bits[i];x=((x>>1)&0x55555555)|((x&0x55555555)<<1);x=((x>>2)&0x33333333)|((x&0x33333333)<<2);x=((x>>4)&0x0f0f0f0f)|((x&0x0f0f0f0f)<<4);x=((x>>8)&0x00ff00ff)|((x&0x00ff00ff)<<8);x=((x>>16)&0x0000ffff)|((x&0x0000ffff)<<16);newBits[len-i]=x;}
if(this.size!==oldBitsLen*32){const leftOffset=oldBitsLen*32-this.size;let currentInt=newBits[0]>>>leftOffset;for(let i=1;i<oldBitsLen;i++){const nextInt=newBits[i];currentInt|=nextInt<<(32-leftOffset);newBits[i-1]=currentInt;currentInt=nextInt>>>leftOffset;}
newBits[oldBitsLen-1]=currentInt;}
this.bits=newBits;}
static makeArray(size){return new Int32Array(Math.floor((size+31)/32));}
equals(o){if(!(o instanceof BitArray)){return false;}
const other=o;return this.size===other.size&&Arrays.equals(this.bits,other.bits);}
hashCode(){return 31*this.size+Arrays.hashCode(this.bits);}
toString(){let result='';for(let i=0,size=this.size;i<size;i++){if((i&0x07)===0){result+=' ';}
result+=this.get(i)?'X':'.';}
return result;}
clone(){return new BitArray(this.size,this.bits.slice());}
toArray(){let result=[];for(let i=0,size=this.size;i<size;i++){result.push(this.get(i));}
return result;}}
var DecodeHintType;(function(DecodeHintType){DecodeHintType[DecodeHintType["OTHER"]=0]="OTHER";DecodeHintType[DecodeHintType["PURE_BARCODE"]=1]="PURE_BARCODE";DecodeHintType[DecodeHintType["POSSIBLE_FORMATS"]=2]="POSSIBLE_FORMATS";DecodeHintType[DecodeHintType["TRY_HARDER"]=3]="TRY_HARDER";DecodeHintType[DecodeHintType["CHARACTER_SET"]=4]="CHARACTER_SET";DecodeHintType[DecodeHintType["ALLOWED_LENGTHS"]=5]="ALLOWED_LENGTHS";DecodeHintType[DecodeHintType["ASSUME_CODE_39_CHECK_DIGIT"]=6]="ASSUME_CODE_39_CHECK_DIGIT";DecodeHintType[DecodeHintType["ASSUME_GS1"]=7]="ASSUME_GS1";DecodeHintType[DecodeHintType["RETURN_CODABAR_START_END"]=8]="RETURN_CODABAR_START_END";DecodeHintType[DecodeHintType["NEED_RESULT_POINT_CALLBACK"]=9]="NEED_RESULT_POINT_CALLBACK";DecodeHintType[DecodeHintType["ALLOWED_EAN_EXTENSIONS"]=10]="ALLOWED_EAN_EXTENSIONS";})(DecodeHintType||(DecodeHintType={}));var DecodeHintType$1=DecodeHintType;class FormatException extends Exception{static getFormatInstance(){return new FormatException();}}
FormatException.kind='FormatException';var CharacterSetValueIdentifiers;(function(CharacterSetValueIdentifiers){CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp437"]=0]="Cp437";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_1"]=1]="ISO8859_1";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_2"]=2]="ISO8859_2";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_3"]=3]="ISO8859_3";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_4"]=4]="ISO8859_4";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_5"]=5]="ISO8859_5";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_6"]=6]="ISO8859_6";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_7"]=7]="ISO8859_7";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_8"]=8]="ISO8859_8";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_9"]=9]="ISO8859_9";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_10"]=10]="ISO8859_10";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_11"]=11]="ISO8859_11";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_13"]=12]="ISO8859_13";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_14"]=13]="ISO8859_14";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_15"]=14]="ISO8859_15";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ISO8859_16"]=15]="ISO8859_16";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["SJIS"]=16]="SJIS";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1250"]=17]="Cp1250";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1251"]=18]="Cp1251";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1252"]=19]="Cp1252";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Cp1256"]=20]="Cp1256";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UnicodeBigUnmarked"]=21]="UnicodeBigUnmarked";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["UTF8"]=22]="UTF8";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["ASCII"]=23]="ASCII";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["Big5"]=24]="Big5";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["GB18030"]=25]="GB18030";CharacterSetValueIdentifiers[CharacterSetValueIdentifiers["EUC_KR"]=26]="EUC_KR";})(CharacterSetValueIdentifiers||(CharacterSetValueIdentifiers={}));class CharacterSetECI{constructor(valueIdentifier,valuesParam,name,...otherEncodingNames){this.valueIdentifier=valueIdentifier;this.name=name;if(typeof valuesParam==='number'){this.values=Int32Array.from([valuesParam]);}
else{this.values=valuesParam;}
this.otherEncodingNames=otherEncodingNames;CharacterSetECI.VALUE_IDENTIFIER_TO_ECI.set(valueIdentifier,this);CharacterSetECI.NAME_TO_ECI.set(name,this);const values=this.values;for(let i=0,length=values.length;i!==length;i++){const v=values[i];CharacterSetECI.VALUES_TO_ECI.set(v,this);}
for(const otherName of otherEncodingNames){CharacterSetECI.NAME_TO_ECI.set(otherName,this);}}
getValueIdentifier(){return this.valueIdentifier;}
getName(){return this.name;}
getValue(){return this.values[0];}
static getCharacterSetECIByValue(value){if(value<0||value>=900){throw new FormatException('incorect value');}
const characterSet=CharacterSetECI.VALUES_TO_ECI.get(value);if(undefined===characterSet){throw new FormatException('incorect value');}
return characterSet;}
static getCharacterSetECIByName(name){const characterSet=CharacterSetECI.NAME_TO_ECI.get(name);if(undefined===characterSet){throw new FormatException('incorect value');}
return characterSet;}
equals(o){if(!(o instanceof CharacterSetECI)){return false;}
const other=o;return this.getName()===other.getName();}}
CharacterSetECI.VALUE_IDENTIFIER_TO_ECI=new Map();CharacterSetECI.VALUES_TO_ECI=new Map();CharacterSetECI.NAME_TO_ECI=new Map();CharacterSetECI.Cp437=new CharacterSetECI(CharacterSetValueIdentifiers.Cp437,Int32Array.from([0,2]),'Cp437');CharacterSetECI.ISO8859_1=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_1,Int32Array.from([1,3]),'ISO-8859-1','ISO88591','ISO8859_1');CharacterSetECI.ISO8859_2=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_2,4,'ISO-8859-2','ISO88592','ISO8859_2');CharacterSetECI.ISO8859_3=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_3,5,'ISO-8859-3','ISO88593','ISO8859_3');CharacterSetECI.ISO8859_4=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_4,6,'ISO-8859-4','ISO88594','ISO8859_4');CharacterSetECI.ISO8859_5=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_5,7,'ISO-8859-5','ISO88595','ISO8859_5');CharacterSetECI.ISO8859_6=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_6,8,'ISO-8859-6','ISO88596','ISO8859_6');CharacterSetECI.ISO8859_7=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_7,9,'ISO-8859-7','ISO88597','ISO8859_7');CharacterSetECI.ISO8859_8=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_8,10,'ISO-8859-8','ISO88598','ISO8859_8');CharacterSetECI.ISO8859_9=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_9,11,'ISO-8859-9','ISO88599','ISO8859_9');CharacterSetECI.ISO8859_10=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_10,12,'ISO-8859-10','ISO885910','ISO8859_10');CharacterSetECI.ISO8859_11=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_11,13,'ISO-8859-11','ISO885911','ISO8859_11');CharacterSetECI.ISO8859_13=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_13,15,'ISO-8859-13','ISO885913','ISO8859_13');CharacterSetECI.ISO8859_14=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_14,16,'ISO-8859-14','ISO885914','ISO8859_14');CharacterSetECI.ISO8859_15=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_15,17,'ISO-8859-15','ISO885915','ISO8859_15');CharacterSetECI.ISO8859_16=new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_16,18,'ISO-8859-16','ISO885916','ISO8859_16');CharacterSetECI.SJIS=new CharacterSetECI(CharacterSetValueIdentifiers.SJIS,20,'SJIS','Shift_JIS');CharacterSetECI.Cp1250=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1250,21,'Cp1250','windows-1250');CharacterSetECI.Cp1251=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1251,22,'Cp1251','windows-1251');CharacterSetECI.Cp1252=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1252,23,'Cp1252','windows-1252');CharacterSetECI.Cp1256=new CharacterSetECI(CharacterSetValueIdentifiers.Cp1256,24,'Cp1256','windows-1256');CharacterSetECI.UnicodeBigUnmarked=new CharacterSetECI(CharacterSetValueIdentifiers.UnicodeBigUnmarked,25,'UnicodeBigUnmarked','UTF-16BE','UnicodeBig');CharacterSetECI.UTF8=new CharacterSetECI(CharacterSetValueIdentifiers.UTF8,26,'UTF8','UTF-8');CharacterSetECI.ASCII=new CharacterSetECI(CharacterSetValueIdentifiers.ASCII,Int32Array.from([27,170]),'ASCII','US-ASCII');CharacterSetECI.Big5=new CharacterSetECI(CharacterSetValueIdentifiers.Big5,28,'Big5');CharacterSetECI.GB18030=new CharacterSetECI(CharacterSetValueIdentifiers.GB18030,29,'GB18030','GB2312','EUC_CN','GBK');CharacterSetECI.EUC_KR=new CharacterSetECI(CharacterSetValueIdentifiers.EUC_KR,30,'EUC_KR','EUC-KR');class UnsupportedOperationException extends Exception{}
UnsupportedOperationException.kind='UnsupportedOperationException';class StringEncoding{static decode(bytes,encoding){const encodingName=this.encodingName(encoding);if(this.customDecoder){return this.customDecoder(bytes,encodingName);}
if(typeof TextDecoder==='undefined'||this.shouldDecodeOnFallback(encodingName)){return this.decodeFallback(bytes,encodingName);}
return new TextDecoder(encodingName).decode(bytes);}
static shouldDecodeOnFallback(encodingName){return!StringEncoding.isBrowser()&&encodingName==='ISO-8859-1';}
static encode(s,encoding){const encodingName=this.encodingName(encoding);if(this.customEncoder){return this.customEncoder(s,encodingName);}
if(typeof TextEncoder==='undefined'){return this.encodeFallback(s);}
return new TextEncoder().encode(s);}
static isBrowser(){return(typeof window!=='undefined'&&{}.toString.call(window)==='[object Window]');}
static encodingName(encoding){return typeof encoding==='string'?encoding:encoding.getName();}
static encodingCharacterSet(encoding){if(encoding instanceof CharacterSetECI){return encoding;}
return CharacterSetECI.getCharacterSetECIByName(encoding);}
static decodeFallback(bytes,encoding){const characterSet=this.encodingCharacterSet(encoding);if(StringEncoding.isDecodeFallbackSupported(characterSet)){let s='';for(let i=0,length=bytes.length;i<length;i++){let h=bytes[i].toString(16);if(h.length<2){h='0'+h;}
s+='%'+h;}
return decodeURIComponent(s);}
if(characterSet.equals(CharacterSetECI.UnicodeBigUnmarked)){return String.fromCharCode.apply(null,new Uint16Array(bytes.buffer));}
throw new UnsupportedOperationException(`Encoding ${this.encodingName(encoding)} not supported by fallback.`);}
static isDecodeFallbackSupported(characterSet){return characterSet.equals(CharacterSetECI.UTF8)||characterSet.equals(CharacterSetECI.ISO8859_1)||characterSet.equals(CharacterSetECI.ASCII);}
static encodeFallback(s){const encodedURIstring=btoa(unescape(encodeURIComponent(s)));const charList=encodedURIstring.split('');const uintArray=[];for(let i=0;i<charList.length;i++){uintArray.push(charList[i].charCodeAt(0));}
return new Uint8Array(uintArray);}}
class StringUtils{static castAsNonUtf8Char(code,encoding=null){const e=encoding?encoding.getName():this.ISO88591;return StringEncoding.decode(new Uint8Array([code]),e);}
static guessEncoding(bytes,hints){if(hints!==null&&hints!==undefined&&undefined!==hints.get(DecodeHintType$1.CHARACTER_SET)){return hints.get(DecodeHintType$1.CHARACTER_SET).toString();}
const length=bytes.length;let canBeISO88591=true;let canBeShiftJIS=true;let canBeUTF8=true;let utf8BytesLeft=0;let utf2BytesChars=0;let utf3BytesChars=0;let utf4BytesChars=0;let sjisBytesLeft=0;let sjisKatakanaChars=0;let sjisCurKatakanaWordLength=0;let sjisCurDoubleBytesWordLength=0;let sjisMaxKatakanaWordLength=0;let sjisMaxDoubleBytesWordLength=0;let isoHighOther=0;const utf8bom=bytes.length>3&&bytes[0]===0xEF&&bytes[1]===0xBB&&bytes[2]===0xBF;for(let i=0;i<length&&(canBeISO88591||canBeShiftJIS||canBeUTF8);i++){const value=bytes[i]&0xFF;if(canBeUTF8){if(utf8BytesLeft>0){if((value&0x80)===0){canBeUTF8=false;}
else{utf8BytesLeft--;}}
else if((value&0x80)!==0){if((value&0x40)===0){canBeUTF8=false;}
else{utf8BytesLeft++;if((value&0x20)===0){utf2BytesChars++;}
else{utf8BytesLeft++;if((value&0x10)===0){utf3BytesChars++;}
else{utf8BytesLeft++;if((value&0x08)===0){utf4BytesChars++;}
else{canBeUTF8=false;}}}}}}
if(canBeISO88591){if(value>0x7F&&value<0xA0){canBeISO88591=false;}
else if(value>0x9F){if(value<0xC0||value===0xD7||value===0xF7){isoHighOther++;}}}
if(canBeShiftJIS){if(sjisBytesLeft>0){if(value<0x40||value===0x7F||value>0xFC){canBeShiftJIS=false;}
else{sjisBytesLeft--;}}
else if(value===0x80||value===0xA0||value>0xEF){canBeShiftJIS=false;}
else if(value>0xA0&&value<0xE0){sjisKatakanaChars++;sjisCurDoubleBytesWordLength=0;sjisCurKatakanaWordLength++;if(sjisCurKatakanaWordLength>sjisMaxKatakanaWordLength){sjisMaxKatakanaWordLength=sjisCurKatakanaWordLength;}}
else if(value>0x7F){sjisBytesLeft++;sjisCurKatakanaWordLength=0;sjisCurDoubleBytesWordLength++;if(sjisCurDoubleBytesWordLength>sjisMaxDoubleBytesWordLength){sjisMaxDoubleBytesWordLength=sjisCurDoubleBytesWordLength;}}
else{sjisCurKatakanaWordLength=0;sjisCurDoubleBytesWordLength=0;}}}
if(canBeUTF8&&utf8BytesLeft>0){canBeUTF8=false;}
if(canBeShiftJIS&&sjisBytesLeft>0){canBeShiftJIS=false;}
if(canBeUTF8&&(utf8bom||utf2BytesChars+utf3BytesChars+utf4BytesChars>0)){return StringUtils.UTF8;}
if(canBeShiftJIS&&(StringUtils.ASSUME_SHIFT_JIS||sjisMaxKatakanaWordLength>=3||sjisMaxDoubleBytesWordLength>=3)){return StringUtils.SHIFT_JIS;}
if(canBeISO88591&&canBeShiftJIS){return(sjisMaxKatakanaWordLength===2&&sjisKatakanaChars===2)||isoHighOther*10>=length?StringUtils.SHIFT_JIS:StringUtils.ISO88591;}
if(canBeISO88591){return StringUtils.ISO88591;}
if(canBeShiftJIS){return StringUtils.SHIFT_JIS;}
if(canBeUTF8){return StringUtils.UTF8;}
return StringUtils.PLATFORM_DEFAULT_ENCODING;}
static format(append,...args){let i=-1;function callback(exp,p0,p1,p2,p3,p4){if(exp==='%%')
return'%';if(args[++i]===undefined)
return undefined;exp=p2?parseInt(p2.substr(1)):undefined;let base=p3?parseInt(p3.substr(1)):undefined;let val;switch(p4){case's':val=args[i];break;case'c':val=args[i][0];break;case'f':val=parseFloat(args[i]).toFixed(exp);break;case'p':val=parseFloat(args[i]).toPrecision(exp);break;case'e':val=parseFloat(args[i]).toExponential(exp);break;case'x':val=parseInt(args[i]).toString(base?base:16);break;case'd':val=parseFloat(parseInt(args[i],base?base:10).toPrecision(exp)).toFixed(0);break;}
val=typeof val==='object'?JSON.stringify(val):(+val).toString(base);let size=parseInt(p1);let ch=p1&&(p1[0]+'')==='0'?'0':' ';while(val.length<size)
val=p0!==undefined?val+ch:ch+val;return val;}
let regex=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return append.replace(regex,callback);}
static getBytes(str,encoding){return StringEncoding.encode(str,encoding);}
static getCharCode(str,index=0){return str.charCodeAt(index);}
static getCharAt(charCode){return String.fromCharCode(charCode);}}
StringUtils.SHIFT_JIS=CharacterSetECI.SJIS.getName();StringUtils.GB2312='GB2312';StringUtils.ISO88591=CharacterSetECI.ISO8859_1.getName();StringUtils.EUC_JP='EUC_JP';StringUtils.UTF8=CharacterSetECI.UTF8.getName();StringUtils.PLATFORM_DEFAULT_ENCODING=StringUtils.UTF8;StringUtils.ASSUME_SHIFT_JIS=false;class StringBuilder{constructor(value=''){this.value=value;}
enableDecoding(encoding){this.encoding=encoding;return this;}
append(s){if(typeof s==='string'){this.value+=s.toString();}
else if(this.encoding){this.value+=StringUtils.castAsNonUtf8Char(s,this.encoding);}
else{this.value+=String.fromCharCode(s);}
return this;}
appendChars(str,offset,len){for(let i=offset;offset<offset+len;i++){this.append(str[i]);}
return this;}
length(){return this.value.length;}
charAt(n){return this.value.charAt(n);}
deleteCharAt(n){this.value=this.value.substr(0,n)+this.value.substring(n+1);}
setCharAt(n,c){this.value=this.value.substr(0,n)+c+this.value.substr(n+1);}
substring(start,end){return this.value.substring(start,end);}
setLengthToZero(){this.value='';}
toString(){return this.value;}
insert(n,c){this.value=this.value.substring(0,n)+c+this.value.substring(n);}}
class BitMatrix{constructor(width,height,rowSize,bits){this.width=width;this.height=height;this.rowSize=rowSize;this.bits=bits;if(undefined===height||null===height){height=width;}
this.height=height;if(width<1||height<1){throw new IllegalArgumentException('Both dimensions must be greater than 0');}
if(undefined===rowSize||null===rowSize){rowSize=Math.floor((width+31)/32);}
this.rowSize=rowSize;if(undefined===bits||null===bits){this.bits=new Int32Array(this.rowSize*this.height);}}
static parseFromBooleanArray(image){const height=image.length;const width=image[0].length;const bits=new BitMatrix(width,height);for(let i=0;i<height;i++){const imageI=image[i];for(let j=0;j<width;j++){if(imageI[j]){bits.set(j,i);}}}
return bits;}
static parseFromString(stringRepresentation,setString,unsetString){if(stringRepresentation===null){throw new IllegalArgumentException('stringRepresentation cannot be null');}
const bits=new Array(stringRepresentation.length);let bitsPos=0;let rowStartPos=0;let rowLength=-1;let nRows=0;let pos=0;while(pos<stringRepresentation.length){if(stringRepresentation.charAt(pos)==='\n'||stringRepresentation.charAt(pos)==='\r'){if(bitsPos>rowStartPos){if(rowLength===-1){rowLength=bitsPos-rowStartPos;}
else if(bitsPos-rowStartPos!==rowLength){throw new IllegalArgumentException('row lengths do not match');}
rowStartPos=bitsPos;nRows++;}
pos++;}
else if(stringRepresentation.substring(pos,pos+setString.length)===setString){pos+=setString.length;bits[bitsPos]=true;bitsPos++;}
else if(stringRepresentation.substring(pos,pos+unsetString.length)===unsetString){pos+=unsetString.length;bits[bitsPos]=false;bitsPos++;}
else{throw new IllegalArgumentException('illegal character encountered: '+stringRepresentation.substring(pos));}}
if(bitsPos>rowStartPos){if(rowLength===-1){rowLength=bitsPos-rowStartPos;}
else if(bitsPos-rowStartPos!==rowLength){throw new IllegalArgumentException('row lengths do not match');}
nRows++;}
const matrix=new BitMatrix(rowLength,nRows);for(let i=0;i<bitsPos;i++){if(bits[i]){matrix.set(Math.floor(i%rowLength),Math.floor(i/rowLength));}}
return matrix;}
get(x,y){const offset=y*this.rowSize+Math.floor(x/32);return((this.bits[offset]>>>(x&0x1f))&1)!==0;}
set(x,y){const offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]|=(1<<(x&0x1f))&0xFFFFFFFF;}
unset(x,y){const offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]&=~((1<<(x&0x1f))&0xFFFFFFFF);}
flip(x,y){const offset=y*this.rowSize+Math.floor(x/32);this.bits[offset]^=((1<<(x&0x1f))&0xFFFFFFFF);}
xor(mask){if(this.width!==mask.getWidth()||this.height!==mask.getHeight()||this.rowSize!==mask.getRowSize()){throw new IllegalArgumentException('input matrix dimensions do not match');}
const rowArray=new BitArray(Math.floor(this.width/32)+1);const rowSize=this.rowSize;const bits=this.bits;for(let y=0,height=this.height;y<height;y++){const offset=y*rowSize;const row=mask.getRow(y,rowArray).getBitArray();for(let x=0;x<rowSize;x++){bits[offset+x]^=row[x];}}}
clear(){const bits=this.bits;const max=bits.length;for(let i=0;i<max;i++){bits[i]=0;}}
setRegion(left,top,width,height){if(top<0||left<0){throw new IllegalArgumentException('Left and top must be nonnegative');}
if(height<1||width<1){throw new IllegalArgumentException('Height and width must be at least 1');}
const right=left+width;const bottom=top+height;if(bottom>this.height||right>this.width){throw new IllegalArgumentException('The region must fit inside the matrix');}
const rowSize=this.rowSize;const bits=this.bits;for(let y=top;y<bottom;y++){const offset=y*rowSize;for(let x=left;x<right;x++){bits[offset+Math.floor(x/32)]|=((1<<(x&0x1f))&0xFFFFFFFF);}}}
getRow(y,row){if(row===null||row===undefined||row.getSize()<this.width){row=new BitArray(this.width);}
else{row.clear();}
const rowSize=this.rowSize;const bits=this.bits;const offset=y*rowSize;for(let x=0;x<rowSize;x++){row.setBulk(x*32,bits[offset+x]);}
return row;}
setRow(y,row){System.arraycopy(row.getBitArray(),0,this.bits,y*this.rowSize,this.rowSize);}
rotate180(){const width=this.getWidth();const height=this.getHeight();let topRow=new BitArray(width);let bottomRow=new BitArray(width);for(let i=0,length=Math.floor((height+1)/2);i<length;i++){topRow=this.getRow(i,topRow);bottomRow=this.getRow(height-1-i,bottomRow);topRow.reverse();bottomRow.reverse();this.setRow(i,bottomRow);this.setRow(height-1-i,topRow);}}
getEnclosingRectangle(){const width=this.width;const height=this.height;const rowSize=this.rowSize;const bits=this.bits;let left=width;let top=height;let right=-1;let bottom=-1;for(let y=0;y<height;y++){for(let x32=0;x32<rowSize;x32++){const theBits=bits[y*rowSize+x32];if(theBits!==0){if(y<top){top=y;}
if(y>bottom){bottom=y;}
if(x32*32<left){let bit=0;while(((theBits<<(31-bit))&0xFFFFFFFF)===0){bit++;}
if((x32*32+bit)<left){left=x32*32+bit;}}
if(x32*32+31>right){let bit=31;while((theBits>>>bit)===0){bit--;}
if((x32*32+bit)>right){right=x32*32+bit;}}}}}
if(right<left||bottom<top){return null;}
return Int32Array.from([left,top,right-left+1,bottom-top+1]);}
getTopLeftOnBit(){const rowSize=this.rowSize;const bits=this.bits;let bitsOffset=0;while(bitsOffset<bits.length&&bits[bitsOffset]===0){bitsOffset++;}
if(bitsOffset===bits.length){return null;}
const y=bitsOffset/rowSize;let x=(bitsOffset%rowSize)*32;const theBits=bits[bitsOffset];let bit=0;while(((theBits<<(31-bit))&0xFFFFFFFF)===0){bit++;}
x+=bit;return Int32Array.from([x,y]);}
getBottomRightOnBit(){const rowSize=this.rowSize;const bits=this.bits;let bitsOffset=bits.length-1;while(bitsOffset>=0&&bits[bitsOffset]===0){bitsOffset--;}
if(bitsOffset<0){return null;}
const y=Math.floor(bitsOffset/rowSize);let x=Math.floor(bitsOffset%rowSize)*32;const theBits=bits[bitsOffset];let bit=31;while((theBits>>>bit)===0){bit--;}
x+=bit;return Int32Array.from([x,y]);}
getWidth(){return this.width;}
getHeight(){return this.height;}
getRowSize(){return this.rowSize;}
equals(o){if(!(o instanceof BitMatrix)){return false;}
const other=o;return this.width===other.width&&this.height===other.height&&this.rowSize===other.rowSize&&Arrays.equals(this.bits,other.bits);}
hashCode(){let hash=this.width;hash=31*hash+this.width;hash=31*hash+this.height;hash=31*hash+this.rowSize;hash=31*hash+Arrays.hashCode(this.bits);return hash;}
toString(setString='X ',unsetString='  ',lineSeparator='\n'){return this.buildToString(setString,unsetString,lineSeparator);}
buildToString(setString,unsetString,lineSeparator){let result=new StringBuilder();for(let y=0,height=this.height;y<height;y++){for(let x=0,width=this.width;x<width;x++){result.append(this.get(x,y)?setString:unsetString);}
result.append(lineSeparator);}
return result.toString();}
clone(){return new BitMatrix(this.width,this.height,this.rowSize,this.bits.slice());}}
class NotFoundException extends Exception{static getNotFoundInstance(){return new NotFoundException();}}
NotFoundException.kind='NotFoundException';class GlobalHistogramBinarizer extends Binarizer{constructor(source){super(source);this.luminances=GlobalHistogramBinarizer.EMPTY;this.buckets=new Int32Array(GlobalHistogramBinarizer.LUMINANCE_BUCKETS);}
getBlackRow(y,row){const source=this.getLuminanceSource();const width=source.getWidth();if(row===undefined||row===null||row.getSize()<width){row=new BitArray(width);}
else{row.clear();}
this.initArrays(width);const localLuminances=source.getRow(y,this.luminances);const localBuckets=this.buckets;for(let x=0;x<width;x++){localBuckets[(localLuminances[x]&0xff)>>GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;}
const blackPoint=GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);if(width<3){for(let x=0;x<width;x++){if((localLuminances[x]&0xff)<blackPoint){row.set(x);}}}
else{let left=localLuminances[0]&0xff;let center=localLuminances[1]&0xff;for(let x=1;x<width-1;x++){const right=localLuminances[x+1]&0xff;if(((center*4)-left-right)/2<blackPoint){row.set(x);}
left=center;center=right;}}
return row;}
getBlackMatrix(){const source=this.getLuminanceSource();const width=source.getWidth();const height=source.getHeight();const matrix=new BitMatrix(width,height);this.initArrays(width);const localBuckets=this.buckets;for(let y=1;y<5;y++){const row=Math.floor((height*y)/5);const localLuminances=source.getRow(row,this.luminances);const right=Math.floor((width*4)/5);for(let x=Math.floor(width/5);x<right;x++){const pixel=localLuminances[x]&0xff;localBuckets[pixel>>GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;}}
const blackPoint=GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);const localLuminances=source.getMatrix();for(let y=0;y<height;y++){const offset=y*width;for(let x=0;x<width;x++){const pixel=localLuminances[offset+x]&0xff;if(pixel<blackPoint){matrix.set(x,y);}}}
return matrix;}
createBinarizer(source){return new GlobalHistogramBinarizer(source);}
initArrays(luminanceSize){if(this.luminances.length<luminanceSize){this.luminances=new Uint8ClampedArray(luminanceSize);}
const buckets=this.buckets;for(let x=0;x<GlobalHistogramBinarizer.LUMINANCE_BUCKETS;x++){buckets[x]=0;}}
static estimateBlackPoint(buckets){const numBuckets=buckets.length;let maxBucketCount=0;let firstPeak=0;let firstPeakSize=0;for(let x=0;x<numBuckets;x++){if(buckets[x]>firstPeakSize){firstPeak=x;firstPeakSize=buckets[x];}
if(buckets[x]>maxBucketCount){maxBucketCount=buckets[x];}}
let secondPeak=0;let secondPeakScore=0;for(let x=0;x<numBuckets;x++){const distanceToBiggest=x-firstPeak;const score=buckets[x]*distanceToBiggest*distanceToBiggest;if(score>secondPeakScore){secondPeak=x;secondPeakScore=score;}}
if(firstPeak>secondPeak){const temp=firstPeak;firstPeak=secondPeak;secondPeak=temp;}
if(secondPeak-firstPeak<=numBuckets/16){throw new NotFoundException();}
let bestValley=secondPeak-1;let bestValleyScore=-1;for(let x=secondPeak-1;x>firstPeak;x--){const fromFirst=x-firstPeak;const score=fromFirst*fromFirst*(secondPeak-x)*(maxBucketCount-buckets[x]);if(score>bestValleyScore){bestValley=x;bestValleyScore=score;}}
return bestValley<<GlobalHistogramBinarizer.LUMINANCE_SHIFT;}}
GlobalHistogramBinarizer.LUMINANCE_BITS=5;GlobalHistogramBinarizer.LUMINANCE_SHIFT=8-GlobalHistogramBinarizer.LUMINANCE_BITS;GlobalHistogramBinarizer.LUMINANCE_BUCKETS=1<<GlobalHistogramBinarizer.LUMINANCE_BITS;GlobalHistogramBinarizer.EMPTY=Uint8ClampedArray.from([0]);class HybridBinarizer extends GlobalHistogramBinarizer{constructor(source){super(source);this.matrix=null;}
getBlackMatrix(){if(this.matrix!==null){return this.matrix;}
const source=this.getLuminanceSource();const width=source.getWidth();const height=source.getHeight();if(width>=HybridBinarizer.MINIMUM_DIMENSION&&height>=HybridBinarizer.MINIMUM_DIMENSION){const luminances=source.getMatrix();let subWidth=width>>HybridBinarizer.BLOCK_SIZE_POWER;if((width&HybridBinarizer.BLOCK_SIZE_MASK)!==0){subWidth++;}
let subHeight=height>>HybridBinarizer.BLOCK_SIZE_POWER;if((height&HybridBinarizer.BLOCK_SIZE_MASK)!==0){subHeight++;}
const blackPoints=HybridBinarizer.calculateBlackPoints(luminances,subWidth,subHeight,width,height);const newMatrix=new BitMatrix(width,height);HybridBinarizer.calculateThresholdForBlock(luminances,subWidth,subHeight,width,height,blackPoints,newMatrix);this.matrix=newMatrix;}
else{this.matrix=super.getBlackMatrix();}
return this.matrix;}
createBinarizer(source){return new HybridBinarizer(source);}
static calculateThresholdForBlock(luminances,subWidth,subHeight,width,height,blackPoints,matrix){const maxYOffset=height-HybridBinarizer.BLOCK_SIZE;const maxXOffset=width-HybridBinarizer.BLOCK_SIZE;for(let y=0;y<subHeight;y++){let yoffset=y<<HybridBinarizer.BLOCK_SIZE_POWER;if(yoffset>maxYOffset){yoffset=maxYOffset;}
const top=HybridBinarizer.cap(y,2,subHeight-3);for(let x=0;x<subWidth;x++){let xoffset=x<<HybridBinarizer.BLOCK_SIZE_POWER;if(xoffset>maxXOffset){xoffset=maxXOffset;}
const left=HybridBinarizer.cap(x,2,subWidth-3);let sum=0;for(let z=-2;z<=2;z++){const blackRow=blackPoints[top+z];sum+=blackRow[left-2]+blackRow[left-1]+blackRow[left]+blackRow[left+1]+blackRow[left+2];}
const average=sum/25;HybridBinarizer.thresholdBlock(luminances,xoffset,yoffset,average,width,matrix);}}}
static cap(value,min,max){return value<min?min:value>max?max:value;}
static thresholdBlock(luminances,xoffset,yoffset,threshold,stride,matrix){for(let y=0,offset=yoffset*stride+xoffset;y<HybridBinarizer.BLOCK_SIZE;y++,offset+=stride){for(let x=0;x<HybridBinarizer.BLOCK_SIZE;x++){if((luminances[offset+x]&0xFF)<=threshold){matrix.set(xoffset+x,yoffset+y);}}}}
static calculateBlackPoints(luminances,subWidth,subHeight,width,height){const maxYOffset=height-HybridBinarizer.BLOCK_SIZE;const maxXOffset=width-HybridBinarizer.BLOCK_SIZE;const blackPoints=new Array(subHeight);for(let y=0;y<subHeight;y++){blackPoints[y]=new Int32Array(subWidth);let yoffset=y<<HybridBinarizer.BLOCK_SIZE_POWER;if(yoffset>maxYOffset){yoffset=maxYOffset;}
for(let x=0;x<subWidth;x++){let xoffset=x<<HybridBinarizer.BLOCK_SIZE_POWER;if(xoffset>maxXOffset){xoffset=maxXOffset;}
let sum=0;let min=0xFF;let max=0;for(let yy=0,offset=yoffset*width+xoffset;yy<HybridBinarizer.BLOCK_SIZE;yy++,offset+=width){for(let xx=0;xx<HybridBinarizer.BLOCK_SIZE;xx++){const pixel=luminances[offset+xx]&0xFF;sum+=pixel;if(pixel<min){min=pixel;}
if(pixel>max){max=pixel;}}
if(max-min>HybridBinarizer.MIN_DYNAMIC_RANGE){for(yy++,offset+=width;yy<HybridBinarizer.BLOCK_SIZE;yy++,offset+=width){for(let xx=0;xx<HybridBinarizer.BLOCK_SIZE;xx++){sum+=luminances[offset+xx]&0xFF;}}}}
let average=sum>>(HybridBinarizer.BLOCK_SIZE_POWER*2);if(max-min<=HybridBinarizer.MIN_DYNAMIC_RANGE){average=min/2;if(y>0&&x>0){const averageNeighborBlackPoint=(blackPoints[y-1][x]+(2*blackPoints[y][x-1])+blackPoints[y-1][x-1])/4;if(min<averageNeighborBlackPoint){average=averageNeighborBlackPoint;}}}
blackPoints[y][x]=average;}}
return blackPoints;}}
HybridBinarizer.BLOCK_SIZE_POWER=3;HybridBinarizer.BLOCK_SIZE=1<<HybridBinarizer.BLOCK_SIZE_POWER;HybridBinarizer.BLOCK_SIZE_MASK=HybridBinarizer.BLOCK_SIZE-1;HybridBinarizer.MINIMUM_DIMENSION=HybridBinarizer.BLOCK_SIZE*5;HybridBinarizer.MIN_DYNAMIC_RANGE=24;class LuminanceSource{constructor(width,height){this.width=width;this.height=height;}
getWidth(){return this.width;}
getHeight(){return this.height;}
isCropSupported(){return false;}
crop(left,top,width,height){throw new UnsupportedOperationException('This luminance source does not support cropping.');}
isRotateSupported(){return false;}
rotateCounterClockwise(){throw new UnsupportedOperationException('This luminance source does not support rotation by 90 degrees.');}
rotateCounterClockwise45(){throw new UnsupportedOperationException('This luminance source does not support rotation by 45 degrees.');}
toString(){const row=new Uint8ClampedArray(this.width);let result=new StringBuilder();for(let y=0;y<this.height;y++){const sourceRow=this.getRow(y,row);for(let x=0;x<this.width;x++){const luminance=sourceRow[x]&0xFF;let c;if(luminance<0x40){c='#';}
else if(luminance<0x80){c='+';}
else if(luminance<0xC0){c='.';}
else{c=' ';}
result.append(c);}
result.append('\n');}
return result.toString();}}
class InvertedLuminanceSource extends LuminanceSource{constructor(delegate){super(delegate.getWidth(),delegate.getHeight());this.delegate=delegate;}
getRow(y,row){const sourceRow=this.delegate.getRow(y,row);const width=this.getWidth();for(let i=0;i<width;i++){sourceRow[i]=(255-(sourceRow[i]&0xFF));}
return sourceRow;}
getMatrix(){const matrix=this.delegate.getMatrix();const length=this.getWidth()*this.getHeight();const invertedMatrix=new Uint8ClampedArray(length);for(let i=0;i<length;i++){invertedMatrix[i]=(255-(matrix[i]&0xFF));}
return invertedMatrix;}
isCropSupported(){return this.delegate.isCropSupported();}
crop(left,top,width,height){return new InvertedLuminanceSource(this.delegate.crop(left,top,width,height));}
isRotateSupported(){return this.delegate.isRotateSupported();}
invert(){return this.delegate;}
rotateCounterClockwise(){return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise());}
rotateCounterClockwise45(){return new InvertedLuminanceSource(this.delegate.rotateCounterClockwise45());}}
class HTMLCanvasElementLuminanceSource extends LuminanceSource{constructor(canvas){super(canvas.width,canvas.height);this.canvas=canvas;this.tempCanvasElement=null;this.buffer=HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(canvas);}
static makeBufferFromCanvasImageData(canvas){const imageData=canvas.getContext('2d').getImageData(0,0,canvas.width,canvas.height);return HTMLCanvasElementLuminanceSource.toGrayscaleBuffer(imageData.data,canvas.width,canvas.height);}
static toGrayscaleBuffer(imageBuffer,width,height){const grayscaleBuffer=new Uint8ClampedArray(width*height);HTMLCanvasElementLuminanceSource.FRAME_INDEX=!HTMLCanvasElementLuminanceSource.FRAME_INDEX;if(HTMLCanvasElementLuminanceSource.FRAME_INDEX){for(let i=0,j=0,length=imageBuffer.length;i<length;i+=4,j++){let gray;const alpha=imageBuffer[i+3];if(alpha===0){gray=0xFF;}
else{const pixelR=imageBuffer[i];const pixelG=imageBuffer[i+1];const pixelB=imageBuffer[i+2];gray=(306*pixelR+
601*pixelG+
117*pixelB+
0x200)>>10;}
grayscaleBuffer[j]=gray;}}
else{for(let i=0,j=0,length=imageBuffer.length;i<length;i+=4,j++){let gray;const alpha=imageBuffer[i+3];if(alpha===0){gray=0xFF;}
else{const pixelR=imageBuffer[i];const pixelG=imageBuffer[i+1];const pixelB=imageBuffer[i+2];gray=(306*pixelR+
601*pixelG+
117*pixelB+
0x200)>>10;}
grayscaleBuffer[j]=0xFF-gray;}}
return grayscaleBuffer;}
getRow(y,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}
const width=this.getWidth();const start=y*width;if(row===null){row=this.buffer.slice(start,start+width);}
else{if(row.length<width){row=new Uint8ClampedArray(width);}
row.set(this.buffer.slice(start,start+width));}
return row;}
getMatrix(){return this.buffer;}
isCropSupported(){return true;}
crop(left,top,width,height){super.crop(left,top,width,height);return this;}
isRotateSupported(){return true;}
rotateCounterClockwise(){this.rotate(-90);return this;}
rotateCounterClockwise45(){this.rotate(-45);return this;}
getTempCanvasElement(){if(null===this.tempCanvasElement){const tempCanvasElement=this.canvas.ownerDocument.createElement('canvas');tempCanvasElement.width=this.canvas.width;tempCanvasElement.height=this.canvas.height;this.tempCanvasElement=tempCanvasElement;}
return this.tempCanvasElement;}
rotate(angle){const tempCanvasElement=this.getTempCanvasElement();const tempContext=tempCanvasElement.getContext('2d');const angleRadians=angle*HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS;const width=this.canvas.width;const height=this.canvas.height;const newWidth=Math.ceil(Math.abs(Math.cos(angleRadians))*width+Math.abs(Math.sin(angleRadians))*height);const newHeight=Math.ceil(Math.abs(Math.sin(angleRadians))*width+Math.abs(Math.cos(angleRadians))*height);tempCanvasElement.width=newWidth;tempCanvasElement.height=newHeight;tempContext.translate(newWidth/2,newHeight/2);tempContext.rotate(angleRadians);tempContext.drawImage(this.canvas,width/-2,height/-2);this.buffer=HTMLCanvasElementLuminanceSource.makeBufferFromCanvasImageData(tempCanvasElement);return this;}
invert(){return new InvertedLuminanceSource(this);}}
HTMLCanvasElementLuminanceSource.DEGREE_TO_RADIANS=Math.PI/180;HTMLCanvasElementLuminanceSource.FRAME_INDEX=true;class VideoInputDevice{constructor(deviceId,label,groupId){this.deviceId=deviceId;this.label=label;this.kind='videoinput';this.groupId=groupId||undefined;}
toJSON(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label,};}}
var __awaiter=((globalThis||global||self||window||undefined)&&(globalThis||global||self||window||undefined).__awaiter)||function(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value);});}
return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value));}catch(e){reject(e);}}
function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e);}}
function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}
step((generator=generator.apply(thisArg,_arguments||[])).next());});};class BrowserCodeReader{constructor(reader,timeBetweenScansMillis=500,_hints){this.reader=reader;this.timeBetweenScansMillis=timeBetweenScansMillis;this._hints=_hints;this._stopContinuousDecode=false;this._stopAsyncDecode=false;this._timeBetweenDecodingAttempts=0;}
get hasNavigator(){return typeof navigator!=='undefined';}
get isMediaDevicesSuported(){return this.hasNavigator&&!!navigator.mediaDevices;}
get canEnumerateDevices(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices);}
get timeBetweenDecodingAttempts(){return this._timeBetweenDecodingAttempts;}
set timeBetweenDecodingAttempts(millis){this._timeBetweenDecodingAttempts=millis<0?0:millis;}
set hints(hints){this._hints=hints||null;}
get hints(){return this._hints;}
listVideoInputDevices(){return __awaiter(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 devices=yield navigator.mediaDevices.enumerateDevices();const videoDevices=[];for(const device of devices){const kind=device.kind==='video'?'videoinput':device.kind;if(kind!=='videoinput'){continue;}
const deviceId=device.deviceId||device.id;const label=device.label||`Video device ${videoDevices.length + 1}`;const groupId=device.groupId;const videoDevice={deviceId,label,kind,groupId};videoDevices.push(videoDevice);}
return videoDevices;});}
getVideoInputDevices(){return __awaiter(this,void 0,void 0,function*(){const devices=yield this.listVideoInputDevices();return devices.map(d=>new VideoInputDevice(d.deviceId,d.label));});}
findDeviceById(deviceId){return __awaiter(this,void 0,void 0,function*(){const devices=yield this.listVideoInputDevices();if(!devices){return null;}
return devices.find(x=>x.deviceId===deviceId);});}
decodeFromInputVideoDevice(deviceId,videoSource){return __awaiter(this,void 0,void 0,function*(){return yield this.decodeOnceFromVideoDevice(deviceId,videoSource);});}
decodeOnceFromVideoDevice(deviceId,videoSource){return __awaiter(this,void 0,void 0,function*(){this.reset();let videoConstraints;if(!deviceId){videoConstraints={facingMode:'environment'};}
else{videoConstraints={deviceId:{exact:deviceId}};}
const constraints={video:videoConstraints};return yield this.decodeOnceFromConstraints(constraints,videoSource);});}
decodeOnceFromConstraints(constraints,videoSource){return __awaiter(this,void 0,void 0,function*(){const stream=yield navigator.mediaDevices.getUserMedia(constraints);return yield this.decodeOnceFromStream(stream,videoSource);});}
decodeOnceFromStream(stream,videoSource){return __awaiter(this,void 0,void 0,function*(){this.reset();const video=yield this.attachStreamToVideo(stream,videoSource);const result=yield this.decodeOnce(video);return result;});}
decodeFromInputVideoDeviceContinuously(deviceId,videoSource,callbackFn){return __awaiter(this,void 0,void 0,function*(){return yield this.decodeFromVideoDevice(deviceId,videoSource,callbackFn);});}
decodeFromVideoDevice(deviceId,videoSource,callbackFn){return __awaiter(this,void 0,void 0,function*(){let videoConstraints;if(!deviceId){videoConstraints={facingMode:'environment'};}
else{videoConstraints={deviceId:{exact:deviceId}};}
const constraints={video:videoConstraints};return yield this.decodeFromConstraints(constraints,videoSource,callbackFn);});}
decodeFromConstraints(constraints,videoSource,callbackFn){return __awaiter(this,void 0,void 0,function*(){const stream=yield navigator.mediaDevices.getUserMedia(constraints);return yield this.decodeFromStream(stream,videoSource,callbackFn);});}
decodeFromStream(stream,videoSource,callbackFn){return __awaiter(this,void 0,void 0,function*(){this.reset();const video=yield this.attachStreamToVideo(stream,videoSource);return yield this.decodeContinuously(video,callbackFn);});}
stopAsyncDecode(){this._stopAsyncDecode=true;}
stopContinuousDecode(){this._stopContinuousDecode=true;}
attachStreamToVideo(stream,videoSource){return __awaiter(this,void 0,void 0,function*(){const videoElement=this.prepareVideoElement(videoSource);this.addVideoSource(videoElement,stream);this.videoElement=videoElement;this.stream=stream;yield this.playVideoOnLoadAsync(videoElement);return videoElement;});}
playVideoOnLoadAsync(videoElement){return new Promise((resolve,reject)=>this.playVideoOnLoad(videoElement,()=>resolve()));}
playVideoOnLoad(element,callbackFn){this.videoEndedListener=()=>this.stopStreams();this.videoCanPlayListener=()=>this.tryPlayVideo(element);element.addEventListener('ended',this.videoEndedListener);element.addEventListener('canplay',this.videoCanPlayListener);element.addEventListener('playing',callbackFn);this.tryPlayVideo(element);}
isVideoPlaying(video){return(video.currentTime>0&&!video.paused&&!video.ended&&video.readyState>2);}
tryPlayVideo(videoElement){return __awaiter(this,void 0,void 0,function*(){if(this.isVideoPlaying(videoElement)){console.warn('Trying to play video that is already playing.');return;}
try{yield videoElement.play();}
catch(_a){console.warn('It was not possible to play the video.');}});}
getMediaElement(mediaElementId,type){const mediaElement=document.getElementById(mediaElementId);if(!mediaElement){throw new ArgumentException(`element with id '${mediaElementId}' not found`);}
if(mediaElement.nodeName.toLowerCase()!==type.toLowerCase()){throw new ArgumentException(`element with id '${mediaElementId}' must be an ${type} element`);}
return mediaElement;}
decodeFromImage(source,url){if(!source&&!url){throw new ArgumentException('either imageElement with a src set or an url must be provided');}
if(url&&!source){return this.decodeFromImageUrl(url);}
return this.decodeFromImageElement(source);}
decodeFromVideo(source,url){if(!source&&!url){throw new ArgumentException('Either an element with a src set or an URL must be provided');}
if(url&&!source){return this.decodeFromVideoUrl(url);}
return this.decodeFromVideoElement(source);}
decodeFromVideoContinuously(source,url,callbackFn){if(undefined===source&&undefined===url){throw new ArgumentException('Either an element with a src set or an URL must be provided');}
if(url&&!source){return this.decodeFromVideoUrlContinuously(url,callbackFn);}
return this.decodeFromVideoElementContinuously(source,callbackFn);}
decodeFromImageElement(source){if(!source){throw new ArgumentException('An image element must be provided.');}
this.reset();const element=this.prepareImageElement(source);this.imageElement=element;let task;if(this.isImageLoaded(element)){task=this.decodeOnce(element,false,true);}
else{task=this._decodeOnLoadImage(element);}
return task;}
decodeFromVideoElement(source){const element=this._decodeFromVideoElementSetup(source);return this._decodeOnLoadVideo(element);}
decodeFromVideoElementContinuously(source,callbackFn){const element=this._decodeFromVideoElementSetup(source);return this._decodeOnLoadVideoContinuously(element,callbackFn);}
_decodeFromVideoElementSetup(source){if(!source){throw new ArgumentException('A video element must be provided.');}
this.reset();const element=this.prepareVideoElement(source);this.videoElement=element;return element;}
decodeFromImageUrl(url){if(!url){throw new ArgumentException('An URL must be provided.');}
this.reset();const element=this.prepareImageElement();this.imageElement=element;const decodeTask=this._decodeOnLoadImage(element);element.src=url;return decodeTask;}
decodeFromVideoUrl(url){if(!url){throw new ArgumentException('An URL must be provided.');}
this.reset();const element=this.prepareVideoElement();const decodeTask=this.decodeFromVideoElement(element);element.src=url;return decodeTask;}
decodeFromVideoUrlContinuously(url,callbackFn){if(!url){throw new ArgumentException('An URL must be provided.');}
this.reset();const element=this.prepareVideoElement();const decodeTask=this.decodeFromVideoElementContinuously(element,callbackFn);element.src=url;return decodeTask;}
_decodeOnLoadImage(element){return new Promise((resolve,reject)=>{this.imageLoadedListener=()=>this.decodeOnce(element,false,true).then(resolve,reject);element.addEventListener('load',this.imageLoadedListener);});}
_decodeOnLoadVideo(videoElement){return __awaiter(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(videoElement);return yield this.decodeOnce(videoElement);});}
_decodeOnLoadVideoContinuously(videoElement,callbackFn){return __awaiter(this,void 0,void 0,function*(){yield this.playVideoOnLoadAsync(videoElement);this.decodeContinuously(videoElement,callbackFn);});}
isImageLoaded(img){if(!img.complete){return false;}
if(img.naturalWidth===0){return false;}
return true;}
prepareImageElement(imageSource){let imageElement;if(typeof imageSource==='undefined'){imageElement=document.createElement('img');imageElement.width=200;imageElement.height=200;}
if(typeof imageSource==='string'){imageElement=this.getMediaElement(imageSource,'img');}
if(imageSource instanceof HTMLImageElement){imageElement=imageSource;}
return imageElement;}
prepareVideoElement(videoSource){let videoElement;if(!videoSource&&typeof document!=='undefined'){videoElement=document.createElement('video');videoElement.width=200;videoElement.height=200;}
if(typeof videoSource==='string'){videoElement=(this.getMediaElement(videoSource,'video'));}
if(videoSource instanceof HTMLVideoElement){videoElement=videoSource;}
videoElement.setAttribute('autoplay','true');videoElement.setAttribute('muted','true');videoElement.setAttribute('playsinline','true');return videoElement;}
decodeOnce(element,retryIfNotFound=true,retryIfChecksumOrFormatError=true){this._stopAsyncDecode=false;const loop=(resolve,reject)=>{if(this._stopAsyncDecode){reject(new NotFoundException('Video stream has ended before any code could be detected.'));this._stopAsyncDecode=undefined;return;}
try{const result=this.decode(element);resolve(result);}
catch(e){const ifNotFound=retryIfNotFound&&e instanceof NotFoundException;const isChecksumOrFormatError=e instanceof ChecksumException||e instanceof FormatException;const ifChecksumOrFormat=isChecksumOrFormatError&&retryIfChecksumOrFormatError;if(ifNotFound||ifChecksumOrFormat){return setTimeout(loop,this._timeBetweenDecodingAttempts,resolve,reject);}
reject(e);}};return new Promise((resolve,reject)=>loop(resolve,reject));}
decodeContinuously(element,callbackFn){this._stopContinuousDecode=false;const loop=()=>{if(this._stopContinuousDecode){this._stopContinuousDecode=undefined;return;}
try{const result=this.decode(element);callbackFn(result,null);setTimeout(loop,this.timeBetweenScansMillis);}
catch(e){callbackFn(null,e);const isChecksumOrFormatError=e instanceof ChecksumException||e instanceof FormatException;const isNotFound=e instanceof NotFoundException;if(isChecksumOrFormatError||isNotFound){setTimeout(loop,this._timeBetweenDecodingAttempts);}}};loop();}
decode(element){const binaryBitmap=this.createBinaryBitmap(element);return this.decodeBitmap(binaryBitmap);}
createBinaryBitmap(mediaElement){const ctx=this.getCaptureCanvasContext(mediaElement);if(mediaElement instanceof HTMLVideoElement){this.drawFrameOnCanvas(mediaElement);}
else{this.drawImageOnCanvas(mediaElement);}
const canvas=this.getCaptureCanvas(mediaElement);const luminanceSource=new HTMLCanvasElementLuminanceSource(canvas);const hybridBinarizer=new HybridBinarizer(luminanceSource);return new BinaryBitmap(hybridBinarizer);}
getCaptureCanvasContext(mediaElement){if(!this.captureCanvasContext){const elem=this.getCaptureCanvas(mediaElement);let ctx;try{ctx=elem.getContext('2d',{willReadFrequently:true});}
catch(e){ctx=elem.getContext('2d');}
this.captureCanvasContext=ctx;}
return this.captureCanvasContext;}
getCaptureCanvas(mediaElement){if(!this.captureCanvas){const elem=this.createCaptureCanvas(mediaElement);this.captureCanvas=elem;}
return this.captureCanvas;}
drawFrameOnCanvas(srcElement,dimensions={sx:0,sy:0,sWidth:srcElement.videoWidth,sHeight:srcElement.videoHeight,dx:0,dy:0,dWidth:srcElement.videoWidth,dHeight:srcElement.videoHeight,},canvasElementContext=this.captureCanvasContext){canvasElementContext.drawImage(srcElement,dimensions.sx,dimensions.sy,dimensions.sWidth,dimensions.sHeight,dimensions.dx,dimensions.dy,dimensions.dWidth,dimensions.dHeight);}
drawImageOnCanvas(srcElement,dimensions={sx:0,sy:0,sWidth:srcElement.naturalWidth,sHeight:srcElement.naturalHeight,dx:0,dy:0,dWidth:srcElement.naturalWidth,dHeight:srcElement.naturalHeight,},canvasElementContext=this.captureCanvasContext){canvasElementContext.drawImage(srcElement,dimensions.sx,dimensions.sy,dimensions.sWidth,dimensions.sHeight,dimensions.dx,dimensions.dy,dimensions.dWidth,dimensions.dHeight);}
decodeBitmap(binaryBitmap){return this.reader.decode(binaryBitmap,this._hints);}
createCaptureCanvas(mediaElement){if(typeof document==='undefined'){this._destroyCaptureCanvas();return null;}
const canvasElement=document.createElement('canvas');let width;let height;if(typeof mediaElement!=='undefined'){if(mediaElement instanceof HTMLVideoElement){width=mediaElement.videoWidth;height=mediaElement.videoHeight;}
else if(mediaElement instanceof HTMLImageElement){width=mediaElement.naturalWidth||mediaElement.width;height=mediaElement.naturalHeight||mediaElement.height;}}
canvasElement.style.width=width+'px';canvasElement.style.height=height+'px';canvasElement.width=width;canvasElement.height=height;return canvasElement;}
stopStreams(){if(this.stream){this.stream.getVideoTracks().forEach(t=>t.stop());this.stream=undefined;}
if(this._stopAsyncDecode===false){this.stopAsyncDecode();}
if(this._stopContinuousDecode===false){this.stopContinuousDecode();}}
reset(){this.stopStreams();this._destroyVideoElement();this._destroyImageElement();this._destroyCaptureCanvas();}
_destroyVideoElement(){if(!this.videoElement){return;}
if(typeof this.videoEndedListener!=='undefined'){this.videoElement.removeEventListener('ended',this.videoEndedListener);}
if(typeof this.videoPlayingEventListener!=='undefined'){this.videoElement.removeEventListener('playing',this.videoPlayingEventListener);}
if(typeof this.videoCanPlayListener!=='undefined'){this.videoElement.removeEventListener('loadedmetadata',this.videoCanPlayListener);}
this.cleanVideoSource(this.videoElement);this.videoElement=undefined;}
_destroyImageElement(){if(!this.imageElement){return;}
if(undefined!==this.imageLoadedListener){this.imageElement.removeEventListener('load',this.imageLoadedListener);}
this.imageElement.src=undefined;this.imageElement.removeAttribute('src');this.imageElement=undefined;}
_destroyCaptureCanvas(){this.captureCanvasContext=undefined;this.captureCanvas=undefined;}
addVideoSource(videoElement,stream){try{videoElement.srcObject=stream;}
catch(err){videoElement.src=URL.createObjectURL(stream);}}
cleanVideoSource(videoElement){try{videoElement.srcObject=null;}
catch(err){videoElement.src='';}
this.videoElement.removeAttribute('src');}}
class Result{constructor(text,rawBytes,numBits=rawBytes==null?0:8*rawBytes.length,resultPoints,format,timestamp=System.currentTimeMillis()){this.text=text;this.rawBytes=rawBytes;this.numBits=numBits;this.resultPoints=resultPoints;this.format=format;this.timestamp=timestamp;this.text=text;this.rawBytes=rawBytes;if(undefined===numBits||null===numBits){this.numBits=(rawBytes===null||rawBytes===undefined)?0:8*rawBytes.length;}
else{this.numBits=numBits;}
this.resultPoints=resultPoints;this.format=format;this.resultMetadata=null;if(undefined===timestamp||null===timestamp){this.timestamp=System.currentTimeMillis();}
else{this.timestamp=timestamp;}}
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(type,value){if(this.resultMetadata===null){this.resultMetadata=new Map();}
this.resultMetadata.set(type,value);}
putAllMetadata(metadata){if(metadata!==null){if(this.resultMetadata===null){this.resultMetadata=metadata;}
else{this.resultMetadata=new Map(metadata);}}}
addResultPoints(newPoints){const oldPoints=this.resultPoints;if(oldPoints===null){this.resultPoints=newPoints;}
else if(newPoints!==null&&newPoints.length>0){const allPoints=new Array(oldPoints.length+newPoints.length);System.arraycopy(oldPoints,0,allPoints,0,oldPoints.length);System.arraycopy(newPoints,0,allPoints,oldPoints.length,newPoints.length);this.resultPoints=allPoints;}}
getTimestamp(){return this.timestamp;}
toString(){return this.text;}}
var BarcodeFormat;(function(BarcodeFormat){BarcodeFormat[BarcodeFormat["AZTEC"]=0]="AZTEC";BarcodeFormat[BarcodeFormat["CODABAR"]=1]="CODABAR";BarcodeFormat[BarcodeFormat["CODE_39"]=2]="CODE_39";BarcodeFormat[BarcodeFormat["CODE_93"]=3]="CODE_93";BarcodeFormat[BarcodeFormat["CODE_128"]=4]="CODE_128";BarcodeFormat[BarcodeFormat["DATA_MATRIX"]=5]="DATA_MATRIX";BarcodeFormat[BarcodeFormat["EAN_8"]=6]="EAN_8";BarcodeFormat[BarcodeFormat["EAN_13"]=7]="EAN_13";BarcodeFormat[BarcodeFormat["ITF"]=8]="ITF";BarcodeFormat[BarcodeFormat["MAXICODE"]=9]="MAXICODE";BarcodeFormat[BarcodeFormat["PDF_417"]=10]="PDF_417";BarcodeFormat[BarcodeFormat["QR_CODE"]=11]="QR_CODE";BarcodeFormat[BarcodeFormat["RSS_14"]=12]="RSS_14";BarcodeFormat[BarcodeFormat["RSS_EXPANDED"]=13]="RSS_EXPANDED";BarcodeFormat[BarcodeFormat["UPC_A"]=14]="UPC_A";BarcodeFormat[BarcodeFormat["UPC_E"]=15]="UPC_E";BarcodeFormat[BarcodeFormat["UPC_EAN_EXTENSION"]=16]="UPC_EAN_EXTENSION";})(BarcodeFormat||(BarcodeFormat={}));var BarcodeFormat$1=BarcodeFormat;var ResultMetadataType;(function(ResultMetadataType){ResultMetadataType[ResultMetadataType["OTHER"]=0]="OTHER";ResultMetadataType[ResultMetadataType["ORIENTATION"]=1]="ORIENTATION";ResultMetadataType[ResultMetadataType["BYTE_SEGMENTS"]=2]="BYTE_SEGMENTS";ResultMetadataType[ResultMetadataType["ERROR_CORRECTION_LEVEL"]=3]="ERROR_CORRECTION_LEVEL";ResultMetadataType[ResultMetadataType["ISSUE_NUMBER"]=4]="ISSUE_NUMBER";ResultMetadataType[ResultMetadataType["SUGGESTED_PRICE"]=5]="SUGGESTED_PRICE";ResultMetadataType[ResultMetadataType["POSSIBLE_COUNTRY"]=6]="POSSIBLE_COUNTRY";ResultMetadataType[ResultMetadataType["UPC_EAN_EXTENSION"]=7]="UPC_EAN_EXTENSION";ResultMetadataType[ResultMetadataType["PDF417_EXTRA_METADATA"]=8]="PDF417_EXTRA_METADATA";ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_SEQUENCE"]=9]="STRUCTURED_APPEND_SEQUENCE";ResultMetadataType[ResultMetadataType["STRUCTURED_APPEND_PARITY"]=10]="STRUCTURED_APPEND_PARITY";})(ResultMetadataType||(ResultMetadataType={}));var ResultMetadataType$1=ResultMetadataType;class DecoderResult{constructor(rawBytes,text,byteSegments,ecLevel,structuredAppendSequenceNumber=-1,structuredAppendParity=-1){this.rawBytes=rawBytes;this.text=text;this.byteSegments=byteSegments;this.ecLevel=ecLevel;this.structuredAppendSequenceNumber=structuredAppendSequenceNumber;this.structuredAppendParity=structuredAppendParity;this.numBits=(rawBytes===undefined||rawBytes===null)?0:8*rawBytes.length;}
getRawBytes(){return this.rawBytes;}
getNumBits(){return this.numBits;}
setNumBits(numBits){this.numBits=numBits;}
getText(){return this.text;}
getByteSegments(){return this.byteSegments;}
getECLevel(){return this.ecLevel;}
getErrorsCorrected(){return this.errorsCorrected;}
setErrorsCorrected(errorsCorrected){this.errorsCorrected=errorsCorrected;}
getErasures(){return this.erasures;}
setErasures(erasures){this.erasures=erasures;}
getOther(){return this.other;}
setOther(other){this.other=other;}
hasStructuredAppend(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0;}
getStructuredAppendParity(){return this.structuredAppendParity;}
getStructuredAppendSequenceNumber(){return this.structuredAppendSequenceNumber;}}
class AbstractGenericGF{exp(a){return this.expTable[a];}
log(a){if(a===0){throw new IllegalArgumentException();}
return this.logTable[a];}
static addOrSubtract(a,b){return a^b;}}
class GenericGFPoly{constructor(field,coefficients){if(coefficients.length===0){throw new IllegalArgumentException();}
this.field=field;const coefficientsLength=coefficients.length;if(coefficientsLength>1&&coefficients[0]===0){let firstNonZero=1;while(firstNonZero<coefficientsLength&&coefficients[firstNonZero]===0){firstNonZero++;}
if(firstNonZero===coefficientsLength){this.coefficients=Int32Array.from([0]);}
else{this.coefficients=new Int32Array(coefficientsLength-firstNonZero);System.arraycopy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.length);}}
else{this.coefficients=coefficients;}}
getCoefficients(){return this.coefficients;}
getDegree(){return this.coefficients.length-1;}
isZero(){return this.coefficients[0]===0;}
getCoefficient(degree){return this.coefficients[this.coefficients.length-1-degree];}
evaluateAt(a){if(a===0){return this.getCoefficient(0);}
const coefficients=this.coefficients;let result;if(a===1){result=0;for(let i=0,length=coefficients.length;i!==length;i++){const coefficient=coefficients[i];result=AbstractGenericGF.addOrSubtract(result,coefficient);}
return result;}
result=coefficients[0];const size=coefficients.length;const field=this.field;for(let i=1;i<size;i++){result=AbstractGenericGF.addOrSubtract(field.multiply(a,result),coefficients[i]);}
return result;}
addOrSubtract(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}
if(this.isZero()){return other;}
if(other.isZero()){return this;}
let smallerCoefficients=this.coefficients;let largerCoefficients=other.coefficients;if(smallerCoefficients.length>largerCoefficients.length){const temp=smallerCoefficients;smallerCoefficients=largerCoefficients;largerCoefficients=temp;}
let sumDiff=new Int32Array(largerCoefficients.length);const lengthDiff=largerCoefficients.length-smallerCoefficients.length;System.arraycopy(largerCoefficients,0,sumDiff,0,lengthDiff);for(let i=lengthDiff;i<largerCoefficients.length;i++){sumDiff[i]=AbstractGenericGF.addOrSubtract(smallerCoefficients[i-lengthDiff],largerCoefficients[i]);}
return new GenericGFPoly(this.field,sumDiff);}
multiply(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}
if(this.isZero()||other.isZero()){return this.field.getZero();}
const aCoefficients=this.coefficients;const aLength=aCoefficients.length;const bCoefficients=other.coefficients;const bLength=bCoefficients.length;const product=new Int32Array(aLength+bLength-1);const field=this.field;for(let i=0;i<aLength;i++){const aCoeff=aCoefficients[i];for(let j=0;j<bLength;j++){product[i+j]=AbstractGenericGF.addOrSubtract(product[i+j],field.multiply(aCoeff,bCoefficients[j]));}}
return new GenericGFPoly(field,product);}
multiplyScalar(scalar){if(scalar===0){return this.field.getZero();}
if(scalar===1){return this;}
const size=this.coefficients.length;const field=this.field;const product=new Int32Array(size);const coefficients=this.coefficients;for(let i=0;i<size;i++){product[i]=field.multiply(coefficients[i],scalar);}
return new GenericGFPoly(field,product);}
multiplyByMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}
if(coefficient===0){return this.field.getZero();}
const coefficients=this.coefficients;const size=coefficients.length;const product=new Int32Array(size+degree);const field=this.field;for(let i=0;i<size;i++){product[i]=field.multiply(coefficients[i],coefficient);}
return new GenericGFPoly(field,product);}
divide(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');}
if(other.isZero()){throw new IllegalArgumentException('Divide by 0');}
const field=this.field;let quotient=field.getZero();let remainder=this;const denominatorLeadingTerm=other.getCoefficient(other.getDegree());const inverseDenominatorLeadingTerm=field.inverse(denominatorLeadingTerm);while(remainder.getDegree()>=other.getDegree()&&!remainder.isZero()){const degreeDifference=remainder.getDegree()-other.getDegree();const scale=field.multiply(remainder.getCoefficient(remainder.getDegree()),inverseDenominatorLeadingTerm);const term=other.multiplyByMonomial(degreeDifference,scale);const iterationQuotient=field.buildMonomial(degreeDifference,scale);quotient=quotient.addOrSubtract(iterationQuotient);remainder=remainder.addOrSubtract(term);}
return[quotient,remainder];}
toString(){let result='';for(let degree=this.getDegree();degree>=0;degree--){let coefficient=this.getCoefficient(degree);if(coefficient!==0){if(coefficient<0){result+=' - ';coefficient=-coefficient;}
else{if(result.length>0){result+=' + ';}}
if(degree===0||coefficient!==1){const alphaPower=this.field.log(coefficient);if(alphaPower===0){result+='1';}
else if(alphaPower===1){result+='a';}
else{result+='a^';result+=alphaPower;}}
if(degree!==0){if(degree===1){result+='x';}
else{result+='x^';result+=degree;}}}}
return result;}}
class ArithmeticException extends Exception{}
ArithmeticException.kind='ArithmeticException';class GenericGF extends AbstractGenericGF{constructor(primitive,size,generatorBase){super();this.primitive=primitive;this.size=size;this.generatorBase=generatorBase;const expTable=new Int32Array(size);let x=1;for(let i=0;i<size;i++){expTable[i]=x;x*=2;if(x>=size){x^=primitive;x&=size-1;}}
this.expTable=expTable;const logTable=new Int32Array(size);for(let i=0;i<size-1;i++){logTable[expTable[i]]=i;}
this.logTable=logTable;this.zero=new GenericGFPoly(this,Int32Array.from([0]));this.one=new GenericGFPoly(this,Int32Array.from([1]));}
getZero(){return this.zero;}
getOne(){return this.one;}
buildMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}
if(coefficient===0){return this.zero;}
const coefficients=new Int32Array(degree+1);coefficients[0]=coefficient;return new GenericGFPoly(this,coefficients);}
inverse(a){if(a===0){throw new ArithmeticException();}
return this.expTable[this.size-this.logTable[a]-1];}
multiply(a,b){if(a===0||b===0){return 0;}
return this.expTable[(this.logTable[a]+this.logTable[b])%(this.size-1)];}
getSize(){return this.size;}
getGeneratorBase(){return this.generatorBase;}
toString(){return('GF(0x'+Integer.toHexString(this.primitive)+','+this.size+')');}
equals(o){return o===this;}}
GenericGF.AZTEC_DATA_12=new GenericGF(0x1069,4096,1);GenericGF.AZTEC_DATA_10=new GenericGF(0x409,1024,1);GenericGF.AZTEC_DATA_6=new GenericGF(0x43,64,1);GenericGF.AZTEC_PARAM=new GenericGF(0x13,16,1);GenericGF.QR_CODE_FIELD_256=new GenericGF(0x011d,256,0);GenericGF.DATA_MATRIX_FIELD_256=new GenericGF(0x012d,256,1);GenericGF.AZTEC_DATA_8=GenericGF.DATA_MATRIX_FIELD_256;GenericGF.MAXICODE_FIELD_64=GenericGF.AZTEC_DATA_6;class ReedSolomonException extends Exception{}
ReedSolomonException.kind='ReedSolomonException';class IllegalStateException extends Exception{}
IllegalStateException.kind='IllegalStateException';class ReedSolomonDecoder{constructor(field){this.field=field;}
decode(received,twoS){const field=this.field;const poly=new GenericGFPoly(field,received);const syndromeCoefficients=new Int32Array(twoS);let noError=true;for(let i=0;i<twoS;i++){const evalResult=poly.evaluateAt(field.exp(i+field.getGeneratorBase()));syndromeCoefficients[syndromeCoefficients.length-1-i]=evalResult;if(evalResult!==0){noError=false;}}
if(noError){return;}
const syndrome=new GenericGFPoly(field,syndromeCoefficients);const sigmaOmega=this.runEuclideanAlgorithm(field.buildMonomial(twoS,1),syndrome,twoS);const sigma=sigmaOmega[0];const omega=sigmaOmega[1];const errorLocations=this.findErrorLocations(sigma);const errorMagnitudes=this.findErrorMagnitudes(omega,errorLocations);for(let i=0;i<errorLocations.length;i++){const position=received.length-1-field.log(errorLocations[i]);if(position<0){throw new ReedSolomonException('Bad error location');}
received[position]=GenericGF.addOrSubtract(received[position],errorMagnitudes[i]);}}
runEuclideanAlgorithm(a,b,R){if(a.getDegree()<b.getDegree()){const temp=a;a=b;b=temp;}
const field=this.field;let rLast=a;let r=b;let tLast=field.getZero();let t=field.getOne();while(r.getDegree()>=(R/2|0)){let rLastLast=rLast;let tLastLast=tLast;rLast=r;tLast=t;if(rLast.isZero()){throw new ReedSolomonException('r_{i-1} was zero');}
r=rLastLast;let q=field.getZero();const denominatorLeadingTerm=rLast.getCoefficient(rLast.getDegree());const dltInverse=field.inverse(denominatorLeadingTerm);while(r.getDegree()>=rLast.getDegree()&&!r.isZero()){const degreeDiff=r.getDegree()-rLast.getDegree();const scale=field.multiply(r.getCoefficient(r.getDegree()),dltInverse);q=q.addOrSubtract(field.buildMonomial(degreeDiff,scale));r=r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff,scale));}
t=q.multiply(tLast).addOrSubtract(tLastLast);if(r.getDegree()>=rLast.getDegree()){throw new IllegalStateException('Division algorithm failed to reduce polynomial?');}}
const sigmaTildeAtZero=t.getCoefficient(0);if(sigmaTildeAtZero===0){throw new ReedSolomonException('sigmaTilde(0) was zero');}
const inverse=field.inverse(sigmaTildeAtZero);const sigma=t.multiplyScalar(inverse);const omega=r.multiplyScalar(inverse);return[sigma,omega];}
findErrorLocations(errorLocator){const numErrors=errorLocator.getDegree();if(numErrors===1){return Int32Array.from([errorLocator.getCoefficient(1)]);}
const result=new Int32Array(numErrors);let e=0;const field=this.field;for(let i=1;i<field.getSize()&&e<numErrors;i++){if(errorLocator.evaluateAt(i)===0){result[e]=field.inverse(i);e++;}}
if(e!==numErrors){throw new ReedSolomonException('Error locator degree does not match number of roots');}
return result;}
findErrorMagnitudes(errorEvaluator,errorLocations){const s=errorLocations.length;const result=new Int32Array(s);const field=this.field;for(let i=0;i<s;i++){const xiInverse=field.inverse(errorLocations[i]);let denominator=1;for(let j=0;j<s;j++){if(i!==j){const term=field.multiply(errorLocations[j],xiInverse);const termPlus1=(term&0x1)===0?term|1:term&~1;denominator=field.multiply(denominator,termPlus1);}}
result[i]=field.multiply(errorEvaluator.evaluateAt(xiInverse),field.inverse(denominator));if(field.getGeneratorBase()!==0){result[i]=field.multiply(result[i],xiInverse);}}
return result;}}
var Table;(function(Table){Table[Table["UPPER"]=0]="UPPER";Table[Table["LOWER"]=1]="LOWER";Table[Table["MIXED"]=2]="MIXED";Table[Table["DIGIT"]=3]="DIGIT";Table[Table["PUNCT"]=4]="PUNCT";Table[Table["BINARY"]=5]="BINARY";})(Table||(Table={}));class Decoder{decode(detectorResult){this.ddata=detectorResult;let matrix=detectorResult.getBits();let rawbits=this.extractBits(matrix);let correctedBits=this.correctBits(rawbits);let rawBytes=Decoder.convertBoolArrayToByteArray(correctedBits);let result=Decoder.getEncodedData(correctedBits);let decoderResult=new DecoderResult(rawBytes,result,null,null);decoderResult.setNumBits(correctedBits.length);return decoderResult;}
static highLevelDecode(correctedBits){return this.getEncodedData(correctedBits);}
static getEncodedData(correctedBits){let endIndex=correctedBits.length;let latchTable=Table.UPPER;let shiftTable=Table.UPPER;let result='';let index=0;while(index<endIndex){if(shiftTable===Table.BINARY){if(endIndex-index<5){break;}
let length=Decoder.readCode(correctedBits,index,5);index+=5;if(length===0){if(endIndex-index<11){break;}
length=Decoder.readCode(correctedBits,index,11)+31;index+=11;}
for(let charCount=0;charCount<length;charCount++){if(endIndex-index<8){index=endIndex;break;}
const code=Decoder.readCode(correctedBits,index,8);result+=StringUtils.castAsNonUtf8Char(code);index+=8;}
shiftTable=latchTable;}
else{let size=shiftTable===Table.DIGIT?4:5;if(endIndex-index<size){break;}
let code=Decoder.readCode(correctedBits,index,size);index+=size;let str=Decoder.getCharacter(shiftTable,code);if(str.startsWith('CTRL_')){latchTable=shiftTable;shiftTable=Decoder.getTable(str.charAt(5));if(str.charAt(6)==='L'){latchTable=shiftTable;}}
else{result+=str;shiftTable=latchTable;}}}
return result;}
static getTable(t){switch(t){case'L':return Table.LOWER;case'P':return Table.PUNCT;case'M':return Table.MIXED;case'D':return Table.DIGIT;case'B':return Table.BINARY;case'U':default:return Table.UPPER;}}
static getCharacter(table,code){switch(table){case Table.UPPER:return Decoder.UPPER_TABLE[code];case Table.LOWER:return Decoder.LOWER_TABLE[code];case Table.MIXED:return Decoder.MIXED_TABLE[code];case Table.PUNCT:return Decoder.PUNCT_TABLE[code];case Table.DIGIT:return Decoder.DIGIT_TABLE[code];default:throw new IllegalStateException('Bad table');}}
correctBits(rawbits){let gf;let codewordSize;if(this.ddata.getNbLayers()<=2){codewordSize=6;gf=GenericGF.AZTEC_DATA_6;}
else if(this.ddata.getNbLayers()<=8){codewordSize=8;gf=GenericGF.AZTEC_DATA_8;}
else if(this.ddata.getNbLayers()<=22){codewordSize=10;gf=GenericGF.AZTEC_DATA_10;}
else{codewordSize=12;gf=GenericGF.AZTEC_DATA_12;}
let numDataCodewords=this.ddata.getNbDatablocks();let numCodewords=rawbits.length/codewordSize;if(numCodewords<numDataCodewords){throw new FormatException();}
let offset=rawbits.length%codewordSize;let dataWords=new Int32Array(numCodewords);for(let i=0;i<numCodewords;i++,offset+=codewordSize){dataWords[i]=Decoder.readCode(rawbits,offset,codewordSize);}
try{let rsDecoder=new ReedSolomonDecoder(gf);rsDecoder.decode(dataWords,numCodewords-numDataCodewords);}
catch(ex){throw new FormatException(ex);}
let mask=(1<<codewordSize)-1;let stuffedBits=0;for(let i=0;i<numDataCodewords;i++){let dataWord=dataWords[i];if(dataWord===0||dataWord===mask){throw new FormatException();}
else if(dataWord===1||dataWord===mask-1){stuffedBits++;}}
let correctedBits=new Array(numDataCodewords*codewordSize-stuffedBits);let index=0;for(let i=0;i<numDataCodewords;i++){let dataWord=dataWords[i];if(dataWord===1||dataWord===mask-1){correctedBits.fill(dataWord>1,index,index+codewordSize-1);index+=codewordSize-1;}
else{for(let bit=codewordSize-1;bit>=0;--bit){correctedBits[index++]=(dataWord&(1<<bit))!==0;}}}
return correctedBits;}
extractBits(matrix){let compact=this.ddata.isCompact();let layers=this.ddata.getNbLayers();let baseMatrixSize=(compact?11:14)+layers*4;let alignmentMap=new Int32Array(baseMatrixSize);let rawbits=new Array(this.totalBitsInLayer(layers,compact));if(compact){for(let i=0;i<alignmentMap.length;i++){alignmentMap[i]=i;}}
else{let matrixSize=baseMatrixSize+1+2*Integer.truncDivision((Integer.truncDivision(baseMatrixSize,2)-1),15);let origCenter=baseMatrixSize/2;let center=Integer.truncDivision(matrixSize,2);for(let i=0;i<origCenter;i++){let newOffset=i+Integer.truncDivision(i,15);alignmentMap[origCenter-i-1]=center-newOffset-1;alignmentMap[origCenter+i]=center+newOffset+1;}}
for(let i=0,rowOffset=0;i<layers;i++){let rowSize=(layers-i)*4+(compact?9:12);let low=i*2;let high=baseMatrixSize-1-low;for(let j=0;j<rowSize;j++){let columnOffset=j*2;for(let k=0;k<2;k++){rawbits[rowOffset+columnOffset+k]=matrix.get(alignmentMap[low+k],alignmentMap[low+j]);rawbits[rowOffset+2*rowSize+columnOffset+k]=matrix.get(alignmentMap[low+j],alignmentMap[high-k]);rawbits[rowOffset+4*rowSize+columnOffset+k]=matrix.get(alignmentMap[high-k],alignmentMap[high-j]);rawbits[rowOffset+6*rowSize+columnOffset+k]=matrix.get(alignmentMap[high-j],alignmentMap[low+k]);}}
rowOffset+=rowSize*8;}
return rawbits;}
static readCode(rawbits,startIndex,length){let res=0;for(let i=startIndex;i<startIndex+length;i++){res<<=1;if(rawbits[i]){res|=0x01;}}
return res;}
static readByte(rawbits,startIndex){let n=rawbits.length-startIndex;if(n>=8){return Decoder.readCode(rawbits,startIndex,8);}
return Decoder.readCode(rawbits,startIndex,n)<<(8-n);}
static convertBoolArrayToByteArray(boolArr){let byteArr=new Uint8Array((boolArr.length+7)/8);for(let i=0;i<byteArr.length;i++){byteArr[i]=Decoder.readByte(boolArr,8*i);}
return byteArr;}
totalBitsInLayer(layers,compact){return((compact?88:112)+16*layers)*layers;}}
Decoder.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'];Decoder.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'];Decoder.MIXED_TABLE=['CTRL_PS',' ','\\1','\\2','\\3','\\4','\\5','\\6','\\7','\b','\t','\n','\\13','\f','\r','\\33','\\34','\\35','\\36','\\37','@','\\','^','_','`','|','~','\\177','CTRL_LL','CTRL_UL','CTRL_PL','CTRL_BS'];Decoder.PUNCT_TABLE=['','\r','\r\n','. ',', ',': ','!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','[',']','{','}','CTRL_UL'];Decoder.DIGIT_TABLE=['CTRL_PS',' ','0','1','2','3','4','5','6','7','8','9',',','.','CTRL_UL','CTRL_US'];class MathUtils{constructor(){}
static round(d){if(isNaN(d))
return 0;if(d<=Number.MIN_SAFE_INTEGER)
return Number.MIN_SAFE_INTEGER;if(d>=Number.MAX_SAFE_INTEGER)
return Number.MAX_SAFE_INTEGER;return(d+(d<0.0?-0.5:0.5))|0;}
static distance(aX,aY,bX,bY){const xDiff=aX-bX;const yDiff=aY-bY;return Math.sqrt(xDiff*xDiff+yDiff*yDiff);}
static sum(array){let count=0;for(let i=0,length=array.length;i!==length;i++){const a=array[i];count+=a;}
return count;}}
class Float{static floatToIntBits(f){return f;}}
Float.MAX_VALUE=Number.MAX_SAFE_INTEGER;class ResultPoint{constructor(x,y){this.x=x;this.y=y;}
getX(){return this.x;}
getY(){return this.y;}
equals(other){if(other instanceof ResultPoint){const otherPoint=other;return this.x===otherPoint.x&&this.y===otherPoint.y;}
return false;}
hashCode(){return 31*Float.floatToIntBits(this.x)+Float.floatToIntBits(this.y);}
toString(){return'('+this.x+','+this.y+')';}
static orderBestPatterns(patterns){const zeroOneDistance=this.distance(patterns[0],patterns[1]);const oneTwoDistance=this.distance(patterns[1],patterns[2]);const zeroTwoDistance=this.distance(patterns[0],patterns[2]);let pointA;let pointB;let pointC;if(oneTwoDistance>=zeroOneDistance&&oneTwoDistance>=zeroTwoDistance){pointB=patterns[0];pointA=patterns[1];pointC=patterns[2];}
else if(zeroTwoDistance>=oneTwoDistance&&zeroTwoDistance>=zeroOneDistance){pointB=patterns[1];pointA=patterns[0];pointC=patterns[2];}
else{pointB=patterns[2];pointA=patterns[0];pointC=patterns[1];}
if(this.crossProductZ(pointA,pointB,pointC)<0.0){const temp=pointA;pointA=pointC;pointC=temp;}
patterns[0]=pointA;patterns[1]=pointB;patterns[2]=pointC;}
static distance(pattern1,pattern2){return MathUtils.distance(pattern1.x,pattern1.y,pattern2.x,pattern2.y);}
static crossProductZ(pointA,pointB,pointC){const bX=pointB.x;const bY=pointB.y;return((pointC.x-bX)*(pointA.y-bY))-((pointC.y-bY)*(pointA.x-bX));}}
class DetectorResult{constructor(bits,points){this.bits=bits;this.points=points;}
getBits(){return this.bits;}
getPoints(){return this.points;}}
class AztecDetectorResult extends DetectorResult{constructor(bits,points,compact,nbDatablocks,nbLayers){super(bits,points);this.compact=compact;this.nbDatablocks=nbDatablocks;this.nbLayers=nbLayers;}
getNbLayers(){return this.nbLayers;}
getNbDatablocks(){return this.nbDatablocks;}
isCompact(){return this.compact;}}
class WhiteRectangleDetector{constructor(image,initSize,x,y){this.image=image;this.height=image.getHeight();this.width=image.getWidth();if(undefined===initSize||null===initSize){initSize=WhiteRectangleDetector.INIT_SIZE;}
if(undefined===x||null===x){x=image.getWidth()/2|0;}
if(undefined===y||null===y){y=image.getHeight()/2|0;}
const halfsize=initSize/2|0;this.leftInit=x-halfsize;this.rightInit=x+halfsize;this.upInit=y-halfsize;this.downInit=y+halfsize;if(this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width){throw new NotFoundException();}}
detect(){let left=this.leftInit;let right=this.rightInit;let up=this.upInit;let down=this.downInit;let sizeExceeded=false;let aBlackPointFoundOnBorder=true;let atLeastOneBlackPointFoundOnBorder=false;let atLeastOneBlackPointFoundOnRight=false;let atLeastOneBlackPointFoundOnBottom=false;let atLeastOneBlackPointFoundOnLeft=false;let atLeastOneBlackPointFoundOnTop=false;const width=this.width;const height=this.height;while(aBlackPointFoundOnBorder){aBlackPointFoundOnBorder=false;let rightBorderNotWhite=true;while((rightBorderNotWhite||!atLeastOneBlackPointFoundOnRight)&&right<width){rightBorderNotWhite=this.containsBlackPoint(up,down,right,false);if(rightBorderNotWhite){right++;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnRight=true;}
else if(!atLeastOneBlackPointFoundOnRight){right++;}}
if(right>=width){sizeExceeded=true;break;}
let bottomBorderNotWhite=true;while((bottomBorderNotWhite||!atLeastOneBlackPointFoundOnBottom)&&down<height){bottomBorderNotWhite=this.containsBlackPoint(left,right,down,true);if(bottomBorderNotWhite){down++;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnBottom=true;}
else if(!atLeastOneBlackPointFoundOnBottom){down++;}}
if(down>=height){sizeExceeded=true;break;}
let leftBorderNotWhite=true;while((leftBorderNotWhite||!atLeastOneBlackPointFoundOnLeft)&&left>=0){leftBorderNotWhite=this.containsBlackPoint(up,down,left,false);if(leftBorderNotWhite){left--;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnLeft=true;}
else if(!atLeastOneBlackPointFoundOnLeft){left--;}}
if(left<0){sizeExceeded=true;break;}
let topBorderNotWhite=true;while((topBorderNotWhite||!atLeastOneBlackPointFoundOnTop)&&up>=0){topBorderNotWhite=this.containsBlackPoint(left,right,up,true);if(topBorderNotWhite){up--;aBlackPointFoundOnBorder=true;atLeastOneBlackPointFoundOnTop=true;}
else if(!atLeastOneBlackPointFoundOnTop){up--;}}
if(up<0){sizeExceeded=true;break;}
if(aBlackPointFoundOnBorder){atLeastOneBlackPointFoundOnBorder=true;}}
if(!sizeExceeded&&atLeastOneBlackPointFoundOnBorder){const maxSize=right-left;let z=null;for(let i=1;z===null&&i<maxSize;i++){z=this.getBlackPointOnSegment(left,down-i,left+i,down);}
if(z==null){throw new NotFoundException();}
let t=null;for(let i=1;t===null&&i<maxSize;i++){t=this.getBlackPointOnSegment(left,up+i,left+i,up);}
if(t==null){throw new NotFoundException();}
let x=null;for(let i=1;x===null&&i<maxSize;i++){x=this.getBlackPointOnSegment(right,up+i,right-i,up);}
if(x==null){throw new NotFoundException();}
let y=null;for(let i=1;y===null&&i<maxSize;i++){y=this.getBlackPointOnSegment(right,down-i,right-i,down);}
if(y==null){throw new NotFoundException();}
return this.centerEdges(y,z,x,t);}
else{throw new NotFoundException();}}
getBlackPointOnSegment(aX,aY,bX,bY){const dist=MathUtils.round(MathUtils.distance(aX,aY,bX,bY));const xStep=(bX-aX)/dist;const yStep=(bY-aY)/dist;const image=this.image;for(let i=0;i<dist;i++){const x=MathUtils.round(aX+i*xStep);const y=MathUtils.round(aY+i*yStep);if(image.get(x,y)){return new ResultPoint(x,y);}}
return null;}
centerEdges(y,z,x,t){const yi=y.getX();const yj=y.getY();const zi=z.getX();const zj=z.getY();const xi=x.getX();const xj=x.getY();const ti=t.getX();const tj=t.getY();const CORR=WhiteRectangleDetector.CORR;if(yi<this.width/2.0){return[new ResultPoint(ti-CORR,tj+CORR),new ResultPoint(zi+CORR,zj+CORR),new ResultPoint(xi-CORR,xj-CORR),new ResultPoint(yi+CORR,yj-CORR)];}
else{return[new ResultPoint(ti+CORR,tj+CORR),new ResultPoint(zi+CORR,zj-CORR),new ResultPoint(xi-CORR,xj+CORR),new ResultPoint(yi-CORR,yj-CORR)];}}
containsBlackPoint(a,b,fixed,horizontal){const image=this.image;if(horizontal){for(let x=a;x<=b;x++){if(image.get(x,fixed)){return true;}}}
else{for(let y=a;y<=b;y++){if(image.get(fixed,y)){return true;}}}
return false;}}
WhiteRectangleDetector.INIT_SIZE=10;WhiteRectangleDetector.CORR=1;class GridSampler{static checkAndNudgePoints(image,points){const width=image.getWidth();const height=image.getHeight();let nudged=true;for(let offset=0;offset<points.length&&nudged;offset+=2){const x=Math.floor(points[offset]);const y=Math.floor(points[offset+1]);if(x<-1||x>width||y<-1||y>height){throw new NotFoundException();}
nudged=false;if(x===-1){points[offset]=0.0;nudged=true;}
else if(x===width){points[offset]=width-1;nudged=true;}
if(y===-1){points[offset+1]=0.0;nudged=true;}
else if(y===height){points[offset+1]=height-1;nudged=true;}}
nudged=true;for(let offset=points.length-2;offset>=0&&nudged;offset-=2){const x=Math.floor(points[offset]);const y=Math.floor(points[offset+1]);if(x<-1||x>width||y<-1||y>height){throw new NotFoundException();}
nudged=false;if(x===-1){points[offset]=0.0;nudged=true;}
else if(x===width){points[offset]=width-1;nudged=true;}
if(y===-1){points[offset+1]=0.0;nudged=true;}
else if(y===height){points[offset+1]=height-1;nudged=true;}}}}
class PerspectiveTransform{constructor(a11,a21,a31,a12,a22,a32,a13,a23,a33){this.a11=a11;this.a21=a21;this.a31=a31;this.a12=a12;this.a22=a22;this.a32=a32;this.a13=a13;this.a23=a23;this.a33=a33;}
static quadrilateralToQuadrilateral(x0,y0,x1,y1,x2,y2,x3,y3,x0p,y0p,x1p,y1p,x2p,y2p,x3p,y3p){const qToS=PerspectiveTransform.quadrilateralToSquare(x0,y0,x1,y1,x2,y2,x3,y3);const sToQ=PerspectiveTransform.squareToQuadrilateral(x0p,y0p,x1p,y1p,x2p,y2p,x3p,y3p);return sToQ.times(qToS);}
transformPoints(points){const max=points.length;const a11=this.a11;const a12=this.a12;const a13=this.a13;const a21=this.a21;const a22=this.a22;const a23=this.a23;const a31=this.a31;const a32=this.a32;const a33=this.a33;for(let i=0;i<max;i+=2){const x=points[i];const y=points[i+1];const denominator=a13*x+a23*y+a33;points[i]=(a11*x+a21*y+a31)/denominator;points[i+1]=(a12*x+a22*y+a32)/denominator;}}
transformPointsWithValues(xValues,yValues){const a11=this.a11;const a12=this.a12;const a13=this.a13;const a21=this.a21;const a22=this.a22;const a23=this.a23;const a31=this.a31;const a32=this.a32;const a33=this.a33;const n=xValues.length;for(let i=0;i<n;i++){const x=xValues[i];const y=yValues[i];const denominator=a13*x+a23*y+a33;xValues[i]=(a11*x+a21*y+a31)/denominator;yValues[i]=(a12*x+a22*y+a32)/denominator;}}
static squareToQuadrilateral(x0,y0,x1,y1,x2,y2,x3,y3){const dx3=x0-x1+x2-x3;const dy3=y0-y1+y2-y3;if(dx3===0.0&&dy3===0.0){return new PerspectiveTransform(x1-x0,x2-x1,x0,y1-y0,y2-y1,y0,0.0,0.0,1.0);}
else{const dx1=x1-x2;const dx2=x3-x2;const dy1=y1-y2;const dy2=y3-y2;const denominator=dx1*dy2-dx2*dy1;const a13=(dx3*dy2-dx2*dy3)/denominator;const a23=(dx1*dy3-dx3*dy1)/denominator;return new PerspectiveTransform(x1-x0+a13*x1,x3-x0+a23*x3,x0,y1-y0+a13*y1,y3-y0+a23*y3,y0,a13,a23,1.0);}}
static quadrilateralToSquare(x0,y0,x1,y1,x2,y2,x3,y3){return PerspectiveTransform.squareToQuadrilateral(x0,y0,x1,y1,x2,y2,x3,y3).buildAdjoint();}
buildAdjoint(){return new PerspectiveTransform(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(other){return new PerspectiveTransform(this.a11*other.a11+this.a21*other.a12+this.a31*other.a13,this.a11*other.a21+this.a21*other.a22+this.a31*other.a23,this.a11*other.a31+this.a21*other.a32+this.a31*other.a33,this.a12*other.a11+this.a22*other.a12+this.a32*other.a13,this.a12*other.a21+this.a22*other.a22+this.a32*other.a23,this.a12*other.a31+this.a22*other.a32+this.a32*other.a33,this.a13*other.a11+this.a23*other.a12+this.a33*other.a13,this.a13*other.a21+this.a23*other.a22+this.a33*other.a23,this.a13*other.a31+this.a23*other.a32+this.a33*other.a33);}}
class DefaultGridSampler extends GridSampler{sampleGrid(image,dimensionX,dimensionY,p1ToX,p1ToY,p2ToX,p2ToY,p3ToX,p3ToY,p4ToX,p4ToY,p1FromX,p1FromY,p2FromX,p2FromY,p3FromX,p3FromY,p4FromX,p4FromY){const transform=PerspectiveTransform.quadrilateralToQuadrilateral(p1ToX,p1ToY,p2ToX,p2ToY,p3ToX,p3ToY,p4ToX,p4ToY,p1FromX,p1FromY,p2FromX,p2FromY,p3FromX,p3FromY,p4FromX,p4FromY);return this.sampleGridWithTransform(image,dimensionX,dimensionY,transform);}
sampleGridWithTransform(image,dimensionX,dimensionY,transform){if(dimensionX<=0||dimensionY<=0){throw new NotFoundException();}
const bits=new BitMatrix(dimensionX,dimensionY);const points=new Float32Array(2*dimensionX);for(let y=0;y<dimensionY;y++){const max=points.length;const iValue=y+0.5;for(let x=0;x<max;x+=2){points[x]=(x/2)+0.5;points[x+1]=iValue;}
transform.transformPoints(points);GridSampler.checkAndNudgePoints(image,points);try{for(let x=0;x<max;x+=2){if(image.get(Math.floor(points[x]),Math.floor(points[x+1]))){bits.set(x/2,y);}}}
catch(aioobe){throw new NotFoundException();}}
return bits;}}
class GridSamplerInstance{static setGridSampler(newGridSampler){GridSamplerInstance.gridSampler=newGridSampler;}
static getInstance(){return GridSamplerInstance.gridSampler;}}
GridSamplerInstance.gridSampler=new DefaultGridSampler();class Point{constructor(x,y){this.x=x;this.y=y;}
toResultPoint(){return new ResultPoint(this.getX(),this.getY());}
getX(){return this.x;}
getY(){return this.y;}}
class Detector{constructor(image){this.EXPECTED_CORNER_BITS=new Int32Array([0xee0,0x1dc,0x83b,0x707,]);this.image=image;}
detect(){return this.detectMirror(false);}
detectMirror(isMirror){let pCenter=this.getMatrixCenter();let bullsEyeCorners=this.getBullsEyeCorners(pCenter);if(isMirror){let temp=bullsEyeCorners[0];bullsEyeCorners[0]=bullsEyeCorners[2];bullsEyeCorners[2]=temp;}
this.extractParameters(bullsEyeCorners);let bits=this.sampleGrid(this.image,bullsEyeCorners[this.shift%4],bullsEyeCorners[(this.shift+1)%4],bullsEyeCorners[(this.shift+2)%4],bullsEyeCorners[(this.shift+3)%4]);let corners=this.getMatrixCornerPoints(bullsEyeCorners);return new AztecDetectorResult(bits,corners,this.compact,this.nbDataBlocks,this.nbLayers);}
extractParameters(bullsEyeCorners){if(!this.isValidPoint(bullsEyeCorners[0])||!this.isValidPoint(bullsEyeCorners[1])||!this.isValidPoint(bullsEyeCorners[2])||!this.isValidPoint(bullsEyeCorners[3])){throw new NotFoundException();}
let length=2*this.nbCenterLayers;let sides=new Int32Array([this.sampleLine(bullsEyeCorners[0],bullsEyeCorners[1],length),this.sampleLine(bullsEyeCorners[1],bullsEyeCorners[2],length),this.sampleLine(bullsEyeCorners[2],bullsEyeCorners[3],length),this.sampleLine(bullsEyeCorners[3],bullsEyeCorners[0],length)]);this.shift=this.getRotation(sides,length);let parameterData=0;for(let i=0;i<4;i++){let side=sides[(this.shift+i)%4];if(this.compact){parameterData<<=7;parameterData+=(side>>1)&0x7F;}
else{parameterData<<=10;parameterData+=((side>>2)&(0x1f<<5))+((side>>1)&0x1F);}}
let correctedData=this.getCorrectedParameterData(parameterData,this.compact);if(this.compact){this.nbLayers=(correctedData>>6)+1;this.nbDataBlocks=(correctedData&0x3F)+1;}
else{this.nbLayers=(correctedData>>11)+1;this.nbDataBlocks=(correctedData&0x7FF)+1;}}
getRotation(sides,length){let cornerBits=0;sides.forEach((side,idx,arr)=>{let t=((side>>(length-2))<<1)+(side&1);cornerBits=(cornerBits<<3)+t;});cornerBits=((cornerBits&1)<<11)+(cornerBits>>1);for(let shift=0;shift<4;shift++){if(Integer.bitCount(cornerBits^this.EXPECTED_CORNER_BITS[shift])<=2){return shift;}}
throw new NotFoundException();}
getCorrectedParameterData(parameterData,compact){let numCodewords;let numDataCodewords;if(compact){numCodewords=7;numDataCodewords=2;}
else{numCodewords=10;numDataCodewords=4;}
let numECCodewords=numCodewords-numDataCodewords;let parameterWords=new Int32Array(numCodewords);for(let i=numCodewords-1;i>=0;--i){parameterWords[i]=parameterData&0xF;parameterData>>=4;}
try{let rsDecoder=new ReedSolomonDecoder(GenericGF.AZTEC_PARAM);rsDecoder.decode(parameterWords,numECCodewords);}
catch(ignored){throw new NotFoundException();}
let result=0;for(let i=0;i<numDataCodewords;i++){result=(result<<4)+parameterWords[i];}
return result;}
getBullsEyeCorners(pCenter){let pina=pCenter;let pinb=pCenter;let pinc=pCenter;let pind=pCenter;let color=true;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){let pouta=this.getFirstDifferent(pina,color,1,-1);let poutb=this.getFirstDifferent(pinb,color,1,1);let poutc=this.getFirstDifferent(pinc,color,-1,1);let poutd=this.getFirstDifferent(pind,color,-1,-1);if(this.nbCenterLayers>2){let q=(this.distancePoint(poutd,pouta)*this.nbCenterLayers)/(this.distancePoint(pind,pina)*(this.nbCenterLayers+2));if(q<0.75||q>1.25||!this.isWhiteOrBlackRectangle(pouta,poutb,poutc,poutd)){break;}}
pina=pouta;pinb=poutb;pinc=poutc;pind=poutd;color=!color;}
if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7){throw new NotFoundException();}
this.compact=this.nbCenterLayers===5;let pinax=new ResultPoint(pina.getX()+0.5,pina.getY()-0.5);let pinbx=new ResultPoint(pinb.getX()+0.5,pinb.getY()+0.5);let pincx=new ResultPoint(pinc.getX()-0.5,pinc.getY()+0.5);let pindx=new ResultPoint(pind.getX()-0.5,pind.getY()-0.5);return this.expandSquare([pinax,pinbx,pincx,pindx],2*this.nbCenterLayers-3,2*this.nbCenterLayers);}
getMatrixCenter(){let pointA;let pointB;let pointC;let pointD;try{let cornerPoints=new WhiteRectangleDetector(this.image).detect();pointA=cornerPoints[0];pointB=cornerPoints[1];pointC=cornerPoints[2];pointD=cornerPoints[3];}
catch(e){let cx=this.image.getWidth()/2;let cy=this.image.getHeight()/2;pointA=this.getFirstDifferent(new Point(cx+7,cy-7),false,1,-1).toResultPoint();pointB=this.getFirstDifferent(new Point(cx+7,cy+7),false,1,1).toResultPoint();pointC=this.getFirstDifferent(new Point(cx-7,cy+7),false,-1,1).toResultPoint();pointD=this.getFirstDifferent(new Point(cx-7,cy-7),false,-1,-1).toResultPoint();}
let cx=MathUtils.round((pointA.getX()+pointD.getX()+pointB.getX()+pointC.getX())/4.0);let cy=MathUtils.round((pointA.getY()+pointD.getY()+pointB.getY()+pointC.getY())/4.0);try{let cornerPoints=new WhiteRectangleDetector(this.image,15,cx,cy).detect();pointA=cornerPoints[0];pointB=cornerPoints[1];pointC=cornerPoints[2];pointD=cornerPoints[3];}
catch(e){pointA=this.getFirstDifferent(new Point(cx+7,cy-7),false,1,-1).toResultPoint();pointB=this.getFirstDifferent(new Point(cx+7,cy+7),false,1,1).toResultPoint();pointC=this.getFirstDifferent(new Point(cx-7,cy+7),false,-1,1).toResultPoint();pointD=this.getFirstDifferent(new Point(cx-7,cy-7),false,-1,-1).toResultPoint();}
cx=MathUtils.round((pointA.getX()+pointD.getX()+pointB.getX()+pointC.getX())/4.0);cy=MathUtils.round((pointA.getY()+pointD.getY()+pointB.getY()+pointC.getY())/4.0);return new Point(cx,cy);}
getMatrixCornerPoints(bullsEyeCorners){return this.expandSquare(bullsEyeCorners,2*this.nbCenterLayers,this.getDimension());}
sampleGrid(image,topLeft,topRight,bottomRight,bottomLeft){let sampler=GridSamplerInstance.getInstance();let dimension=this.getDimension();let low=dimension/2-this.nbCenterLayers;let high=dimension/2+this.nbCenterLayers;return sampler.sampleGrid(image,dimension,dimension,low,low,high,low,high,high,low,high,topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRight.getX(),bottomRight.getY(),bottomLeft.getX(),bottomLeft.getY());}
sampleLine(p1,p2,size){let result=0;let d=this.distanceResultPoint(p1,p2);let moduleSize=d/size;let px=p1.getX();let py=p1.getY();let dx=moduleSize*(p2.getX()-p1.getX())/d;let dy=moduleSize*(p2.getY()-p1.getY())/d;for(let i=0;i<size;i++){if(this.image.get(MathUtils.round(px+i*dx),MathUtils.round(py+i*dy))){result|=1<<(size-i-1);}}
return result;}
isWhiteOrBlackRectangle(p1,p2,p3,p4){let corr=3;p1=new Point(p1.getX()-corr,p1.getY()+corr);p2=new Point(p2.getX()-corr,p2.getY()-corr);p3=new Point(p3.getX()+corr,p3.getY()-corr);p4=new Point(p4.getX()+corr,p4.getY()+corr);let cInit=this.getColor(p4,p1);if(cInit===0){return false;}
let c=this.getColor(p1,p2);if(c!==cInit){return false;}
c=this.getColor(p2,p3);if(c!==cInit){return false;}
c=this.getColor(p3,p4);return c===cInit;}
getColor(p1,p2){let d=this.distancePoint(p1,p2);let dx=(p2.getX()-p1.getX())/d;let dy=(p2.getY()-p1.getY())/d;let error=0;let px=p1.getX();let py=p1.getY();let colorModel=this.image.get(p1.getX(),p1.getY());let iMax=Math.ceil(d);for(let i=0;i<iMax;i++){px+=dx;py+=dy;if(this.image.get(MathUtils.round(px),MathUtils.round(py))!==colorModel){error++;}}
let errRatio=error/d;if(errRatio>0.1&&errRatio<0.9){return 0;}
return(errRatio<=0.1)===colorModel?1:-1;}
getFirstDifferent(init,color,dx,dy){let x=init.getX()+dx;let y=init.getY()+dy;while(this.isValid(x,y)&&this.image.get(x,y)===color){x+=dx;y+=dy;}
x-=dx;y-=dy;while(this.isValid(x,y)&&this.image.get(x,y)===color){x+=dx;}
x-=dx;while(this.isValid(x,y)&&this.image.get(x,y)===color){y+=dy;}
y-=dy;return new Point(x,y);}
expandSquare(cornerPoints,oldSide,newSide){let ratio=newSide/(2.0*oldSide);let dx=cornerPoints[0].getX()-cornerPoints[2].getX();let dy=cornerPoints[0].getY()-cornerPoints[2].getY();let centerx=(cornerPoints[0].getX()+cornerPoints[2].getX())/2.0;let centery=(cornerPoints[0].getY()+cornerPoints[2].getY())/2.0;let result0=new ResultPoint(centerx+ratio*dx,centery+ratio*dy);let result2=new ResultPoint(centerx-ratio*dx,centery-ratio*dy);dx=cornerPoints[1].getX()-cornerPoints[3].getX();dy=cornerPoints[1].getY()-cornerPoints[3].getY();centerx=(cornerPoints[1].getX()+cornerPoints[3].getX())/2.0;centery=(cornerPoints[1].getY()+cornerPoints[3].getY())/2.0;let result1=new ResultPoint(centerx+ratio*dx,centery+ratio*dy);let result3=new ResultPoint(centerx-ratio*dx,centery-ratio*dy);let results=[result0,result1,result2,result3];return results;}
isValid(x,y){return x>=0&&x<this.image.getWidth()&&y>0&&y<this.image.getHeight();}
isValidPoint(point){let x=MathUtils.round(point.getX());let y=MathUtils.round(point.getY());return this.isValid(x,y);}
distancePoint(a,b){return MathUtils.distance(a.getX(),a.getY(),b.getX(),b.getY());}
distanceResultPoint(a,b){return MathUtils.distance(a.getX(),a.getY(),b.getX(),b.getY());}
getDimension(){if(this.compact){return 4*this.nbLayers+11;}
if(this.nbLayers<=4){return 4*this.nbLayers+15;}
return 4*this.nbLayers+2*(Integer.truncDivision((this.nbLayers-4),8)+1)+15;}}
class AztecReader{decode(image,hints=null){let exception=null;let detector=new Detector(image.getBlackMatrix());let points=null;let decoderResult=null;try{let detectorResult=detector.detectMirror(false);points=detectorResult.getPoints();this.reportFoundResultPoints(hints,points);decoderResult=new Decoder().decode(detectorResult);}
catch(e){exception=e;}
if(decoderResult==null){try{let detectorResult=detector.detectMirror(true);points=detectorResult.getPoints();this.reportFoundResultPoints(hints,points);decoderResult=new Decoder().decode(detectorResult);}
catch(e){if(exception!=null){throw exception;}
throw e;}}
let result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),decoderResult.getNumBits(),points,BarcodeFormat$1.AZTEC,System.currentTimeMillis());let byteSegments=decoderResult.getByteSegments();if(byteSegments!=null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}
let ecLevel=decoderResult.getECLevel();if(ecLevel!=null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}
return result;}
reportFoundResultPoints(hints,points){if(hints!=null){let rpcb=hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(rpcb!=null){points.forEach((point,idx,arr)=>{rpcb.foundPossibleResultPoint(point);});}}}
reset(){}}
class BrowserAztecCodeReader extends BrowserCodeReader{constructor(timeBetweenScansMillis=500){super(new AztecReader(),timeBetweenScansMillis);}}
class OneDReader{decode(image,hints){try{return this.doDecode(image,hints);}
catch(nfe){const tryHarder=hints&&(hints.get(DecodeHintType$1.TRY_HARDER)===true);if(tryHarder&&image.isRotateSupported()){const rotatedImage=image.rotateCounterClockwise();const result=this.doDecode(rotatedImage,hints);const metadata=result.getResultMetadata();let orientation=270;if(metadata!==null&&(metadata.get(ResultMetadataType$1.ORIENTATION)===true)){orientation=(orientation+metadata.get(ResultMetadataType$1.ORIENTATION)%360);}
result.putMetadata(ResultMetadataType$1.ORIENTATION,orientation);const points=result.getResultPoints();if(points!==null){const height=rotatedImage.getHeight();for(let i=0;i<points.length;i++){points[i]=new ResultPoint(height-points[i].getY()-1,points[i].getX());}}
return result;}
else{throw new NotFoundException();}}}
reset(){}
doDecode(image,hints){const width=image.getWidth();const height=image.getHeight();let row=new BitArray(width);const tryHarder=hints&&(hints.get(DecodeHintType$1.TRY_HARDER)===true);const rowStep=Math.max(1,height>>(tryHarder?8:5));let maxLines;if(tryHarder){maxLines=height;}
else{maxLines=15;}
const middle=Math.trunc(height/2);for(let x=0;x<maxLines;x++){const rowStepsAboveOrBelow=Math.trunc((x+1)/2);const isAbove=(x&0x01)===0;const rowNumber=middle+rowStep*(isAbove?rowStepsAboveOrBelow:-rowStepsAboveOrBelow);if(rowNumber<0||rowNumber>=height){break;}
try{row=image.getBlackRow(rowNumber,row);}
catch(ignored){continue;}
for(let attempt=0;attempt<2;attempt++){if(attempt===1){row.reverse();if(hints&&(hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK)===true)){const newHints=new Map();hints.forEach((hint,key)=>newHints.set(key,hint));newHints.delete(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);hints=newHints;}}
try{const result=this.decodeRow(rowNumber,row,hints);if(attempt===1){result.putMetadata(ResultMetadataType$1.ORIENTATION,180);const points=result.getResultPoints();if(points!==null){points[0]=new ResultPoint(width-points[0].getX()-1,points[0].getY());points[1]=new ResultPoint(width-points[1].getX()-1,points[1].getY());}}
return result;}
catch(re){}}}
throw new NotFoundException();}
static recordPattern(row,start,counters){const numCounters=counters.length;for(let index=0;index<numCounters;index++)
counters[index]=0;const end=row.getSize();if(start>=end){throw new NotFoundException();}
let isWhite=!row.get(start);let counterPosition=0;let i=start;while(i<end){if(row.get(i)!==isWhite){counters[counterPosition]++;}
else{if(++counterPosition===numCounters){break;}
else{counters[counterPosition]=1;isWhite=!isWhite;}}
i++;}
if(!(counterPosition===numCounters||(counterPosition===numCounters-1&&i===end))){throw new NotFoundException();}}
static recordPatternInReverse(row,start,counters){let numTransitionsLeft=counters.length;let last=row.get(start);while(start>0&&numTransitionsLeft>=0){if(row.get(--start)!==last){numTransitionsLeft--;last=!last;}}
if(numTransitionsLeft>=0){throw new NotFoundException();}
OneDReader.recordPattern(row,start+1,counters);}
static patternMatchVariance(counters,pattern,maxIndividualVariance){const numCounters=counters.length;let total=0;let patternLength=0;for(let i=0;i<numCounters;i++){total+=counters[i];patternLength+=pattern[i];}
if(total<patternLength){return Number.POSITIVE_INFINITY;}
const unitBarWidth=total/patternLength;maxIndividualVariance*=unitBarWidth;let totalVariance=0.0;for(let x=0;x<numCounters;x++){const counter=counters[x];const scaledPattern=pattern[x]*unitBarWidth;const variance=counter>scaledPattern?counter-scaledPattern:scaledPattern-counter;if(variance>maxIndividualVariance){return Number.POSITIVE_INFINITY;}
totalVariance+=variance;}
return totalVariance/total;}}
class Code128Reader extends OneDReader{static findStartPattern(row){const width=row.getSize();const rowOffset=row.getNextSet(0);let counterPosition=0;let counters=Int32Array.from([0,0,0,0,0,0]);let patternStart=rowOffset;let isWhite=false;const patternLength=6;for(let i=rowOffset;i<width;i++){if(row.get(i)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===(patternLength-1)){let bestVariance=Code128Reader.MAX_AVG_VARIANCE;let bestMatch=-1;for(let startCode=Code128Reader.CODE_START_A;startCode<=Code128Reader.CODE_START_C;startCode++){const variance=OneDReader.patternMatchVariance(counters,Code128Reader.CODE_PATTERNS[startCode],Code128Reader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=startCode;}}
if(bestMatch>=0&&row.isRange(Math.max(0,patternStart-(i-patternStart)/2),patternStart,false)){return Int32Array.from([patternStart,i,bestMatch]);}
patternStart+=counters[0]+counters[1];counters=counters.slice(2,counters.length-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
static decodeCode(row,counters,rowOffset){OneDReader.recordPattern(row,rowOffset,counters);let bestVariance=Code128Reader.MAX_AVG_VARIANCE;let bestMatch=-1;for(let d=0;d<Code128Reader.CODE_PATTERNS.length;d++){const pattern=Code128Reader.CODE_PATTERNS[d];const variance=this.patternMatchVariance(counters,pattern,Code128Reader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=d;}}
if(bestMatch>=0){return bestMatch;}
else{throw new NotFoundException();}}
decodeRow(rowNumber,row,hints){const convertFNC1=hints&&(hints.get(DecodeHintType$1.ASSUME_GS1)===true);const startPatternInfo=Code128Reader.findStartPattern(row);const startCode=startPatternInfo[2];let currentRawCodesIndex=0;const rawCodes=new Uint8Array(20);rawCodes[currentRawCodesIndex++]=startCode;let codeSet;switch(startCode){case Code128Reader.CODE_START_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_START_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_START_C:codeSet=Code128Reader.CODE_CODE_C;break;default:throw new FormatException();}
let done=false;let isNextShifted=false;let result='';let lastStart=startPatternInfo[0];let nextStart=startPatternInfo[1];const counters=Int32Array.from([0,0,0,0,0,0]);let lastCode=0;let code=0;let checksumTotal=startCode;let multiplier=0;let lastCharacterWasPrintable=true;let upperMode=false;let shiftUpperMode=false;while(!done){const unshift=isNextShifted;isNextShifted=false;lastCode=code;code=Code128Reader.decodeCode(row,counters,nextStart);rawCodes[currentRawCodesIndex++]=code;if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=true;}
if(code!==Code128Reader.CODE_STOP){multiplier++;checksumTotal+=multiplier*code;}
lastStart=nextStart;nextStart+=counters.reduce((previous,current)=>previous+current,0);switch(code){case Code128Reader.CODE_START_A:case Code128Reader.CODE_START_B:case Code128Reader.CODE_START_C:throw new FormatException();}
switch(codeSet){case Code128Reader.CODE_CODE_A:if(code<64){if(shiftUpperMode===upperMode){result+=String.fromCharCode((' '.charCodeAt(0)+code));}
else{result+=String.fromCharCode((' '.charCodeAt(0)+code+128));}
shiftUpperMode=false;}
else if(code<96){if(shiftUpperMode===upperMode){result+=String.fromCharCode((code-64));}
else{result+=String.fromCharCode((code+64));}
shiftUpperMode=false;}
else{if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}
switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){result+=']C1';}
else{result+=String.fromCharCode(29);}}
break;case Code128Reader.CODE_FNC_2:case Code128Reader.CODE_FNC_3:break;case Code128Reader.CODE_FNC_4_A:if(!upperMode&&shiftUpperMode){upperMode=true;shiftUpperMode=false;}
else if(upperMode&&shiftUpperMode){upperMode=false;shiftUpperMode=false;}
else{shiftUpperMode=true;}
break;case Code128Reader.CODE_SHIFT:isNextShifted=true;codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_CODE_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_CODE_C:codeSet=Code128Reader.CODE_CODE_C;break;case Code128Reader.CODE_STOP:done=true;break;}}
break;case Code128Reader.CODE_CODE_B:if(code<96){if(shiftUpperMode===upperMode){result+=String.fromCharCode((' '.charCodeAt(0)+code));}
else{result+=String.fromCharCode((' '.charCodeAt(0)+code+128));}
shiftUpperMode=false;}
else{if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}
switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){result+=']C1';}
else{result+=String.fromCharCode(29);}}
break;case Code128Reader.CODE_FNC_2:case Code128Reader.CODE_FNC_3:break;case Code128Reader.CODE_FNC_4_B:if(!upperMode&&shiftUpperMode){upperMode=true;shiftUpperMode=false;}
else if(upperMode&&shiftUpperMode){upperMode=false;shiftUpperMode=false;}
else{shiftUpperMode=true;}
break;case Code128Reader.CODE_SHIFT:isNextShifted=true;codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_C:codeSet=Code128Reader.CODE_CODE_C;break;case Code128Reader.CODE_STOP:done=true;break;}}
break;case Code128Reader.CODE_CODE_C:if(code<100){if(code<10){result+='0';}
result+=code;}
else{if(code!==Code128Reader.CODE_STOP){lastCharacterWasPrintable=false;}
switch(code){case Code128Reader.CODE_FNC_1:if(convertFNC1){if(result.length===0){result+=']C1';}
else{result+=String.fromCharCode(29);}}
break;case Code128Reader.CODE_CODE_A:codeSet=Code128Reader.CODE_CODE_A;break;case Code128Reader.CODE_CODE_B:codeSet=Code128Reader.CODE_CODE_B;break;case Code128Reader.CODE_STOP:done=true;break;}}
break;}
if(unshift){codeSet=codeSet===Code128Reader.CODE_CODE_A?Code128Reader.CODE_CODE_B:Code128Reader.CODE_CODE_A;}}
const lastPatternSize=nextStart-lastStart;nextStart=row.getNextUnset(nextStart);if(!row.isRange(nextStart,Math.min(row.getSize(),nextStart+(nextStart-lastStart)/2),false)){throw new NotFoundException();}
checksumTotal-=multiplier*lastCode;if(checksumTotal%103!==lastCode){throw new ChecksumException();}
const resultLength=result.length;if(resultLength===0){throw new NotFoundException();}
if(resultLength>0&&lastCharacterWasPrintable){if(codeSet===Code128Reader.CODE_CODE_C){result=result.substring(0,resultLength-2);}
else{result=result.substring(0,resultLength-1);}}
const left=(startPatternInfo[1]+startPatternInfo[0])/2.0;const right=lastStart+lastPatternSize/2.0;const rawCodesSize=rawCodes.length;const rawBytes=new Uint8Array(rawCodesSize);for(let i=0;i<rawCodesSize;i++){rawBytes[i]=rawCodes[i];}
const points=[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)];return new Result(result,rawBytes,0,points,BarcodeFormat$1.CODE_128,new Date().getTime());}}
Code128Reader.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]),];Code128Reader.MAX_AVG_VARIANCE=0.25;Code128Reader.MAX_INDIVIDUAL_VARIANCE=0.7;Code128Reader.CODE_SHIFT=98;Code128Reader.CODE_CODE_C=99;Code128Reader.CODE_CODE_B=100;Code128Reader.CODE_CODE_A=101;Code128Reader.CODE_FNC_1=102;Code128Reader.CODE_FNC_2=97;Code128Reader.CODE_FNC_3=96;Code128Reader.CODE_FNC_4_A=101;Code128Reader.CODE_FNC_4_B=100;Code128Reader.CODE_START_A=103;Code128Reader.CODE_START_B=104;Code128Reader.CODE_START_C=105;Code128Reader.CODE_STOP=106;class Code39Reader extends OneDReader{constructor(usingCheckDigit=false,extendedMode=false){super();this.usingCheckDigit=usingCheckDigit;this.extendedMode=extendedMode;this.decodeRowResult='';this.counters=new Int32Array(9);}
decodeRow(rowNumber,row,hints){let theCounters=this.counters;theCounters.fill(0);this.decodeRowResult='';let start=Code39Reader.findAsteriskPattern(row,theCounters);let nextStart=row.getNextSet(start[1]);let end=row.getSize();let decodedChar;let lastStart;do{Code39Reader.recordPattern(row,nextStart,theCounters);let pattern=Code39Reader.toNarrowWidePattern(theCounters);if(pattern<0){throw new NotFoundException();}
decodedChar=Code39Reader.patternToChar(pattern);this.decodeRowResult+=decodedChar;lastStart=nextStart;for(let counter of theCounters){nextStart+=counter;}
nextStart=row.getNextSet(nextStart);}while(decodedChar!=='*');this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let lastPatternSize=0;for(let counter of theCounters){lastPatternSize+=counter;}
let whiteSpaceAfterEnd=nextStart-lastStart-lastPatternSize;if(nextStart!==end&&(whiteSpaceAfterEnd*2)<lastPatternSize){throw new NotFoundException();}
if(this.usingCheckDigit){let max=this.decodeRowResult.length-1;let total=0;for(let i=0;i<max;i++){total+=Code39Reader.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(i));}
if(this.decodeRowResult.charAt(max)!==Code39Reader.ALPHABET_STRING.charAt(total%43)){throw new ChecksumException();}
this.decodeRowResult=this.decodeRowResult.substring(0,max);}
if(this.decodeRowResult.length===0){throw new NotFoundException();}
let resultString;if(this.extendedMode){resultString=Code39Reader.decodeExtended(this.decodeRowResult);}
else{resultString=this.decodeRowResult;}
let left=(start[1]+start[0])/2.0;let right=lastStart+lastPatternSize/2.0;return new Result(resultString,null,0,[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)],BarcodeFormat$1.CODE_39,new Date().getTime());}
static findAsteriskPattern(row,counters){let width=row.getSize();let rowOffset=row.getNextSet(0);let counterPosition=0;let patternStart=rowOffset;let isWhite=false;let patternLength=counters.length;for(let i=rowOffset;i<width;i++){if(row.get(i)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===patternLength-1){if(this.toNarrowWidePattern(counters)===Code39Reader.ASTERISK_ENCODING&&row.isRange(Math.max(0,patternStart-Math.floor((i-patternStart)/2)),patternStart,false)){return[patternStart,i];}
patternStart+=counters[0]+counters[1];counters.copyWithin(0,2,2+counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
static toNarrowWidePattern(counters){let numCounters=counters.length;let maxNarrowCounter=0;let wideCounters;do{let minCounter=0x7fffffff;for(let counter of counters){if(counter<minCounter&&counter>maxNarrowCounter){minCounter=counter;}}
maxNarrowCounter=minCounter;wideCounters=0;let totalWideCountersWidth=0;let pattern=0;for(let i=0;i<numCounters;i++){let counter=counters[i];if(counter>maxNarrowCounter){pattern|=1<<(numCounters-1-i);wideCounters++;totalWideCountersWidth+=counter;}}
if(wideCounters===3){for(let i=0;i<numCounters&&wideCounters>0;i++){let counter=counters[i];if(counter>maxNarrowCounter){wideCounters--;if((counter*2)>=totalWideCountersWidth){return-1;}}}
return pattern;}}while(wideCounters>3);return-1;}
static patternToChar(pattern){for(let i=0;i<Code39Reader.CHARACTER_ENCODINGS.length;i++){if(Code39Reader.CHARACTER_ENCODINGS[i]===pattern){return Code39Reader.ALPHABET_STRING.charAt(i);}}
if(pattern===Code39Reader.ASTERISK_ENCODING){return'*';}
throw new NotFoundException();}
static decodeExtended(encoded){let length=encoded.length;let decoded='';for(let i=0;i<length;i++){let c=encoded.charAt(i);if(c==='+'||c==='$'||c==='%'||c==='/'){let next=encoded.charAt(i+1);let decodedChar='\0';switch(c){case'+':if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)+32);}
else{throw new FormatException();}
break;case'$':if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)-64);}
else{throw new FormatException();}
break;case'%':if(next>='A'&&next<='E'){decodedChar=String.fromCharCode(next.charCodeAt(0)-38);}
else if(next>='F'&&next<='J'){decodedChar=String.fromCharCode(next.charCodeAt(0)-11);}
else if(next>='K'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)+16);}
else if(next>='P'&&next<='T'){decodedChar=String.fromCharCode(next.charCodeAt(0)+43);}
else if(next==='U'){decodedChar='\0';}
else if(next==='V'){decodedChar='@';}
else if(next==='W'){decodedChar='`';}
else if(next==='X'||next==='Y'||next==='Z'){decodedChar='\x7f';}
else{throw new FormatException();}
break;case'/':if(next>='A'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)-32);}
else if(next==='Z'){decodedChar=':';}
else{throw new FormatException();}
break;}
decoded+=decodedChar;i++;}
else{decoded+=c;}}
return decoded;}}
Code39Reader.ALPHABET_STRING='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';Code39Reader.CHARACTER_ENCODINGS=[0x034,0x121,0x061,0x160,0x031,0x130,0x070,0x025,0x124,0x064,0x109,0x049,0x148,0x019,0x118,0x058,0x00D,0x10C,0x04C,0x01C,0x103,0x043,0x142,0x013,0x112,0x052,0x007,0x106,0x046,0x016,0x181,0x0C1,0x1C0,0x091,0x190,0x0D0,0x085,0x184,0x0C4,0x0A8,0x0A2,0x08A,0x02A];Code39Reader.ASTERISK_ENCODING=0x094;class Code93Reader extends OneDReader{constructor(){super();this.decodeRowResult='';this.counters=new Int32Array(6);}
decodeRow(rowNumber,row,hints){let start=this.findAsteriskPattern(row);let nextStart=row.getNextSet(start[1]);let end=row.getSize();let theCounters=this.counters;theCounters.fill(0);this.decodeRowResult='';let decodedChar;let lastStart;do{Code93Reader.recordPattern(row,nextStart,theCounters);let pattern=this.toPattern(theCounters);if(pattern<0){throw new NotFoundException();}
decodedChar=this.patternToChar(pattern);this.decodeRowResult+=decodedChar;lastStart=nextStart;for(let counter of theCounters){nextStart+=counter;}
nextStart=row.getNextSet(nextStart);}while(decodedChar!=='*');this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);let lastPatternSize=0;for(let counter of theCounters){lastPatternSize+=counter;}
if(nextStart===end||!row.get(nextStart)){throw new NotFoundException();}
if(this.decodeRowResult.length<2){throw new NotFoundException();}
this.checkChecksums(this.decodeRowResult);this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-2);let resultString=this.decodeExtended(this.decodeRowResult);let left=(start[1]+start[0])/2.0;let right=lastStart+lastPatternSize/2.0;return new Result(resultString,null,0,[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)],BarcodeFormat$1.CODE_93,new Date().getTime());}
findAsteriskPattern(row){let width=row.getSize();let rowOffset=row.getNextSet(0);this.counters.fill(0);let theCounters=this.counters;let patternStart=rowOffset;let isWhite=false;let patternLength=theCounters.length;let counterPosition=0;for(let i=rowOffset;i<width;i++){if(row.get(i)!==isWhite){theCounters[counterPosition]++;}
else{if(counterPosition===patternLength-1){if(this.toPattern(theCounters)===Code93Reader.ASTERISK_ENCODING){return new Int32Array([patternStart,i]);}
patternStart+=theCounters[0]+theCounters[1];theCounters.copyWithin(0,2,2+counterPosition-1);theCounters[counterPosition-1]=0;theCounters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
theCounters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException;}
toPattern(counters){let sum=0;for(const counter of counters){sum+=counter;}
let pattern=0;let max=counters.length;for(let i=0;i<max;i++){let scaled=Math.round(counters[i]*9.0/sum);if(scaled<1||scaled>4){return-1;}
if((i&0x01)===0){for(let j=0;j<scaled;j++){pattern=(pattern<<1)|0x01;}}
else{pattern<<=scaled;}}
return pattern;}
patternToChar(pattern){for(let i=0;i<Code93Reader.CHARACTER_ENCODINGS.length;i++){if(Code93Reader.CHARACTER_ENCODINGS[i]===pattern){return Code93Reader.ALPHABET_STRING.charAt(i);}}
throw new NotFoundException();}
decodeExtended(encoded){let length=encoded.length;let decoded='';for(let i=0;i<length;i++){let c=encoded.charAt(i);if(c>='a'&&c<='d'){if(i>=length-1){throw new FormatException();}
let next=encoded.charAt(i+1);let decodedChar='\0';switch(c){case'd':if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)+32);}
else{throw new FormatException();}
break;case'a':if(next>='A'&&next<='Z'){decodedChar=String.fromCharCode(next.charCodeAt(0)-64);}
else{throw new FormatException();}
break;case'b':if(next>='A'&&next<='E'){decodedChar=String.fromCharCode(next.charCodeAt(0)-38);}
else if(next>='F'&&next<='J'){decodedChar=String.fromCharCode(next.charCodeAt(0)-11);}
else if(next>='K'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)+16);}
else if(next>='P'&&next<='T'){decodedChar=String.fromCharCode(next.charCodeAt(0)+43);}
else if(next==='U'){decodedChar='\0';}
else if(next==='V'){decodedChar='@';}
else if(next==='W'){decodedChar='`';}
else if(next>='X'&&next<='Z'){decodedChar=String.fromCharCode(127);}
else{throw new FormatException();}
break;case'c':if(next>='A'&&next<='O'){decodedChar=String.fromCharCode(next.charCodeAt(0)-32);}
else if(next==='Z'){decodedChar=':';}
else{throw new FormatException();}
break;}
decoded+=decodedChar;i++;}
else{decoded+=c;}}
return decoded;}
checkChecksums(result){let length=result.length;this.checkOneChecksum(result,length-2,20);this.checkOneChecksum(result,length-1,15);}
checkOneChecksum(result,checkPosition,weightMax){let weight=1;let total=0;for(let i=checkPosition-1;i>=0;i--){total+=weight*Code93Reader.ALPHABET_STRING.indexOf(result.charAt(i));if(++weight>weightMax){weight=1;}}
if(result.charAt(checkPosition)!==Code93Reader.ALPHABET_STRING[total%47]){throw new ChecksumException;}}}
Code93Reader.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*";Code93Reader.CHARACTER_ENCODINGS=[0x114,0x148,0x144,0x142,0x128,0x124,0x122,0x150,0x112,0x10A,0x1A8,0x1A4,0x1A2,0x194,0x192,0x18A,0x168,0x164,0x162,0x134,0x11A,0x158,0x14C,0x146,0x12C,0x116,0x1B4,0x1B2,0x1AC,0x1A6,0x196,0x19A,0x16C,0x166,0x136,0x13A,0x12E,0x1D4,0x1D2,0x1CA,0x16E,0x176,0x1AE,0x126,0x1DA,0x1D6,0x132,0x15E,];Code93Reader.ASTERISK_ENCODING=Code93Reader.CHARACTER_ENCODINGS[47];class ITFReader extends OneDReader{constructor(){super(...arguments);this.narrowLineWidth=-1;}
decodeRow(rowNumber,row,hints){let startRange=this.decodeStart(row);let endRange=this.decodeEnd(row);let result=new StringBuilder();ITFReader.decodeMiddle(row,startRange[1],endRange[0],result);let resultString=result.toString();let allowedLengths=null;if(hints!=null){allowedLengths=hints.get(DecodeHintType$1.ALLOWED_LENGTHS);}
if(allowedLengths==null){allowedLengths=ITFReader.DEFAULT_ALLOWED_LENGTHS;}
let length=resultString.length;let lengthOK=false;let maxAllowedLength=0;for(let value of allowedLengths){if(length===value){lengthOK=true;break;}
if(value>maxAllowedLength){maxAllowedLength=value;}}
if(!lengthOK&&length>maxAllowedLength){lengthOK=true;}
if(!lengthOK){throw new FormatException();}
const points=[new ResultPoint(startRange[1],rowNumber),new ResultPoint(endRange[0],rowNumber)];let resultReturn=new Result(resultString,null,0,points,BarcodeFormat$1.ITF,new Date().getTime());return resultReturn;}
static decodeMiddle(row,payloadStart,payloadEnd,resultString){let counterDigitPair=new Int32Array(10);let counterBlack=new Int32Array(5);let counterWhite=new Int32Array(5);counterDigitPair.fill(0);counterBlack.fill(0);counterWhite.fill(0);while(payloadStart<payloadEnd){OneDReader.recordPattern(row,payloadStart,counterDigitPair);for(let k=0;k<5;k++){let twoK=2*k;counterBlack[k]=counterDigitPair[twoK];counterWhite[k]=counterDigitPair[twoK+1];}
let bestMatch=ITFReader.decodeDigit(counterBlack);resultString.append(bestMatch.toString());bestMatch=this.decodeDigit(counterWhite);resultString.append(bestMatch.toString());counterDigitPair.forEach(function(counterDigit){payloadStart+=counterDigit;});}}
decodeStart(row){let endStart=ITFReader.skipWhiteSpace(row);let startPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.START_PATTERN);this.narrowLineWidth=(startPattern[1]-startPattern[0])/4;this.validateQuietZone(row,startPattern[0]);return startPattern;}
validateQuietZone(row,startPattern){let quietCount=this.narrowLineWidth*10;quietCount=quietCount<startPattern?quietCount:startPattern;for(let i=startPattern-1;quietCount>0&&i>=0;i--){if(row.get(i)){break;}
quietCount--;}
if(quietCount!==0){throw new NotFoundException();}}
static skipWhiteSpace(row){const width=row.getSize();const endStart=row.getNextSet(0);if(endStart===width){throw new NotFoundException();}
return endStart;}
decodeEnd(row){row.reverse();try{let endStart=ITFReader.skipWhiteSpace(row);let endPattern;try{endPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.END_PATTERN_REVERSED[0]);}
catch(error){if(error instanceof NotFoundException){endPattern=ITFReader.findGuardPattern(row,endStart,ITFReader.END_PATTERN_REVERSED[1]);}}
this.validateQuietZone(row,endPattern[0]);let temp=endPattern[0];endPattern[0]=row.getSize()-endPattern[1];endPattern[1]=row.getSize()-temp;return endPattern;}
finally{row.reverse();}}
static findGuardPattern(row,rowOffset,pattern){let patternLength=pattern.length;let counters=new Int32Array(patternLength);let width=row.getSize();let isWhite=false;let counterPosition=0;let patternStart=rowOffset;counters.fill(0);for(let x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===patternLength-1){if(OneDReader.patternMatchVariance(counters,pattern,ITFReader.MAX_INDIVIDUAL_VARIANCE)<ITFReader.MAX_AVG_VARIANCE){return[patternStart,x];}
patternStart+=counters[0]+counters[1];System.arraycopy(counters,2,counters,0,counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
static decodeDigit(counters){let bestVariance=ITFReader.MAX_AVG_VARIANCE;let bestMatch=-1;let max=ITFReader.PATTERNS.length;for(let i=0;i<max;i++){let pattern=ITFReader.PATTERNS[i];let variance=OneDReader.patternMatchVariance(counters,pattern,ITFReader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=i;}
else if(variance===bestVariance){bestMatch=-1;}}
if(bestMatch>=0){return bestMatch%10;}
else{throw new NotFoundException();}}}
ITFReader.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])];ITFReader.MAX_AVG_VARIANCE=0.38;ITFReader.MAX_INDIVIDUAL_VARIANCE=0.5;ITFReader.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14];ITFReader.START_PATTERN=Int32Array.from([1,1,1,1]);ITFReader.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])];class AbstractUPCEANReader extends OneDReader{constructor(){super(...arguments);this.decodeRowStringBuffer='';}
static findStartGuardPattern(row){let foundStart=false;let startRange;let nextStart=0;let counters=Int32Array.from([0,0,0]);while(!foundStart){counters=Int32Array.from([0,0,0]);startRange=AbstractUPCEANReader.findGuardPattern(row,nextStart,false,this.START_END_PATTERN,counters);let start=startRange[0];nextStart=startRange[1];let quietStart=start-(nextStart-start);if(quietStart>=0){foundStart=row.isRange(quietStart,start,false);}}
return startRange;}
static checkChecksum(s){return AbstractUPCEANReader.checkStandardUPCEANChecksum(s);}
static checkStandardUPCEANChecksum(s){let length=s.length;if(length===0)
return false;let check=parseInt(s.charAt(length-1),10);return AbstractUPCEANReader.getStandardUPCEANChecksum(s.substring(0,length-1))===check;}
static getStandardUPCEANChecksum(s){let length=s.length;let sum=0;for(let i=length-1;i>=0;i-=2){let digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}
sum+=digit;}
sum*=3;for(let i=length-2;i>=0;i-=2){let digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}
sum+=digit;}
return(1000-sum)%10;}
static decodeEnd(row,endStart){return AbstractUPCEANReader.findGuardPattern(row,endStart,false,AbstractUPCEANReader.START_END_PATTERN,new Int32Array(AbstractUPCEANReader.START_END_PATTERN.length).fill(0));}
static findGuardPatternWithoutCounters(row,rowOffset,whiteFirst,pattern){return this.findGuardPattern(row,rowOffset,whiteFirst,pattern,new Int32Array(pattern.length));}
static findGuardPattern(row,rowOffset,whiteFirst,pattern,counters){let width=row.getSize();rowOffset=whiteFirst?row.getNextUnset(rowOffset):row.getNextSet(rowOffset);let counterPosition=0;let patternStart=rowOffset;let patternLength=pattern.length;let isWhite=whiteFirst;for(let x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===patternLength-1){if(OneDReader.patternMatchVariance(counters,pattern,AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE)<AbstractUPCEANReader.MAX_AVG_VARIANCE){return Int32Array.from([patternStart,x]);}
patternStart+=counters[0]+counters[1];let slice=counters.slice(2,counters.length);for(let i=0;i<counterPosition-1;i++){counters[i]=slice[i];}
counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
static decodeDigit(row,counters,rowOffset,patterns){this.recordPattern(row,rowOffset,counters);let bestVariance=this.MAX_AVG_VARIANCE;let bestMatch=-1;let max=patterns.length;for(let i=0;i<max;i++){let pattern=patterns[i];let variance=OneDReader.patternMatchVariance(counters,pattern,AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE);if(variance<bestVariance){bestVariance=variance;bestMatch=i;}}
if(bestMatch>=0){return bestMatch;}
else{throw new NotFoundException();}}}
AbstractUPCEANReader.MAX_AVG_VARIANCE=0.48;AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE=0.7;AbstractUPCEANReader.START_END_PATTERN=Int32Array.from([1,1,1]);AbstractUPCEANReader.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]);AbstractUPCEANReader.END_PATTERN=Int32Array.from([1,1,1,1,1,1]);AbstractUPCEANReader.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 UPCEANExtension5Support{constructor(){this.CHECK_DIGIT_ENCODINGS=[0x18,0x14,0x12,0x11,0x0C,0x06,0x03,0x0A,0x09,0x05];this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);this.decodeRowStringBuffer='';}
decodeRow(rowNumber,row,extensionStartRange){let result=this.decodeRowStringBuffer;let end=this.decodeMiddle(row,extensionStartRange,result);let resultString=result.toString();let extensionData=UPCEANExtension5Support.parseExtensionString(resultString);let resultPoints=[new ResultPoint((extensionStartRange[0]+extensionStartRange[1])/2.0,rowNumber),new ResultPoint(end,rowNumber)];let extensionResult=new Result(resultString,null,0,resultPoints,BarcodeFormat$1.UPC_EAN_EXTENSION,new Date().getTime());if(extensionData!=null){extensionResult.putAllMetadata(extensionData);}
return extensionResult;}
decodeMiddle(row,startRange,resultString){let counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let end=row.getSize();let rowOffset=startRange[1];let lgPatternFound=0;for(let x=0;x<5&&rowOffset<end;x++){let bestMatch=AbstractUPCEANReader.decodeDigit(row,counters,rowOffset,AbstractUPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch%10));for(let counter of counters){rowOffset+=counter;}
if(bestMatch>=10){lgPatternFound|=1<<(4-x);}
if(x!==4){rowOffset=row.getNextSet(rowOffset);rowOffset=row.getNextUnset(rowOffset);}}
if(resultString.length!==5){throw new NotFoundException();}
let checkDigit=this.determineCheckDigit(lgPatternFound);if(UPCEANExtension5Support.extensionChecksum(resultString.toString())!==checkDigit){throw new NotFoundException();}
return rowOffset;}
static extensionChecksum(s){let length=s.length;let sum=0;for(let i=length-2;i>=0;i-=2){sum+=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);}
sum*=3;for(let i=length-1;i>=0;i-=2){sum+=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);}
sum*=3;return sum%10;}
determineCheckDigit(lgPatternFound){for(let d=0;d<10;d++){if(lgPatternFound===this.CHECK_DIGIT_ENCODINGS[d]){return d;}}
throw new NotFoundException();}
static parseExtensionString(raw){if(raw.length!==5){return null;}
let value=UPCEANExtension5Support.parseExtension5String(raw);if(value==null){return null;}
return new Map([[ResultMetadataType$1.SUGGESTED_PRICE,value]]);}
static parseExtension5String(raw){let currency;switch(raw.charAt(0)){case'0':currency='£';break;case'5':currency='$';break;case'9':switch(raw){case'90000':return null;case'99991':return'0.00';case'99990':return'Used';}
currency='';break;default:currency='';break;}
let rawAmount=parseInt(raw.substring(1));let unitsString=(rawAmount/100).toString();let hundredths=rawAmount%100;let hundredthsString=hundredths<10?'0'+hundredths:hundredths.toString();return currency+unitsString+'.'+hundredthsString;}}
class UPCEANExtension2Support{constructor(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);this.decodeRowStringBuffer='';}
decodeRow(rowNumber,row,extensionStartRange){let result=this.decodeRowStringBuffer;let end=this.decodeMiddle(row,extensionStartRange,result);let resultString=result.toString();let extensionData=UPCEANExtension2Support.parseExtensionString(resultString);let resultPoints=[new ResultPoint((extensionStartRange[0]+extensionStartRange[1])/2.0,rowNumber),new ResultPoint(end,rowNumber)];let extensionResult=new Result(resultString,null,0,resultPoints,BarcodeFormat$1.UPC_EAN_EXTENSION,new Date().getTime());if(extensionData!=null){extensionResult.putAllMetadata(extensionData);}
return extensionResult;}
decodeMiddle(row,startRange,resultString){let counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let end=row.getSize();let rowOffset=startRange[1];let checkParity=0;for(let x=0;x<2&&rowOffset<end;x++){let bestMatch=AbstractUPCEANReader.decodeDigit(row,counters,rowOffset,AbstractUPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch%10));for(let counter of counters){rowOffset+=counter;}
if(bestMatch>=10){checkParity|=1<<(1-x);}
if(x!==1){rowOffset=row.getNextSet(rowOffset);rowOffset=row.getNextUnset(rowOffset);}}
if(resultString.length!==2){throw new NotFoundException();}
if(parseInt(resultString.toString())%4!==checkParity){throw new NotFoundException();}
return rowOffset;}
static parseExtensionString(raw){if(raw.length!==2){return null;}
return new Map([[ResultMetadataType$1.ISSUE_NUMBER,parseInt(raw)]]);}}
class UPCEANExtensionSupport{static decodeRow(rowNumber,row,rowOffset){let extensionStartRange=AbstractUPCEANReader.findGuardPattern(row,rowOffset,false,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{let fiveSupport=new UPCEANExtension5Support();return fiveSupport.decodeRow(rowNumber,row,extensionStartRange);}
catch(err){let twoSupport=new UPCEANExtension2Support();return twoSupport.decodeRow(rowNumber,row,extensionStartRange);}}}
UPCEANExtensionSupport.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]);class UPCEANReader extends AbstractUPCEANReader{constructor(){super();this.decodeRowStringBuffer='';UPCEANReader.L_AND_G_PATTERNS=UPCEANReader.L_PATTERNS.map(arr=>Int32Array.from(arr));for(let i=10;i<20;i++){let widths=UPCEANReader.L_PATTERNS[i-10];let reversedWidths=new Int32Array(widths.length);for(let j=0;j<widths.length;j++){reversedWidths[j]=widths[widths.length-j-1];}
UPCEANReader.L_AND_G_PATTERNS[i]=reversedWidths;}}
decodeRow(rowNumber,row,hints){let startGuardRange=UPCEANReader.findStartGuardPattern(row);let resultPointCallback=hints==null?null:hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(resultPointCallback!=null){const resultPoint=new ResultPoint((startGuardRange[0]+startGuardRange[1])/2.0,rowNumber);resultPointCallback.foundPossibleResultPoint(resultPoint);}
let budello=this.decodeMiddle(row,startGuardRange,this.decodeRowStringBuffer);let endStart=budello.rowOffset;let result=budello.resultString;if(resultPointCallback!=null){const resultPoint=new ResultPoint(endStart,rowNumber);resultPointCallback.foundPossibleResultPoint(resultPoint);}
let endRange=UPCEANReader.decodeEnd(row,endStart);if(resultPointCallback!=null){const resultPoint=new ResultPoint((endRange[0]+endRange[1])/2.0,rowNumber);resultPointCallback.foundPossibleResultPoint(resultPoint);}
let end=endRange[1];let quietEnd=end+(end-endRange[0]);if(quietEnd>=row.getSize()||!row.isRange(end,quietEnd,false)){throw new NotFoundException();}
let resultString=result.toString();if(resultString.length<8){throw new FormatException();}
if(!UPCEANReader.checkChecksum(resultString)){throw new ChecksumException();}
let left=(startGuardRange[1]+startGuardRange[0])/2.0;let right=(endRange[1]+endRange[0])/2.0;let format=this.getBarcodeFormat();let resultPoint=[new ResultPoint(left,rowNumber),new ResultPoint(right,rowNumber)];let decodeResult=new Result(resultString,null,0,resultPoint,format,new Date().getTime());let extensionLength=0;try{let extensionResult=UPCEANExtensionSupport.decodeRow(rowNumber,row,endRange[1]);decodeResult.putMetadata(ResultMetadataType$1.UPC_EAN_EXTENSION,extensionResult.getText());decodeResult.putAllMetadata(extensionResult.getResultMetadata());decodeResult.addResultPoints(extensionResult.getResultPoints());extensionLength=extensionResult.getText().length;}
catch(err){}
let allowedExtensions=hints==null?null:hints.get(DecodeHintType$1.ALLOWED_EAN_EXTENSIONS);if(allowedExtensions!=null){let valid=false;for(let length in allowedExtensions){if(extensionLength.toString()===length){valid=true;break;}}
if(!valid){throw new NotFoundException();}}
if(format===BarcodeFormat$1.EAN_13||format===BarcodeFormat$1.UPC_A);return decodeResult;}
static checkChecksum(s){return UPCEANReader.checkStandardUPCEANChecksum(s);}
static checkStandardUPCEANChecksum(s){let length=s.length;if(length===0)
return false;let check=parseInt(s.charAt(length-1),10);return UPCEANReader.getStandardUPCEANChecksum(s.substring(0,length-1))===check;}
static getStandardUPCEANChecksum(s){let length=s.length;let sum=0;for(let i=length-1;i>=0;i-=2){let digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}
sum+=digit;}
sum*=3;for(let i=length-2;i>=0;i-=2){let digit=s.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);if(digit<0||digit>9){throw new FormatException();}
sum+=digit;}
return(1000-sum)%10;}
static decodeEnd(row,endStart){return UPCEANReader.findGuardPattern(row,endStart,false,UPCEANReader.START_END_PATTERN,new Int32Array(UPCEANReader.START_END_PATTERN.length).fill(0));}}
class EAN13Reader extends UPCEANReader{constructor(){super();this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);}
decodeMiddle(row,startRange,resultString){let counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let end=row.getSize();let rowOffset=startRange[1];let lgPatternFound=0;for(let x=0;x<6&&rowOffset<end;x++){let bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_AND_G_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch%10));for(let counter of counters){rowOffset+=counter;}
if(bestMatch>=10){lgPatternFound|=1<<(5-x);}}
resultString=EAN13Reader.determineFirstDigit(resultString,lgPatternFound);let middleRange=UPCEANReader.findGuardPattern(row,rowOffset,true,UPCEANReader.MIDDLE_PATTERN,new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));rowOffset=middleRange[1];for(let x=0;x<6&&rowOffset<end;x++){let bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch));for(let counter of counters){rowOffset+=counter;}}
return{rowOffset,resultString};}
getBarcodeFormat(){return BarcodeFormat$1.EAN_13;}
static determineFirstDigit(resultString,lgPatternFound){for(let d=0;d<10;d++){if(lgPatternFound===this.FIRST_DIGIT_ENCODINGS[d]){resultString=String.fromCharCode(('0'.charCodeAt(0)+d))+resultString;return resultString;}}
throw new NotFoundException();}}
EAN13Reader.FIRST_DIGIT_ENCODINGS=[0x00,0x0B,0x0D,0xE,0x13,0x19,0x1C,0x15,0x16,0x1A];class EAN8Reader extends UPCEANReader{constructor(){super();this.decodeMiddleCounters=Int32Array.from([0,0,0,0]);}
decodeMiddle(row,startRange,resultString){const counters=this.decodeMiddleCounters;counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let end=row.getSize();let rowOffset=startRange[1];for(let x=0;x<4&&rowOffset<end;x++){let bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch));for(let counter of counters){rowOffset+=counter;}}
let middleRange=UPCEANReader.findGuardPattern(row,rowOffset,true,UPCEANReader.MIDDLE_PATTERN,new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));rowOffset=middleRange[1];for(let x=0;x<4&&rowOffset<end;x++){let bestMatch=UPCEANReader.decodeDigit(row,counters,rowOffset,UPCEANReader.L_PATTERNS);resultString+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch));for(let counter of counters){rowOffset+=counter;}}
return{rowOffset,resultString};}
getBarcodeFormat(){return BarcodeFormat$1.EAN_8;}}
class UPCAReader extends UPCEANReader{constructor(){super(...arguments);this.ean13Reader=new EAN13Reader();}
getBarcodeFormat(){return BarcodeFormat$1.UPC_A;}
decode(image,hints){return this.maybeReturnResult(this.ean13Reader.decode(image));}
decodeRow(rowNumber,row,hints){return this.maybeReturnResult(this.ean13Reader.decodeRow(rowNumber,row,hints));}
decodeMiddle(row,startRange,resultString){return this.ean13Reader.decodeMiddle(row,startRange,resultString);}
maybeReturnResult(result){let text=result.getText();if(text.charAt(0)==='0'){let upcaResult=new Result(text.substring(1),null,null,result.getResultPoints(),BarcodeFormat$1.UPC_A);if(result.getResultMetadata()!=null){upcaResult.putAllMetadata(result.getResultMetadata());}
return upcaResult;}
else{throw new NotFoundException();}}
reset(){this.ean13Reader.reset();}}
class UPCEReader extends UPCEANReader{constructor(){super();this.decodeMiddleCounters=new Int32Array(4);}
decodeMiddle(row,startRange,result){const counters=this.decodeMiddleCounters.map(x=>x);counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;const end=row.getSize();let rowOffset=startRange[1];let lgPatternFound=0;for(let x=0;x<6&&rowOffset<end;x++){const bestMatch=UPCEReader.decodeDigit(row,counters,rowOffset,UPCEReader.L_AND_G_PATTERNS);result+=String.fromCharCode(('0'.charCodeAt(0)+bestMatch%10));for(let counter of counters){rowOffset+=counter;}
if(bestMatch>=10){lgPatternFound|=1<<(5-x);}}
UPCEReader.determineNumSysAndCheckDigit(new StringBuilder(result),lgPatternFound);return rowOffset;}
decodeEnd(row,endStart){return UPCEReader.findGuardPatternWithoutCounters(row,endStart,true,UPCEReader.MIDDLE_END_PATTERN);}
checkChecksum(s){return UPCEANReader.checkChecksum(UPCEReader.convertUPCEtoUPCA(s));}
static determineNumSysAndCheckDigit(resultString,lgPatternFound){for(let numSys=0;numSys<=1;numSys++){for(let d=0;d<10;d++){if(lgPatternFound===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]){resultString.insert(0,('0'+numSys));resultString.append(('0'+d));return;}}}
throw NotFoundException.getNotFoundInstance();}
getBarcodeFormat(){return BarcodeFormat$1.UPC_E;}
static convertUPCEtoUPCA(upce){const upceChars=upce.slice(1,7).split('').map(x=>x.charCodeAt(0));const result=new StringBuilder();result.append(upce.charAt(0));let lastChar=upceChars[5];switch(lastChar){case 0:case 1:case 2:result.appendChars(upceChars,0,2);result.append(lastChar);result.append('0000');result.appendChars(upceChars,2,3);break;case 3:result.appendChars(upceChars,0,3);result.append('00000');result.appendChars(upceChars,3,2);break;case 4:result.appendChars(upceChars,0,4);result.append('00000');result.append(upceChars[4]);break;default:result.appendChars(upceChars,0,5);result.append('0000');result.append(lastChar);break;}
if(upce.length>=8){result.append(upce.charAt(7));}
return result.toString();}}
UPCEReader.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]);UPCEReader.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([0x38,0x34,0x32,0x31,0x2C,0x26,0x23,0x2A,0x29,0x25]),Int32Array.from([0x07,0x0B,0x0D,0x0E,0x13,0x19,0x1C,0x15,0x16,0x1]),];class MultiFormatUPCEANReader extends OneDReader{constructor(hints){super();let possibleFormats=hints==null?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);let readers=[];if(possibleFormats!=null){if(possibleFormats.indexOf(BarcodeFormat$1.EAN_13)>-1){readers.push(new EAN13Reader());}
if(possibleFormats.indexOf(BarcodeFormat$1.UPC_A)>-1){readers.push(new UPCAReader());}
if(possibleFormats.indexOf(BarcodeFormat$1.EAN_8)>-1){readers.push(new EAN8Reader());}
if(possibleFormats.indexOf(BarcodeFormat$1.UPC_E)>-1){readers.push(new UPCEReader());}}
if(readers.length===0){readers.push(new EAN13Reader());readers.push(new UPCAReader());readers.push(new EAN8Reader());readers.push(new UPCEReader());}
this.readers=readers;}
decodeRow(rowNumber,row,hints){for(let reader of this.readers){try{const result=reader.decodeRow(rowNumber,row,hints);const ean13MayBeUPCA=result.getBarcodeFormat()===BarcodeFormat$1.EAN_13&&result.getText().charAt(0)==='0';const possibleFormats=hints==null?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);const canReturnUPCA=possibleFormats==null||possibleFormats.includes(BarcodeFormat$1.UPC_A);if(ean13MayBeUPCA&&canReturnUPCA){const rawBytes=result.getRawBytes();const resultUPCA=new Result(result.getText().substring(1),rawBytes,(rawBytes?rawBytes.length:null),result.getResultPoints(),BarcodeFormat$1.UPC_A);resultUPCA.putAllMetadata(result.getResultMetadata());return resultUPCA;}
return result;}
catch(err){}}
throw new NotFoundException();}
reset(){for(let reader of this.readers){reader.reset();}}}
class CodaBarReader extends OneDReader{constructor(){super(...arguments);this.CODA_BAR_CHAR_SET={nnnnnww:'0',nnnnwwn:'1',nnnwnnw:'2',wwnnnnn:'3',nnwnnwn:'4',wnnnnwn:'5',nwnnnnw:'6',nwnnwnn:'7',nwwnnnn:'8',wnnwnnn:'9',nnnwwnn:'-',nnwwnnn:'$',wnnnwnw:':',wnwnnnw:'/',wnwnwnn:'.',nnwwwww:'+',nnwwnwn:'A',nwnwnnw:'B',nnnwnww:'C',nnnwwwn:'D'};}
decodeRow(rowNumber,row,hints){let validRowData=this.getValidRowData(row);if(!validRowData)
throw new NotFoundException();let retStr=this.codaBarDecodeRow(validRowData.row);if(!retStr)
throw new NotFoundException();return new Result(retStr,null,0,[new ResultPoint(validRowData.left,rowNumber),new ResultPoint(validRowData.right,rowNumber)],BarcodeFormat$1.CODABAR,new Date().getTime());}
getValidRowData(row){let booleanArr=row.toArray();let startIndex=booleanArr.indexOf(true);if(startIndex===-1)
return null;let lastIndex=booleanArr.lastIndexOf(true);if(lastIndex<=startIndex)
return null;booleanArr=booleanArr.slice(startIndex,lastIndex+1);let result=[];let lastBit=booleanArr[0];let bitLength=1;for(let i=1;i<booleanArr.length;i++){if(booleanArr[i]===lastBit){bitLength++;}
else{lastBit=booleanArr[i];result.push(bitLength);bitLength=1;}}
result.push(bitLength);if(result.length<23&&(result.length+1)%8!==0)
return null;return{row:result,left:startIndex,right:lastIndex};}
codaBarDecodeRow(row){const code=[];const barThreshold=Math.ceil(row.reduce((pre,item)=>(pre+item)/2,0));while(row.length>0){const seg=row.splice(0,8).splice(0,7);const key=seg.map(len=>(len<barThreshold?'n':'w')).join('');if(this.CODA_BAR_CHAR_SET[key]===undefined)
return null;code.push(this.CODA_BAR_CHAR_SET[key]);}
let strCode=code.join('');if(this.validCodaBarString(strCode))
return strCode;return null;}
validCodaBarString(src){let reg=/^[A-D].{1,}[A-D]$/;return reg.test(src);}}
class AbstractRSSReader extends OneDReader{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(counters,finderPatterns){for(let value=0;value<finderPatterns.length;value++){if(OneDReader.patternMatchVariance(counters,finderPatterns[value],AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE)<AbstractRSSReader.MAX_AVG_VARIANCE){return value;}}
throw new NotFoundException();}
static count(array){return MathUtils.sum(new Int32Array(array));}
static increment(array,errors){let index=0;let biggestError=errors[0];for(let i=1;i<array.length;i++){if(errors[i]>biggestError){biggestError=errors[i];index=i;}}
array[index]++;}
static decrement(array,errors){let index=0;let biggestError=errors[0];for(let i=1;i<array.length;i++){if(errors[i]<biggestError){biggestError=errors[i];index=i;}}
array[index]--;}
static isFinderPattern(counters){let firstTwoSum=counters[0]+counters[1];let sum=firstTwoSum+counters[2]+counters[3];let ratio=firstTwoSum/sum;if(ratio>=AbstractRSSReader.MIN_FINDER_PATTERN_RATIO&&ratio<=AbstractRSSReader.MAX_FINDER_PATTERN_RATIO){let minCounter=Number.MAX_SAFE_INTEGER;let maxCounter=Number.MIN_SAFE_INTEGER;for(let counter of counters){if(counter>maxCounter){maxCounter=counter;}
if(counter<minCounter){minCounter=counter;}}
return maxCounter<10*minCounter;}
return false;}}
AbstractRSSReader.MAX_AVG_VARIANCE=0.2;AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE=0.45;AbstractRSSReader.MIN_FINDER_PATTERN_RATIO=9.5/12.0;AbstractRSSReader.MAX_FINDER_PATTERN_RATIO=12.5/14.0;class DataCharacter{constructor(value,checksumPortion){this.value=value;this.checksumPortion=checksumPortion;}
getValue(){return this.value;}
getChecksumPortion(){return this.checksumPortion;}
toString(){return this.value+'('+this.checksumPortion+')';}
equals(o){if(!(o instanceof DataCharacter)){return false;}
const that=o;return this.value===that.value&&this.checksumPortion===that.checksumPortion;}
hashCode(){return this.value^this.checksumPortion;}}
class FinderPattern{constructor(value,startEnd,start,end,rowNumber){this.value=value;this.startEnd=startEnd;this.value=value;this.startEnd=startEnd;this.resultPoints=new Array();this.resultPoints.push(new ResultPoint(start,rowNumber));this.resultPoints.push(new ResultPoint(end,rowNumber));}
getValue(){return this.value;}
getStartEnd(){return this.startEnd;}
getResultPoints(){return this.resultPoints;}
equals(o){if(!(o instanceof FinderPattern)){return false;}
const that=o;return this.value===that.value;}
hashCode(){return this.value;}}
class RSSUtils{constructor(){}
static getRSSvalue(widths,maxWidth,noNarrow){let n=0;for(let width of widths){n+=width;}
let val=0;let narrowMask=0;let elements=widths.length;for(let bar=0;bar<elements-1;bar++){let elmWidth;for(elmWidth=1,narrowMask|=1<<bar;elmWidth<widths[bar];elmWidth++,narrowMask&=~(1<<bar)){let subVal=RSSUtils.combins(n-elmWidth-1,elements-bar-2);if(noNarrow&&(narrowMask===0)&&(n-elmWidth-(elements-bar-1)>=elements-bar-1)){subVal-=RSSUtils.combins(n-elmWidth-(elements-bar),elements-bar-2);}
if(elements-bar-1>1){let lessVal=0;for(let mxwElement=n-elmWidth-(elements-bar-2);mxwElement>maxWidth;mxwElement--){lessVal+=RSSUtils.combins(n-elmWidth-mxwElement-1,elements-bar-3);}
subVal-=lessVal*(elements-1-bar);}
else if(n-elmWidth>maxWidth){subVal--;}
val+=subVal;}
n-=elmWidth;}
return val;}
static combins(n,r){let maxDenom;let minDenom;if(n-r>r){minDenom=r;maxDenom=n-r;}
else{minDenom=n-r;maxDenom=r;}
let val=1;let j=1;for(let i=n;i>maxDenom;i--){val*=i;if(j<=minDenom){val/=j;j++;}}
while((j<=minDenom)){val/=j;j++;}
return val;}}
class BitArrayBuilder{static buildBitArray(pairs){let charNumber=pairs.length*2-1;if(pairs[pairs.length-1].getRightChar()==null){charNumber-=1;}
let size=12*charNumber;let binary=new BitArray(size);let accPos=0;let firstPair=pairs[0];let firstValue=firstPair.getRightChar().getValue();for(let i=11;i>=0;--i){if((firstValue&(1<<i))!==0){binary.set(accPos);}
accPos++;}
for(let i=1;i<pairs.length;++i){let currentPair=pairs[i];let leftValue=currentPair.getLeftChar().getValue();for(let j=11;j>=0;--j){if((leftValue&(1<<j))!==0){binary.set(accPos);}
accPos++;}
if(currentPair.getRightChar()!==null){let rightValue=currentPair.getRightChar().getValue();for(let j=11;j>=0;--j){if((rightValue&(1<<j))!==0){binary.set(accPos);}
accPos++;}}}
return binary;}}
class BlockParsedResult{constructor(finished,decodedInformation){if(decodedInformation){this.decodedInformation=null;}
else{this.finished=finished;this.decodedInformation=decodedInformation;}}
getDecodedInformation(){return this.decodedInformation;}
isFinished(){return this.finished;}}
class DecodedObject{constructor(newPosition){this.newPosition=newPosition;}
getNewPosition(){return this.newPosition;}}
class DecodedChar extends DecodedObject{constructor(newPosition,value){super(newPosition);this.value=value;}
getValue(){return this.value;}
isFNC1(){return this.value===DecodedChar.FNC1;}}
DecodedChar.FNC1='$';class DecodedInformation extends DecodedObject{constructor(newPosition,newString,remainingValue){super(newPosition);if(remainingValue){this.remaining=true;this.remainingValue=this.remainingValue;}
else{this.remaining=false;this.remainingValue=0;}
this.newString=newString;}
getNewString(){return this.newString;}
isRemaining(){return this.remaining;}
getRemainingValue(){return this.remainingValue;}}
class DecodedNumeric extends DecodedObject{constructor(newPosition,firstDigit,secondDigit){super(newPosition);if(firstDigit<0||firstDigit>10||secondDigit<0||secondDigit>10){throw new FormatException();}
this.firstDigit=firstDigit;this.secondDigit=secondDigit;}
getFirstDigit(){return this.firstDigit;}
getSecondDigit(){return this.secondDigit;}
getValue(){return this.firstDigit*10+this.secondDigit;}
isFirstDigitFNC1(){return this.firstDigit===DecodedNumeric.FNC1;}
isSecondDigitFNC1(){return this.secondDigit===DecodedNumeric.FNC1;}
isAnyFNC1(){return this.firstDigit===DecodedNumeric.FNC1||this.secondDigit===DecodedNumeric.FNC1;}}
DecodedNumeric.FNC1=10;class FieldParser{constructor(){}
static parseFieldsInGeneralPurpose(rawInformation){if(!rawInformation){return null;}
if(rawInformation.length<2){throw new NotFoundException();}
let firstTwoDigits=rawInformation.substring(0,2);for(let dataLength of FieldParser.TWO_DIGIT_DATA_LENGTH){if(dataLength[0]===firstTwoDigits){if(dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(2,dataLength[2],rawInformation);}
return FieldParser.processFixedAI(2,dataLength[1],rawInformation);}}
if(rawInformation.length<3){throw new NotFoundException();}
let firstThreeDigits=rawInformation.substring(0,3);for(let dataLength of FieldParser.THREE_DIGIT_DATA_LENGTH){if(dataLength[0]===firstThreeDigits){if(dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(3,dataLength[2],rawInformation);}
return FieldParser.processFixedAI(3,dataLength[1],rawInformation);}}
for(let dataLength of FieldParser.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH){if(dataLength[0]===firstThreeDigits){if(dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(4,dataLength[2],rawInformation);}
return FieldParser.processFixedAI(4,dataLength[1],rawInformation);}}
if(rawInformation.length<4){throw new NotFoundException();}
let firstFourDigits=rawInformation.substring(0,4);for(let dataLength of FieldParser.FOUR_DIGIT_DATA_LENGTH){if(dataLength[0]===firstFourDigits){if(dataLength[1]===FieldParser.VARIABLE_LENGTH){return FieldParser.processVariableAI(4,dataLength[2],rawInformation);}
return FieldParser.processFixedAI(4,dataLength[1],rawInformation);}}
throw new NotFoundException();}
static processFixedAI(aiSize,fieldSize,rawInformation){if(rawInformation.length<aiSize){throw new NotFoundException();}
let ai=rawInformation.substring(0,aiSize);if(rawInformation.length<aiSize+fieldSize){throw new NotFoundException();}
let field=rawInformation.substring(aiSize,aiSize+fieldSize);let remaining=rawInformation.substring(aiSize+fieldSize);let result='('+ai+')'+field;let parsedAI=FieldParser.parseFieldsInGeneralPurpose(remaining);return parsedAI==null?result:result+parsedAI;}
static processVariableAI(aiSize,variableFieldSize,rawInformation){let ai=rawInformation.substring(0,aiSize);let maxSize;if(rawInformation.length<aiSize+variableFieldSize){maxSize=rawInformation.length;}
else{maxSize=aiSize+variableFieldSize;}
let field=rawInformation.substring(aiSize,maxSize);let remaining=rawInformation.substring(maxSize);let result='('+ai+')'+field;let parsedAI=FieldParser.parseFieldsInGeneralPurpose(remaining);return parsedAI==null?result:result+parsedAI;}}
FieldParser.VARIABLE_LENGTH=[];FieldParser.TWO_DIGIT_DATA_LENGTH=[['00',18],['01',14],['02',14],['10',FieldParser.VARIABLE_LENGTH,20],['11',6],['12',6],['13',6],['15',6],['17',6],['20',2],['21',FieldParser.VARIABLE_LENGTH,20],['22',FieldParser.VARIABLE_LENGTH,29],['30',FieldParser.VARIABLE_LENGTH,8],['37',FieldParser.VARIABLE_LENGTH,8],['90',FieldParser.VARIABLE_LENGTH,30],['91',FieldParser.VARIABLE_LENGTH,30],['92',FieldParser.VARIABLE_LENGTH,30],['93',FieldParser.VARIABLE_LENGTH,30],['94',FieldParser.VARIABLE_LENGTH,30],['95',FieldParser.VARIABLE_LENGTH,30],['96',FieldParser.VARIABLE_LENGTH,30],['97',FieldParser.VARIABLE_LENGTH,3],['98',FieldParser.VARIABLE_LENGTH,30],['99',FieldParser.VARIABLE_LENGTH,30],];FieldParser.THREE_DIGIT_DATA_LENGTH=[['240',FieldParser.VARIABLE_LENGTH,30],['241',FieldParser.VARIABLE_LENGTH,30],['242',FieldParser.VARIABLE_LENGTH,6],['250',FieldParser.VARIABLE_LENGTH,30],['251',FieldParser.VARIABLE_LENGTH,30],['253',FieldParser.VARIABLE_LENGTH,17],['254',FieldParser.VARIABLE_LENGTH,20],['400',FieldParser.VARIABLE_LENGTH,30],['401',FieldParser.VARIABLE_LENGTH,30],['402',17],['403',FieldParser.VARIABLE_LENGTH,30],['410',13],['411',13],['412',13],['413',13],['414',13],['420',FieldParser.VARIABLE_LENGTH,20],['421',FieldParser.VARIABLE_LENGTH,15],['422',3],['423',FieldParser.VARIABLE_LENGTH,15],['424',3],['425',3],['426',3],];FieldParser.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',FieldParser.VARIABLE_LENGTH,15],['391',FieldParser.VARIABLE_LENGTH,18],['392',FieldParser.VARIABLE_LENGTH,15],['393',FieldParser.VARIABLE_LENGTH,18],['703',FieldParser.VARIABLE_LENGTH,30],];FieldParser.FOUR_DIGIT_DATA_LENGTH=[['7001',13],['7002',FieldParser.VARIABLE_LENGTH,30],['7003',10],['8001',14],['8002',FieldParser.VARIABLE_LENGTH,20],['8003',FieldParser.VARIABLE_LENGTH,30],['8004',FieldParser.VARIABLE_LENGTH,30],['8005',6],['8006',18],['8007',FieldParser.VARIABLE_LENGTH,30],['8008',FieldParser.VARIABLE_LENGTH,12],['8018',18],['8020',FieldParser.VARIABLE_LENGTH,25],['8100',6],['8101',10],['8102',2],['8110',FieldParser.VARIABLE_LENGTH,70],['8200',FieldParser.VARIABLE_LENGTH,70],];class GeneralAppIdDecoder{constructor(information){this.buffer=new StringBuilder();this.information=information;}
decodeAllCodes(buff,initialPosition){let currentPosition=initialPosition;let remaining=null;do{let info=this.decodeGeneralPurposeField(currentPosition,remaining);let parsedFields=FieldParser.parseFieldsInGeneralPurpose(info.getNewString());if(parsedFields!=null){buff.append(parsedFields);}
if(info.isRemaining()){remaining=''+info.getRemainingValue();}
else{remaining=null;}
if(currentPosition===info.getNewPosition()){break;}
currentPosition=info.getNewPosition();}while(true);return buff.toString();}
isStillNumeric(pos){if(pos+7>this.information.getSize()){return pos+4<=this.information.getSize();}
for(let i=pos;i<pos+3;++i){if(this.information.get(i)){return true;}}
return this.information.get(pos+3);}
decodeNumeric(pos){if(pos+7>this.information.getSize()){let numeric=this.extractNumericValueFromBitArray(pos,4);if(numeric===0){return new DecodedNumeric(this.information.getSize(),DecodedNumeric.FNC1,DecodedNumeric.FNC1);}
return new DecodedNumeric(this.information.getSize(),numeric-1,DecodedNumeric.FNC1);}
let numeric=this.extractNumericValueFromBitArray(pos,7);let digit1=(numeric-8)/11;let digit2=(numeric-8)%11;return new DecodedNumeric(pos+7,digit1,digit2);}
extractNumericValueFromBitArray(pos,bits){return GeneralAppIdDecoder.extractNumericValueFromBitArray(this.information,pos,bits);}
static extractNumericValueFromBitArray(information,pos,bits){let value=0;for(let i=0;i<bits;++i){if(information.get(pos+i)){value|=1<<(bits-i-1);}}
return value;}
decodeGeneralPurposeField(pos,remaining){this.buffer.setLengthToZero();if(remaining!=null){this.buffer.append(remaining);}
this.current.setPosition(pos);let lastDecoded=this.parseBlocks();if(lastDecoded!=null&&lastDecoded.isRemaining()){return new DecodedInformation(this.current.getPosition(),this.buffer.toString(),lastDecoded.getRemainingValue());}
return new DecodedInformation(this.current.getPosition(),this.buffer.toString());}
parseBlocks(){let isFinished;let result;do{let initialPosition=this.current.getPosition();if(this.current.isAlpha()){result=this.parseAlphaBlock();isFinished=result.isFinished();}
else if(this.current.isIsoIec646()){result=this.parseIsoIec646Block();isFinished=result.isFinished();}
else{result=this.parseNumericBlock();isFinished=result.isFinished();}
let positionChanged=initialPosition!==this.current.getPosition();if(!positionChanged&&!isFinished){break;}}while(!isFinished);return result.getDecodedInformation();}
parseNumericBlock(){while(this.isStillNumeric(this.current.getPosition())){let numeric=this.decodeNumeric(this.current.getPosition());this.current.setPosition(numeric.getNewPosition());if(numeric.isFirstDigitFNC1()){let information;if(numeric.isSecondDigitFNC1()){information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());}
else{information=new DecodedInformation(this.current.getPosition(),this.buffer.toString(),numeric.getSecondDigit());}
return new BlockParsedResult(true,information);}
this.buffer.append(numeric.getFirstDigit());if(numeric.isSecondDigitFNC1()){let information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,information);}
this.buffer.append(numeric.getSecondDigit());}
if(this.isNumericToAlphaNumericLatch(this.current.getPosition())){this.current.setAlpha();this.current.incrementPosition(4);}
return new BlockParsedResult(false);}
parseIsoIec646Block(){while(this.isStillIsoIec646(this.current.getPosition())){let iso=this.decodeIsoIec646(this.current.getPosition());this.current.setPosition(iso.getNewPosition());if(iso.isFNC1()){let information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,information);}
this.buffer.append(iso.getValue());}
if(this.isAlphaOr646ToNumericLatch(this.current.getPosition())){this.current.incrementPosition(3);this.current.setNumeric();}
else if(this.isAlphaTo646ToAlphaLatch(this.current.getPosition())){if(this.current.getPosition()+5<this.information.getSize()){this.current.incrementPosition(5);}
else{this.current.setPosition(this.information.getSize());}
this.current.setAlpha();}
return new BlockParsedResult(false);}
parseAlphaBlock(){while(this.isStillAlpha(this.current.getPosition())){let alpha=this.decodeAlphanumeric(this.current.getPosition());this.current.setPosition(alpha.getNewPosition());if(alpha.isFNC1()){let information=new DecodedInformation(this.current.getPosition(),this.buffer.toString());return new BlockParsedResult(true,information);}
this.buffer.append(alpha.getValue());}
if(this.isAlphaOr646ToNumericLatch(this.current.getPosition())){this.current.incrementPosition(3);this.current.setNumeric();}
else if(this.isAlphaTo646ToAlphaLatch(this.current.getPosition())){if(this.current.getPosition()+5<this.information.getSize()){this.current.incrementPosition(5);}
else{this.current.setPosition(this.information.getSize());}
this.current.setIsoIec646();}
return new BlockParsedResult(false);}
isStillIsoIec646(pos){if(pos+5>this.information.getSize()){return false;}
let fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue>=5&&fiveBitValue<16){return true;}
if(pos+7>this.information.getSize()){return false;}
let sevenBitValue=this.extractNumericValueFromBitArray(pos,7);if(sevenBitValue>=64&&sevenBitValue<116){return true;}
if(pos+8>this.information.getSize()){return false;}
let eightBitValue=this.extractNumericValueFromBitArray(pos,8);return eightBitValue>=232&&eightBitValue<253;}
decodeIsoIec646(pos){let fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue===15){return new DecodedChar(pos+5,DecodedChar.FNC1);}
if(fiveBitValue>=5&&fiveBitValue<15){return new DecodedChar(pos+5,('0'+(fiveBitValue-5)));}
let sevenBitValue=this.extractNumericValueFromBitArray(pos,7);if(sevenBitValue>=64&&sevenBitValue<90){return new DecodedChar(pos+7,(''+(sevenBitValue+1)));}
if(sevenBitValue>=90&&sevenBitValue<116){return new DecodedChar(pos+7,(''+(sevenBitValue+7)));}
let eightBitValue=this.extractNumericValueFromBitArray(pos,8);let c;switch(eightBitValue){case 232:c='!';break;case 233:c='"';break;case 234:c='%';break;case 235:c='&';break;case 236:c='\'';break;case 237:c='(';break;case 238:c=')';break;case 239:c='*';break;case 240:c='+';break;case 241:c=',';break;case 242:c='-';break;case 243:c='.';break;case 244:c='/';break;case 245:c=':';break;case 246:c=';';break;case 247:c='<';break;case 248:c='=';break;case 249:c='>';break;case 250:c='?';break;case 251:c='_';break;case 252:c=' ';break;default:throw new FormatException();}
return new DecodedChar(pos+8,c);}
isStillAlpha(pos){if(pos+5>this.information.getSize()){return false;}
let fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue>=5&&fiveBitValue<16){return true;}
if(pos+6>this.information.getSize()){return false;}
let sixBitValue=this.extractNumericValueFromBitArray(pos,6);return sixBitValue>=16&&sixBitValue<63;}
decodeAlphanumeric(pos){let fiveBitValue=this.extractNumericValueFromBitArray(pos,5);if(fiveBitValue===15){return new DecodedChar(pos+5,DecodedChar.FNC1);}
if(fiveBitValue>=5&&fiveBitValue<15){return new DecodedChar(pos+5,('0'+(fiveBitValue-5)));}
let sixBitValue=this.extractNumericValueFromBitArray(pos,6);if(sixBitValue>=32&&sixBitValue<58){return new DecodedChar(pos+6,(''+(sixBitValue+33)));}
let c;switch(sixBitValue){case 58:c='*';break;case 59:c=',';break;case 60:c='-';break;case 61:c='.';break;case 62:c='/';break;default:throw new IllegalStateException('Decoding invalid alphanumeric value: '+sixBitValue);}
return new DecodedChar(pos+6,c);}
isAlphaTo646ToAlphaLatch(pos){if(pos+1>this.information.getSize()){return false;}
for(let i=0;i<5&&i+pos<this.information.getSize();++i){if(i===2){if(!this.information.get(pos+2)){return false;}}
else if(this.information.get(pos+i)){return false;}}
return true;}
isAlphaOr646ToNumericLatch(pos){if(pos+3>this.information.getSize()){return false;}
for(let i=pos;i<pos+3;++i){if(this.information.get(i)){return false;}}
return true;}
isNumericToAlphaNumericLatch(pos){if(pos+1>this.information.getSize()){return false;}
for(let i=0;i<4&&i+pos<this.information.getSize();++i){if(this.information.get(pos+i)){return false;}}
return true;}}
class AbstractExpandedDecoder{constructor(information){this.information=information;this.generalDecoder=new GeneralAppIdDecoder(information);}
getInformation(){return this.information;}
getGeneralDecoder(){return this.generalDecoder;}}
class AI01decoder extends AbstractExpandedDecoder{constructor(information){super(information);}
encodeCompressedGtin(buf,currentPos){buf.append('(01)');let initialPosition=buf.length();buf.append('9');this.encodeCompressedGtinWithoutAI(buf,currentPos,initialPosition);}
encodeCompressedGtinWithoutAI(buf,currentPos,initialBufferPosition){for(let i=0;i<4;++i){let currentBlock=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos+10*i,10);if(currentBlock/100===0){buf.append('0');}
if(currentBlock/10===0){buf.append('0');}
buf.append(currentBlock);}
AI01decoder.appendCheckDigit(buf,initialBufferPosition);}
static appendCheckDigit(buf,currentPos){let checkDigit=0;for(let i=0;i<13;i++){let digit=buf.charAt(i+currentPos).charCodeAt(0)-'0'.charCodeAt(0);checkDigit+=(i&0x01)===0?3*digit:digit;}
checkDigit=10-(checkDigit%10);if(checkDigit===10){checkDigit=0;}
buf.append(checkDigit);}}
AI01decoder.GTIN_SIZE=40;class AI01AndOtherAIs extends AI01decoder{constructor(information){super(information);}
parseInformation(){let buff=new StringBuilder();buff.append('(01)');let initialGtinPosition=buff.length();let firstGtinDigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01AndOtherAIs.HEADER_SIZE,4);buff.append(firstGtinDigit);this.encodeCompressedGtinWithoutAI(buff,AI01AndOtherAIs.HEADER_SIZE+4,initialGtinPosition);return this.getGeneralDecoder().decodeAllCodes(buff,AI01AndOtherAIs.HEADER_SIZE+44);}}
AI01AndOtherAIs.HEADER_SIZE=1+1+2;class AnyAIDecoder extends AbstractExpandedDecoder{constructor(information){super(information);}
parseInformation(){let buf=new StringBuilder();return this.getGeneralDecoder().decodeAllCodes(buf,AnyAIDecoder.HEADER_SIZE);}}
AnyAIDecoder.HEADER_SIZE=2+1+2;class AI01weightDecoder extends AI01decoder{constructor(information){super(information);}
encodeCompressedWeight(buf,currentPos,weightSize){let originalWeightNumeric=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos,weightSize);this.addWeightCode(buf,originalWeightNumeric);let weightNumeric=this.checkWeight(originalWeightNumeric);let currentDivisor=100000;for(let i=0;i<5;++i){if(weightNumeric/currentDivisor===0){buf.append('0');}
currentDivisor/=10;}
buf.append(weightNumeric);}}
class AI013x0xDecoder extends AI01weightDecoder{constructor(information){super(information);}
parseInformation(){if(this.getInformation().getSize()!==AI013x0xDecoder.HEADER_SIZE+
AI01weightDecoder.GTIN_SIZE+
AI013x0xDecoder.WEIGHT_SIZE){throw new NotFoundException();}
let buf=new StringBuilder();this.encodeCompressedGtin(buf,AI013x0xDecoder.HEADER_SIZE);this.encodeCompressedWeight(buf,AI013x0xDecoder.HEADER_SIZE+AI01weightDecoder.GTIN_SIZE,AI013x0xDecoder.WEIGHT_SIZE);return buf.toString();}}
AI013x0xDecoder.HEADER_SIZE=4+1;AI013x0xDecoder.WEIGHT_SIZE=15;class AI013103decoder extends AI013x0xDecoder{constructor(information){super(information);}
addWeightCode(buf,weight){buf.append('(3103)');}
checkWeight(weight){return weight;}}
class AI01320xDecoder extends AI013x0xDecoder{constructor(information){super(information);}
addWeightCode(buf,weight){if(weight<10000){buf.append('(3202)');}
else{buf.append('(3203)');}}
checkWeight(weight){if(weight<10000){return weight;}
return weight-10000;}}
class AI01392xDecoder extends AI01decoder{constructor(information){super(information);}
parseInformation(){if(this.getInformation().getSize()<AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE){throw new NotFoundException();}
let buf=new StringBuilder();this.encodeCompressedGtin(buf,AI01392xDecoder.HEADER_SIZE);let lastAIdigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE,AI01392xDecoder.LAST_DIGIT_SIZE);buf.append('(392');buf.append(lastAIdigit);buf.append(')');let decodedInformation=this.getGeneralDecoder().decodeGeneralPurposeField(AI01392xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE+AI01392xDecoder.LAST_DIGIT_SIZE,null);buf.append(decodedInformation.getNewString());return buf.toString();}}
AI01392xDecoder.HEADER_SIZE=5+1+2;AI01392xDecoder.LAST_DIGIT_SIZE=2;class AI01393xDecoder extends AI01decoder{constructor(information){super(information);}
parseInformation(){if(this.getInformation().getSize()<AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE){throw new NotFoundException();}
let buf=new StringBuilder();this.encodeCompressedGtin(buf,AI01393xDecoder.HEADER_SIZE);let lastAIdigit=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE+AI01decoder.GTIN_SIZE,AI01393xDecoder.LAST_DIGIT_SIZE);buf.append('(393');buf.append(lastAIdigit);buf.append(')');let firstThreeDigits=this.getGeneralDecoder().extractNumericValueFromBitArray(AI01393xDecoder.HEADER_SIZE+
AI01decoder.GTIN_SIZE+
AI01393xDecoder.LAST_DIGIT_SIZE,AI01393xDecoder.FIRST_THREE_DIGITS_SIZE);if(firstThreeDigits/100===0){buf.append('0');}
if(firstThreeDigits/10===0){buf.append('0');}
buf.append(firstThreeDigits);let generalInformation=this.getGeneralDecoder().decodeGeneralPurposeField(AI01393xDecoder.HEADER_SIZE+
AI01decoder.GTIN_SIZE+
AI01393xDecoder.LAST_DIGIT_SIZE+
AI01393xDecoder.FIRST_THREE_DIGITS_SIZE,null);buf.append(generalInformation.getNewString());return buf.toString();}}
AI01393xDecoder.HEADER_SIZE=5+1+2;AI01393xDecoder.LAST_DIGIT_SIZE=2;AI01393xDecoder.FIRST_THREE_DIGITS_SIZE=10;class AI013x0x1xDecoder extends AI01weightDecoder{constructor(information,firstAIdigits,dateCode){super(information);this.dateCode=dateCode;this.firstAIdigits=firstAIdigits;}
parseInformation(){if(this.getInformation().getSize()!==AI013x0x1xDecoder.HEADER_SIZE+
AI013x0x1xDecoder.GTIN_SIZE+
AI013x0x1xDecoder.WEIGHT_SIZE+
AI013x0x1xDecoder.DATE_SIZE){throw new NotFoundException();}
let buf=new StringBuilder();this.encodeCompressedGtin(buf,AI013x0x1xDecoder.HEADER_SIZE);this.encodeCompressedWeight(buf,AI013x0x1xDecoder.HEADER_SIZE+AI013x0x1xDecoder.GTIN_SIZE,AI013x0x1xDecoder.WEIGHT_SIZE);this.encodeCompressedDate(buf,AI013x0x1xDecoder.HEADER_SIZE+
AI013x0x1xDecoder.GTIN_SIZE+
AI013x0x1xDecoder.WEIGHT_SIZE);return buf.toString();}
encodeCompressedDate(buf,currentPos){let numericDate=this.getGeneralDecoder().extractNumericValueFromBitArray(currentPos,AI013x0x1xDecoder.DATE_SIZE);if(numericDate===38400){return;}
buf.append('(');buf.append(this.dateCode);buf.append(')');let day=numericDate%32;numericDate/=32;let month=(numericDate%12)+1;numericDate/=12;let year=numericDate;if(year/10===0){buf.append('0');}
buf.append(year);if(month/10===0){buf.append('0');}
buf.append(month);if(day/10===0){buf.append('0');}
buf.append(day);}
addWeightCode(buf,weight){buf.append('(');buf.append(this.firstAIdigits);buf.append(weight/100000);buf.append(')');}
checkWeight(weight){return weight%100000;}}
AI013x0x1xDecoder.HEADER_SIZE=7+1;AI013x0x1xDecoder.WEIGHT_SIZE=20;AI013x0x1xDecoder.DATE_SIZE=16;function createDecoder(information){try{if(information.get(1)){return new AI01AndOtherAIs(information);}
if(!information.get(2)){return new AnyAIDecoder(information);}
let fourBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,4);switch(fourBitEncodationMethod){case 4:return new AI013103decoder(information);case 5:return new AI01320xDecoder(information);}
let fiveBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,5);switch(fiveBitEncodationMethod){case 12:return new AI01392xDecoder(information);case 13:return new AI01393xDecoder(information);}
let sevenBitEncodationMethod=GeneralAppIdDecoder.extractNumericValueFromBitArray(information,1,7);switch(sevenBitEncodationMethod){case 56:return new AI013x0x1xDecoder(information,'310','11');case 57:return new AI013x0x1xDecoder(information,'320','11');case 58:return new AI013x0x1xDecoder(information,'310','13');case 59:return new AI013x0x1xDecoder(information,'320','13');case 60:return new AI013x0x1xDecoder(information,'310','15');case 61:return new AI013x0x1xDecoder(information,'320','15');case 62:return new AI013x0x1xDecoder(information,'310','17');case 63:return new AI013x0x1xDecoder(information,'320','17');}}
catch(e){console.log(e);throw new IllegalStateException('unknown decoder: '+information);}}
class ExpandedPair{constructor(leftChar,rightChar,finderPatter,mayBeLast){this.leftchar=leftChar;this.rightchar=rightChar;this.finderpattern=finderPatter;this.maybeLast=mayBeLast;}
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(o1,o2){if(!(o1 instanceof ExpandedPair)){return false;}
return ExpandedPair.equalsOrNull(o1.leftchar,o2.leftchar)&&ExpandedPair.equalsOrNull(o1.rightchar,o2.rightchar)&&ExpandedPair.equalsOrNull(o1.finderpattern,o2.finderpattern);}
static equalsOrNull(o1,o2){return o1===null?o2===null:ExpandedPair.equals(o1,o2);}
hashCode(){let value=this.leftchar.getValue()^this.rightchar.getValue()^this.finderpattern.getValue();return value;}}
class ExpandedRow{constructor(pairs,rowNumber,wasReversed){this.pairs=pairs;this.rowNumber=rowNumber;this.wasReversed=wasReversed;}
getPairs(){return this.pairs;}
getRowNumber(){return this.rowNumber;}
isReversed(){return this.wasReversed;}
isEquivalent(otherPairs){return this.checkEqualitity(this,otherPairs);}
toString(){return'{ '+this.pairs+' }';}
equals(o1,o2){if(!(o1 instanceof ExpandedRow)){return false;}
return this.checkEqualitity(o1,o2)&&o1.wasReversed===o2.wasReversed;}
checkEqualitity(pair1,pair2){if(!pair1||!pair2)
return;let result;pair1.forEach((e1,i)=>{pair2.forEach(e2=>{if(e1.getLeftChar().getValue()===e2.getLeftChar().getValue()&&e1.getRightChar().getValue()===e2.getRightChar().getValue()&&e1.getFinderPatter().getValue()===e2.getFinderPatter().getValue()){result=true;}});});return result;}}
class RSSExpandedReader extends AbstractRSSReader{constructor(){super(...arguments);this.pairs=new Array(RSSExpandedReader.MAX_PAIRS);this.rows=new Array();this.startEnd=[2];}
decodeRow(rowNumber,row,hints){this.pairs.length=0;this.startFromEven=false;try{return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber,row));}
catch(e){}
this.pairs.length=0;this.startFromEven=true;return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber,row));}
reset(){this.pairs.length=0;this.rows.length=0;}
decodeRow2pairs(rowNumber,row){let done=false;while(!done){try{this.pairs.push(this.retrieveNextPair(row,this.pairs,rowNumber));}
catch(error){if(error instanceof NotFoundException){if(!this.pairs.length){throw new NotFoundException();}
done=true;}}}
if(this.checkChecksum()){return this.pairs;}
let tryStackedDecode;if(this.rows.length){tryStackedDecode=true;}
else{tryStackedDecode=false;}
this.storeRow(rowNumber,false);if(tryStackedDecode){let ps=this.checkRowsBoolean(false);if(ps!=null){return ps;}
ps=this.checkRowsBoolean(true);if(ps!=null){return ps;}}
throw new NotFoundException();}
checkRowsBoolean(reverse){if(this.rows.length>25){this.rows.length=0;return null;}
this.pairs.length=0;if(reverse){this.rows=this.rows.reverse();}
let ps=null;try{ps=this.checkRows(new Array(),0);}
catch(e){console.log(e);}
if(reverse){this.rows=this.rows.reverse();}
return ps;}
checkRows(collectedRows,currentRow){for(let i=currentRow;i<this.rows.length;i++){let row=this.rows[i];this.pairs.length=0;for(let collectedRow of collectedRows){this.pairs.push(collectedRow.getPairs());}
this.pairs.push(row.getPairs());if(!RSSExpandedReader.isValidSequence(this.pairs)){continue;}
if(this.checkChecksum()){return this.pairs;}
let rs=new Array(collectedRows);rs.push(row);try{return this.checkRows(rs,i+1);}
catch(e){console.log(e);}}
throw new NotFoundException();}
static isValidSequence(pairs){for(let sequence of RSSExpandedReader.FINDER_PATTERN_SEQUENCES){if(pairs.length>sequence.length){continue;}
let stop=true;for(let j=0;j<pairs.length;j++){if(pairs[j].getFinderPattern().getValue()!==sequence[j]){stop=false;break;}}
if(stop){return true;}}
return false;}
storeRow(rowNumber,wasReversed){let insertPos=0;let prevIsSame=false;let nextIsSame=false;while(insertPos<this.rows.length){let erow=this.rows[insertPos];if(erow.getRowNumber()>rowNumber){nextIsSame=erow.isEquivalent(this.pairs);break;}
prevIsSame=erow.isEquivalent(this.pairs);insertPos++;}
if(nextIsSame||prevIsSame){return;}
if(RSSExpandedReader.isPartialRow(this.pairs,this.rows)){return;}
this.rows.push(insertPos,new ExpandedRow(this.pairs,rowNumber,wasReversed));this.removePartialRows(this.pairs,this.rows);}
removePartialRows(pairs,rows){for(let row of rows){if(row.getPairs().length===pairs.length){continue;}
for(let p of row.getPairs()){for(let pp of pairs){if(ExpandedPair.equals(p,pp)){break;}}}}}
static isPartialRow(pairs,rows){for(let r of rows){let allFound=true;for(let p of pairs){let found=false;for(let pp of r.getPairs()){if(p.equals(pp)){found=true;break;}}
if(!found){allFound=false;break;}}
if(allFound){return true;}}
return false;}
getRows(){return this.rows;}
static constructResult(pairs){let binary=BitArrayBuilder.buildBitArray(pairs);let decoder=createDecoder(binary);let resultingString=decoder.parseInformation();let firstPoints=pairs[0].getFinderPattern().getResultPoints();let lastPoints=pairs[pairs.length-1].getFinderPattern().getResultPoints();let points=[firstPoints[0],firstPoints[1],lastPoints[0],lastPoints[1]];return new Result(resultingString,null,null,points,BarcodeFormat$1.RSS_EXPANDED,null);}
checkChecksum(){let firstPair=this.pairs.get(0);let checkCharacter=firstPair.getLeftChar();let firstCharacter=firstPair.getRightChar();if(firstCharacter===null){return false;}
let checksum=firstCharacter.getChecksumPortion();let s=2;for(let i=1;i<this.pairs.size();++i){let currentPair=this.pairs.get(i);checksum+=currentPair.getLeftChar().getChecksumPortion();s++;let currentRightChar=currentPair.getRightChar();if(currentRightChar!=null){checksum+=currentRightChar.getChecksumPortion();s++;}}
checksum%=211;let checkCharacterValue=211*(s-4)+checksum;return checkCharacterValue===checkCharacter.getValue();}
static getNextSecondBar(row,initialPos){let currentPos;if(row.get(initialPos)){currentPos=row.getNextUnset(initialPos);currentPos=row.getNextSet(currentPos);}
else{currentPos=row.getNextSet(initialPos);currentPos=row.getNextUnset(currentPos);}
return currentPos;}
retrieveNextPair(row,previousPairs,rowNumber){let isOddPattern=previousPairs.length%2===0;if(this.startFromEven){isOddPattern=!isOddPattern;}
let pattern;let keepFinding=true;let forcedOffset=-1;do{this.findNextPair(row,previousPairs,forcedOffset);pattern=this.parseFoundFinderPattern(row,rowNumber,isOddPattern);if(pattern===null){forcedOffset=RSSExpandedReader.getNextSecondBar(row,this.startEnd[0]);}
else{keepFinding=false;}}while(keepFinding);let leftChar=this.decodeDataCharacter(row,pattern,isOddPattern,true);if(!this.isEmptyPair(previousPairs)&&previousPairs[previousPairs.length-1].mustBeLast()){throw new NotFoundException();}
let rightChar;try{rightChar=this.decodeDataCharacter(row,pattern,isOddPattern,false);}
catch(e){rightChar=null;console.log(e);}
return new ExpandedPair(leftChar,rightChar,pattern,true);}
isEmptyPair(pairs){if(pairs.length===0){return true;}
return false;}
findNextPair(row,previousPairs,forcedOffset){let counters=this.getDecodeFinderCounters();counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let width=row.getSize();let rowOffset;if(forcedOffset>=0){rowOffset=forcedOffset;}
else if(this.isEmptyPair(previousPairs)){rowOffset=0;}
else{let lastPair=previousPairs[previousPairs.length-1];rowOffset=lastPair.getFinderPattern().getStartEnd()[1];}
let searchingEvenPair=previousPairs.length%2!==0;if(this.startFromEven){searchingEvenPair=!searchingEvenPair;}
let isWhite=false;while(rowOffset<width){isWhite=!row.get(rowOffset);if(!isWhite){break;}
rowOffset++;}
let counterPosition=0;let patternStart=rowOffset;for(let x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===3){if(searchingEvenPair){RSSExpandedReader.reverseCounters(counters);}
if(RSSExpandedReader.isFinderPattern(counters)){this.startEnd[0]=patternStart;this.startEnd[1]=x;return;}
if(searchingEvenPair){RSSExpandedReader.reverseCounters(counters);}
patternStart+=counters[0]+counters[1];counters[0]=counters[2];counters[1]=counters[3];counters[2]=0;counters[3]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
static reverseCounters(counters){let length=counters.length;for(let i=0;i<length/2;++i){let tmp=counters[i];counters[i]=counters[length-i-1];counters[length-i-1]=tmp;}}
parseFoundFinderPattern(row,rowNumber,oddPattern){let firstCounter;let start;let end;if(oddPattern){let firstElementStart=this.startEnd[0]-1;while(firstElementStart>=0&&!row.get(firstElementStart)){firstElementStart--;}
firstElementStart++;firstCounter=this.startEnd[0]-firstElementStart;start=firstElementStart;end=this.startEnd[1];}
else{start=this.startEnd[0];end=row.getNextUnset(this.startEnd[1]+1);firstCounter=end-this.startEnd[1];}
let counters=this.getDecodeFinderCounters();System.arraycopy(counters,0,counters,1,counters.length-1);counters[0]=firstCounter;let value;try{value=this.parseFinderValue(counters,RSSExpandedReader.FINDER_PATTERNS);}
catch(e){return null;}
return new FinderPattern(value,[start,end],start,end,rowNumber);}
decodeDataCharacter(row,pattern,isOddPattern,leftChar){let counters=this.getDataCharacterCounters();for(let x=0;x<counters.length;x++){counters[x]=0;}
if(leftChar){RSSExpandedReader.recordPatternInReverse(row,pattern.getStartEnd()[0],counters);}
else{RSSExpandedReader.recordPattern(row,pattern.getStartEnd()[1],counters);for(let i=0,j=counters.length-1;i<j;i++,j--){let temp=counters[i];counters[i]=counters[j];counters[j]=temp;}}
let numModules=17;let elementWidth=MathUtils.sum(new Int32Array(counters))/numModules;let expectedElementWidth=(pattern.getStartEnd()[1]-pattern.getStartEnd()[0])/15.0;if(Math.abs(elementWidth-expectedElementWidth)/expectedElementWidth>0.3){throw new NotFoundException();}
let oddCounts=this.getOddCounts();let evenCounts=this.getEvenCounts();let oddRoundingErrors=this.getOddRoundingErrors();let evenRoundingErrors=this.getEvenRoundingErrors();for(let i=0;i<counters.length;i++){let value=(1.0*counters[i])/elementWidth;let count=value+0.5;if(count<1){if(value<0.3){throw new NotFoundException();}
count=1;}
else if(count>8){if(value>8.7){throw new NotFoundException();}
count=8;}
let offset=i/2;if((i&0x01)===0){oddCounts[offset]=count;oddRoundingErrors[offset]=value-count;}
else{evenCounts[offset]=count;evenRoundingErrors[offset]=value-count;}}
this.adjustOddEvenCounts(numModules);let weightRowNumber=4*pattern.getValue()+(isOddPattern?0:2)+(leftChar?0:1)-1;let oddSum=0;let oddChecksumPortion=0;for(let i=oddCounts.length-1;i>=0;i--){if(RSSExpandedReader.isNotA1left(pattern,isOddPattern,leftChar)){let weight=RSSExpandedReader.WEIGHTS[weightRowNumber][2*i];oddChecksumPortion+=oddCounts[i]*weight;}
oddSum+=oddCounts[i];}
let evenChecksumPortion=0;for(let i=evenCounts.length-1;i>=0;i--){if(RSSExpandedReader.isNotA1left(pattern,isOddPattern,leftChar)){let weight=RSSExpandedReader.WEIGHTS[weightRowNumber][2*i+1];evenChecksumPortion+=evenCounts[i]*weight;}}
let checksumPortion=oddChecksumPortion+evenChecksumPortion;if((oddSum&0x01)!==0||oddSum>13||oddSum<4){throw new NotFoundException();}
let group=(13-oddSum)/2;let oddWidest=RSSExpandedReader.SYMBOL_WIDEST[group];let evenWidest=9-oddWidest;let vOdd=RSSUtils.getRSSvalue(oddCounts,oddWidest,true);let vEven=RSSUtils.getRSSvalue(evenCounts,evenWidest,false);let tEven=RSSExpandedReader.EVEN_TOTAL_SUBSET[group];let gSum=RSSExpandedReader.GSUM[group];let value=vOdd*tEven+vEven+gSum;return new DataCharacter(value,checksumPortion);}
static isNotA1left(pattern,isOddPattern,leftChar){return!(pattern.getValue()===0&&isOddPattern&&leftChar);}
adjustOddEvenCounts(numModules){let oddSum=MathUtils.sum(new Int32Array(this.getOddCounts()));let evenSum=MathUtils.sum(new Int32Array(this.getEvenCounts()));let incrementOdd=false;let decrementOdd=false;if(oddSum>13){decrementOdd=true;}
else if(oddSum<4){incrementOdd=true;}
let incrementEven=false;let decrementEven=false;if(evenSum>13){decrementEven=true;}
else if(evenSum<4){incrementEven=true;}
let mismatch=oddSum+evenSum-numModules;let oddParityBad=(oddSum&0x01)===1;let evenParityBad=(evenSum&0x01)===0;if(mismatch===1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}
decrementOdd=true;}
else{if(!evenParityBad){throw new NotFoundException();}
decrementEven=true;}}
else if(mismatch===-1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}
incrementOdd=true;}
else{if(!evenParityBad){throw new NotFoundException();}
incrementEven=true;}}
else if(mismatch===0){if(oddParityBad){if(!evenParityBad){throw new NotFoundException();}
if(oddSum<evenSum){incrementOdd=true;decrementEven=true;}
else{decrementOdd=true;incrementEven=true;}}
else{if(evenParityBad){throw new NotFoundException();}}}
else{throw new NotFoundException();}
if(incrementOdd){if(decrementOdd){throw new NotFoundException();}
RSSExpandedReader.increment(this.getOddCounts(),this.getOddRoundingErrors());}
if(decrementOdd){RSSExpandedReader.decrement(this.getOddCounts(),this.getOddRoundingErrors());}
if(incrementEven){if(decrementEven){throw new NotFoundException();}
RSSExpandedReader.increment(this.getEvenCounts(),this.getOddRoundingErrors());}
if(decrementEven){RSSExpandedReader.decrement(this.getEvenCounts(),this.getEvenRoundingErrors());}}}
RSSExpandedReader.SYMBOL_WIDEST=[7,5,4,3,1];RSSExpandedReader.EVEN_TOTAL_SUBSET=[4,20,52,104,204];RSSExpandedReader.GSUM=[0,348,1388,2948,3988];RSSExpandedReader.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]),];RSSExpandedReader.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],];RSSExpandedReader.FINDER_PAT_A=0;RSSExpandedReader.FINDER_PAT_B=1;RSSExpandedReader.FINDER_PAT_C=2;RSSExpandedReader.FINDER_PAT_D=3;RSSExpandedReader.FINDER_PAT_E=4;RSSExpandedReader.FINDER_PAT_F=5;RSSExpandedReader.FINDER_PATTERN_SEQUENCES=[[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_C,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_F,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_E,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F,],[RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_A,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_B,RSSExpandedReader.FINDER_PAT_C,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_D,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_E,RSSExpandedReader.FINDER_PAT_F,RSSExpandedReader.FINDER_PAT_F,],];RSSExpandedReader.MAX_PAIRS=11;class Pair extends DataCharacter{constructor(value,checksumPortion,finderPattern){super(value,checksumPortion);this.count=0;this.finderPattern=finderPattern;}
getFinderPattern(){return this.finderPattern;}
getCount(){return this.count;}
incrementCount(){this.count++;}}
class RSS14Reader extends AbstractRSSReader{constructor(){super(...arguments);this.possibleLeftPairs=[];this.possibleRightPairs=[];}
decodeRow(rowNumber,row,hints){const leftPair=this.decodePair(row,false,rowNumber,hints);RSS14Reader.addOrTally(this.possibleLeftPairs,leftPair);row.reverse();let rightPair=this.decodePair(row,true,rowNumber,hints);RSS14Reader.addOrTally(this.possibleRightPairs,rightPair);row.reverse();for(let left of this.possibleLeftPairs){if(left.getCount()>1){for(let right of this.possibleRightPairs){if(right.getCount()>1&&RSS14Reader.checkChecksum(left,right)){return RSS14Reader.constructResult(left,right);}}}}
throw new NotFoundException();}
static addOrTally(possiblePairs,pair){if(pair==null){return;}
let found=false;for(let other of possiblePairs){if(other.getValue()===pair.getValue()){other.incrementCount();found=true;break;}}
if(!found){possiblePairs.push(pair);}}
reset(){this.possibleLeftPairs.length=0;this.possibleRightPairs.length=0;}
static constructResult(leftPair,rightPair){let symbolValue=4537077*leftPair.getValue()+rightPair.getValue();let text=new String(symbolValue).toString();let buffer=new StringBuilder();for(let i=13-text.length;i>0;i--){buffer.append('0');}
buffer.append(text);let checkDigit=0;for(let i=0;i<13;i++){let digit=buffer.charAt(i).charCodeAt(0)-'0'.charCodeAt(0);checkDigit+=((i&0x01)===0)?3*digit:digit;}
checkDigit=10-(checkDigit%10);if(checkDigit===10){checkDigit=0;}
buffer.append(checkDigit.toString());let leftPoints=leftPair.getFinderPattern().getResultPoints();let rightPoints=rightPair.getFinderPattern().getResultPoints();return new Result(buffer.toString(),null,0,[leftPoints[0],leftPoints[1],rightPoints[0],rightPoints[1]],BarcodeFormat$1.RSS_14,new Date().getTime());}
static checkChecksum(leftPair,rightPair){let checkValue=(leftPair.getChecksumPortion()+16*rightPair.getChecksumPortion())%79;let targetCheckValue=9*leftPair.getFinderPattern().getValue()+rightPair.getFinderPattern().getValue();if(targetCheckValue>72){targetCheckValue--;}
if(targetCheckValue>8){targetCheckValue--;}
return checkValue===targetCheckValue;}
decodePair(row,right,rowNumber,hints){try{let startEnd=this.findFinderPattern(row,right);let pattern=this.parseFoundFinderPattern(row,rowNumber,right,startEnd);let resultPointCallback=hints==null?null:hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);if(resultPointCallback!=null){let center=(startEnd[0]+startEnd[1])/2.0;if(right){center=row.getSize()-1-center;}
resultPointCallback.foundPossibleResultPoint(new ResultPoint(center,rowNumber));}
let outside=this.decodeDataCharacter(row,pattern,true);let inside=this.decodeDataCharacter(row,pattern,false);return new Pair(1597*outside.getValue()+inside.getValue(),outside.getChecksumPortion()+4*inside.getChecksumPortion(),pattern);}
catch(err){return null;}}
decodeDataCharacter(row,pattern,outsideChar){let counters=this.getDataCharacterCounters();for(let x=0;x<counters.length;x++){counters[x]=0;}
if(outsideChar){OneDReader.recordPatternInReverse(row,pattern.getStartEnd()[0],counters);}
else{OneDReader.recordPattern(row,pattern.getStartEnd()[1]+1,counters);for(let i=0,j=counters.length-1;i<j;i++,j--){let temp=counters[i];counters[i]=counters[j];counters[j]=temp;}}
let numModules=outsideChar?16:15;let elementWidth=MathUtils.sum(new Int32Array(counters))/numModules;let oddCounts=this.getOddCounts();let evenCounts=this.getEvenCounts();let oddRoundingErrors=this.getOddRoundingErrors();let evenRoundingErrors=this.getEvenRoundingErrors();for(let i=0;i<counters.length;i++){let value=counters[i]/elementWidth;let count=Math.floor(value+0.5);if(count<1){count=1;}
else if(count>8){count=8;}
let offset=Math.floor(i/2);if((i&0x01)===0){oddCounts[offset]=count;oddRoundingErrors[offset]=value-count;}
else{evenCounts[offset]=count;evenRoundingErrors[offset]=value-count;}}
this.adjustOddEvenCounts(outsideChar,numModules);let oddSum=0;let oddChecksumPortion=0;for(let i=oddCounts.length-1;i>=0;i--){oddChecksumPortion*=9;oddChecksumPortion+=oddCounts[i];oddSum+=oddCounts[i];}
let evenChecksumPortion=0;let evenSum=0;for(let i=evenCounts.length-1;i>=0;i--){evenChecksumPortion*=9;evenChecksumPortion+=evenCounts[i];evenSum+=evenCounts[i];}
let checksumPortion=oddChecksumPortion+3*evenChecksumPortion;if(outsideChar){if((oddSum&0x01)!==0||oddSum>12||oddSum<4){throw new NotFoundException();}
let group=(12-oddSum)/2;let oddWidest=RSS14Reader.OUTSIDE_ODD_WIDEST[group];let evenWidest=9-oddWidest;let vOdd=RSSUtils.getRSSvalue(oddCounts,oddWidest,false);let vEven=RSSUtils.getRSSvalue(evenCounts,evenWidest,true);let tEven=RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET[group];let gSum=RSS14Reader.OUTSIDE_GSUM[group];return new DataCharacter(vOdd*tEven+vEven+gSum,checksumPortion);}
else{if((evenSum&0x01)!==0||evenSum>10||evenSum<4){throw new NotFoundException();}
let group=(10-evenSum)/2;let oddWidest=RSS14Reader.INSIDE_ODD_WIDEST[group];let evenWidest=9-oddWidest;let vOdd=RSSUtils.getRSSvalue(oddCounts,oddWidest,true);let vEven=RSSUtils.getRSSvalue(evenCounts,evenWidest,false);let tOdd=RSS14Reader.INSIDE_ODD_TOTAL_SUBSET[group];let gSum=RSS14Reader.INSIDE_GSUM[group];return new DataCharacter(vEven*tOdd+vOdd+gSum,checksumPortion);}}
findFinderPattern(row,rightFinderPattern){let counters=this.getDecodeFinderCounters();counters[0]=0;counters[1]=0;counters[2]=0;counters[3]=0;let width=row.getSize();let isWhite=false;let rowOffset=0;while(rowOffset<width){isWhite=!row.get(rowOffset);if(rightFinderPattern===isWhite){break;}
rowOffset++;}
let counterPosition=0;let patternStart=rowOffset;for(let x=rowOffset;x<width;x++){if(row.get(x)!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===3){if(AbstractRSSReader.isFinderPattern(counters)){return[patternStart,x];}
patternStart+=counters[0]+counters[1];counters[0]=counters[2];counters[1]=counters[3];counters[2]=0;counters[3]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
throw new NotFoundException();}
parseFoundFinderPattern(row,rowNumber,right,startEnd){let firstIsBlack=row.get(startEnd[0]);let firstElementStart=startEnd[0]-1;while(firstElementStart>=0&&firstIsBlack!==row.get(firstElementStart)){firstElementStart--;}
firstElementStart++;const firstCounter=startEnd[0]-firstElementStart;const counters=this.getDecodeFinderCounters();const copy=new Int32Array(counters.length);System.arraycopy(counters,0,copy,1,counters.length-1);copy[0]=firstCounter;const value=this.parseFinderValue(copy,RSS14Reader.FINDER_PATTERNS);let start=firstElementStart;let end=startEnd[1];if(right){start=row.getSize()-1-start;end=row.getSize()-1-end;}
return new FinderPattern(value,[firstElementStart,startEnd[1]],start,end,rowNumber);}
adjustOddEvenCounts(outsideChar,numModules){let oddSum=MathUtils.sum(new Int32Array(this.getOddCounts()));let evenSum=MathUtils.sum(new Int32Array(this.getEvenCounts()));let incrementOdd=false;let decrementOdd=false;let incrementEven=false;let decrementEven=false;if(outsideChar){if(oddSum>12){decrementOdd=true;}
else if(oddSum<4){incrementOdd=true;}
if(evenSum>12){decrementEven=true;}
else if(evenSum<4){incrementEven=true;}}
else{if(oddSum>11){decrementOdd=true;}
else if(oddSum<5){incrementOdd=true;}
if(evenSum>10){decrementEven=true;}
else if(evenSum<4){incrementEven=true;}}
let mismatch=oddSum+evenSum-numModules;let oddParityBad=(oddSum&0x01)===(outsideChar?1:0);let evenParityBad=(evenSum&0x01)===1;if(mismatch===1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}
decrementOdd=true;}
else{if(!evenParityBad){throw new NotFoundException();}
decrementEven=true;}}
else if(mismatch===-1){if(oddParityBad){if(evenParityBad){throw new NotFoundException();}
incrementOdd=true;}
else{if(!evenParityBad){throw new NotFoundException();}
incrementEven=true;}}
else if(mismatch===0){if(oddParityBad){if(!evenParityBad){throw new NotFoundException();}
if(oddSum<evenSum){incrementOdd=true;decrementEven=true;}
else{decrementOdd=true;incrementEven=true;}}
else{if(evenParityBad){throw new NotFoundException();}}}
else{throw new NotFoundException();}
if(incrementOdd){if(decrementOdd){throw new NotFoundException();}
AbstractRSSReader.increment(this.getOddCounts(),this.getOddRoundingErrors());}
if(decrementOdd){AbstractRSSReader.decrement(this.getOddCounts(),this.getOddRoundingErrors());}
if(incrementEven){if(decrementEven){throw new NotFoundException();}
AbstractRSSReader.increment(this.getEvenCounts(),this.getOddRoundingErrors());}
if(decrementEven){AbstractRSSReader.decrement(this.getEvenCounts(),this.getEvenRoundingErrors());}}}
RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126];RSS14Reader.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81];RSS14Reader.OUTSIDE_GSUM=[0,161,961,2015,2715];RSS14Reader.INSIDE_GSUM=[0,336,1036,1516];RSS14Reader.OUTSIDE_ODD_WIDEST=[8,6,4,3,1];RSS14Reader.INSIDE_ODD_WIDEST=[2,4,6,8];RSS14Reader.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 MultiFormatOneDReader extends OneDReader{constructor(hints){super();this.readers=[];const possibleFormats=!hints?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);const useCode39CheckDigit=hints&&hints.get(DecodeHintType$1.ASSUME_CODE_39_CHECK_DIGIT)!==undefined;if(possibleFormats){if(possibleFormats.includes(BarcodeFormat$1.EAN_13)||possibleFormats.includes(BarcodeFormat$1.UPC_A)||possibleFormats.includes(BarcodeFormat$1.EAN_8)||possibleFormats.includes(BarcodeFormat$1.UPC_E)){this.readers.push(new MultiFormatUPCEANReader(hints));}
if(possibleFormats.includes(BarcodeFormat$1.CODE_39)){this.readers.push(new Code39Reader(useCode39CheckDigit));}
if(possibleFormats.includes(BarcodeFormat$1.CODE_93)){this.readers.push(new Code93Reader());}
if(possibleFormats.includes(BarcodeFormat$1.CODE_128)){this.readers.push(new Code128Reader());}
if(possibleFormats.includes(BarcodeFormat$1.ITF)){this.readers.push(new ITFReader());}
if(possibleFormats.includes(BarcodeFormat$1.CODABAR)){this.readers.push(new CodaBarReader());}
if(possibleFormats.includes(BarcodeFormat$1.RSS_14)){this.readers.push(new RSS14Reader());}
if(possibleFormats.includes(BarcodeFormat$1.RSS_EXPANDED)){console.warn('RSS Expanded reader IS NOT ready for production yet! use at your own risk.');this.readers.push(new RSSExpandedReader());}}
if(this.readers.length===0){this.readers.push(new MultiFormatUPCEANReader(hints));this.readers.push(new Code39Reader());this.readers.push(new Code93Reader());this.readers.push(new MultiFormatUPCEANReader(hints));this.readers.push(new Code128Reader());this.readers.push(new ITFReader());this.readers.push(new RSS14Reader());}}
decodeRow(rowNumber,row,hints){for(let i=0;i<this.readers.length;i++){try{return this.readers[i].decodeRow(rowNumber,row,hints);}
catch(re){}}
throw new NotFoundException();}
reset(){this.readers.forEach(reader=>reader.reset());}}
class BrowserBarcodeReader extends BrowserCodeReader{constructor(timeBetweenScansMillis=500,hints){super(new MultiFormatOneDReader(hints),timeBetweenScansMillis,hints);}}
class ECBlocks{constructor(ecCodewords,ecBlocks1,ecBlocks2){this.ecCodewords=ecCodewords;this.ecBlocks=[ecBlocks1];ecBlocks2&&this.ecBlocks.push(ecBlocks2);}
getECCodewords(){return this.ecCodewords;}
getECBlocks(){return this.ecBlocks;}}
class ECB{constructor(count,dataCodewords){this.count=count;this.dataCodewords=dataCodewords;}
getCount(){return this.count;}
getDataCodewords(){return this.dataCodewords;}}
class Version{constructor(versionNumber,symbolSizeRows,symbolSizeColumns,dataRegionSizeRows,dataRegionSizeColumns,ecBlocks){this.versionNumber=versionNumber;this.symbolSizeRows=symbolSizeRows;this.symbolSizeColumns=symbolSizeColumns;this.dataRegionSizeRows=dataRegionSizeRows;this.dataRegionSizeColumns=dataRegionSizeColumns;this.ecBlocks=ecBlocks;let total=0;const ecCodewords=ecBlocks.getECCodewords();const ecbArray=ecBlocks.getECBlocks();for(let ecBlock of ecbArray){total+=ecBlock.getCount()*(ecBlock.getDataCodewords()+ecCodewords);}
this.totalCodewords=total;}
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(numRows,numColumns){if((numRows&0x01)!==0||(numColumns&0x01)!==0){throw new FormatException();}
for(let version of Version.VERSIONS){if(version.symbolSizeRows===numRows&&version.symbolSizeColumns===numColumns){return version;}}
throw new FormatException();}
toString(){return''+this.versionNumber;}
static buildVersions(){return[new Version(1,10,10,8,8,new ECBlocks(5,new ECB(1,3))),new Version(2,12,12,10,10,new ECBlocks(7,new ECB(1,5))),new Version(3,14,14,12,12,new ECBlocks(10,new ECB(1,8))),new Version(4,16,16,14,14,new ECBlocks(12,new ECB(1,12))),new Version(5,18,18,16,16,new ECBlocks(14,new ECB(1,18))),new Version(6,20,20,18,18,new ECBlocks(18,new ECB(1,22))),new Version(7,22,22,20,20,new ECBlocks(20,new ECB(1,30))),new Version(8,24,24,22,22,new ECBlocks(24,new ECB(1,36))),new Version(9,26,26,24,24,new ECBlocks(28,new ECB(1,44))),new Version(10,32,32,14,14,new ECBlocks(36,new ECB(1,62))),new Version(11,36,36,16,16,new ECBlocks(42,new ECB(1,86))),new Version(12,40,40,18,18,new ECBlocks(48,new ECB(1,114))),new Version(13,44,44,20,20,new ECBlocks(56,new ECB(1,144))),new Version(14,48,48,22,22,new ECBlocks(68,new ECB(1,174))),new Version(15,52,52,24,24,new ECBlocks(42,new ECB(2,102))),new Version(16,64,64,14,14,new ECBlocks(56,new ECB(2,140))),new Version(17,72,72,16,16,new ECBlocks(36,new ECB(4,92))),new Version(18,80,80,18,18,new ECBlocks(48,new ECB(4,114))),new Version(19,88,88,20,20,new ECBlocks(56,new ECB(4,144))),new Version(20,96,96,22,22,new ECBlocks(68,new ECB(4,174))),new Version(21,104,104,24,24,new ECBlocks(56,new ECB(6,136))),new Version(22,120,120,18,18,new ECBlocks(68,new ECB(6,175))),new Version(23,132,132,20,20,new ECBlocks(62,new ECB(8,163))),new Version(24,144,144,22,22,new ECBlocks(62,new ECB(8,156),new ECB(2,155))),new Version(25,8,18,6,16,new ECBlocks(7,new ECB(1,5))),new Version(26,8,32,6,14,new ECBlocks(11,new ECB(1,10))),new Version(27,12,26,10,24,new ECBlocks(14,new ECB(1,16))),new Version(28,12,36,10,16,new ECBlocks(18,new ECB(1,22))),new Version(29,16,36,14,16,new ECBlocks(24,new ECB(1,32))),new Version(30,16,48,14,22,new ECBlocks(28,new ECB(1,49)))];}}
Version.VERSIONS=Version.buildVersions();class BitMatrixParser{constructor(bitMatrix){const dimension=bitMatrix.getHeight();if(dimension<8||dimension>144||(dimension&0x01)!==0){throw new FormatException();}
this.version=BitMatrixParser.readVersion(bitMatrix);this.mappingBitMatrix=this.extractDataRegion(bitMatrix);this.readMappingMatrix=new BitMatrix(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight());}
getVersion(){return this.version;}
static readVersion(bitMatrix){const numRows=bitMatrix.getHeight();const numColumns=bitMatrix.getWidth();return Version.getVersionForDimensions(numRows,numColumns);}
readCodewords(){const result=new Int8Array(this.version.getTotalCodewords());let resultOffset=0;let row=4;let column=0;const numRows=this.mappingBitMatrix.getHeight();const numColumns=this.mappingBitMatrix.getWidth();let corner1Read=false;let corner2Read=false;let corner3Read=false;let corner4Read=false;do{if((row===numRows)&&(column===0)&&!corner1Read){result[resultOffset++]=this.readCorner1(numRows,numColumns)&0xff;row-=2;column+=2;corner1Read=true;}
else if((row===numRows-2)&&(column===0)&&((numColumns&0x03)!==0)&&!corner2Read){result[resultOffset++]=this.readCorner2(numRows,numColumns)&0xff;row-=2;column+=2;corner2Read=true;}
else if((row===numRows+4)&&(column===2)&&((numColumns&0x07)===0)&&!corner3Read){result[resultOffset++]=this.readCorner3(numRows,numColumns)&0xff;row-=2;column+=2;corner3Read=true;}
else if((row===numRows-2)&&(column===0)&&((numColumns&0x07)===4)&&!corner4Read){result[resultOffset++]=this.readCorner4(numRows,numColumns)&0xff;row-=2;column+=2;corner4Read=true;}
else{do{if((row<numRows)&&(column>=0)&&!this.readMappingMatrix.get(column,row)){result[resultOffset++]=this.readUtah(row,column,numRows,numColumns)&0xff;}
row-=2;column+=2;}while((row>=0)&&(column<numColumns));row+=1;column+=3;do{if((row>=0)&&(column<numColumns)&&!this.readMappingMatrix.get(column,row)){result[resultOffset++]=this.readUtah(row,column,numRows,numColumns)&0xff;}
row+=2;column-=2;}while((row<numRows)&&(column>=0));row+=3;column+=1;}}while((row<numRows)||(column<numColumns));if(resultOffset!==this.version.getTotalCodewords()){throw new FormatException();}
return result;}
readModule(row,column,numRows,numColumns){if(row<0){row+=numRows;column+=4-((numRows+4)&0x07);}
if(column<0){column+=numColumns;row+=4-((numColumns+4)&0x07);}
this.readMappingMatrix.set(column,row);return this.mappingBitMatrix.get(column,row);}
readUtah(row,column,numRows,numColumns){let currentByte=0;if(this.readModule(row-2,column-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row-2,column-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row-1,column-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row-1,column-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row-1,column,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row,column-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row,column-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(row,column,numRows,numColumns)){currentByte|=1;}
return currentByte;}
readCorner1(numRows,numColumns){let currentByte=0;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-1,1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-1,2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(2,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(3,numColumns-1,numRows,numColumns)){currentByte|=1;}
return currentByte;}
readCorner2(numRows,numColumns){let currentByte=0;if(this.readModule(numRows-3,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-2,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-4,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-3,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}
return currentByte;}
readCorner3(numRows,numColumns){let currentByte=0;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-1,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-3,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-3,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}
return currentByte;}
readCorner4(numRows,numColumns){let currentByte=0;if(this.readModule(numRows-3,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-2,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(numRows-1,0,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-2,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(0,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(1,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(2,numColumns-1,numRows,numColumns)){currentByte|=1;}
currentByte<<=1;if(this.readModule(3,numColumns-1,numRows,numColumns)){currentByte|=1;}
return currentByte;}
extractDataRegion(bitMatrix){const symbolSizeRows=this.version.getSymbolSizeRows();const symbolSizeColumns=this.version.getSymbolSizeColumns();if(bitMatrix.getHeight()!==symbolSizeRows){throw new IllegalArgumentException('Dimension of bitMatrix must match the version size');}
const dataRegionSizeRows=this.version.getDataRegionSizeRows();const dataRegionSizeColumns=this.version.getDataRegionSizeColumns();const numDataRegionsRow=symbolSizeRows/dataRegionSizeRows|0;const numDataRegionsColumn=symbolSizeColumns/dataRegionSizeColumns|0;const sizeDataRegionRow=numDataRegionsRow*dataRegionSizeRows;const sizeDataRegionColumn=numDataRegionsColumn*dataRegionSizeColumns;const bitMatrixWithoutAlignment=new BitMatrix(sizeDataRegionColumn,sizeDataRegionRow);for(let dataRegionRow=0;dataRegionRow<numDataRegionsRow;++dataRegionRow){const dataRegionRowOffset=dataRegionRow*dataRegionSizeRows;for(let dataRegionColumn=0;dataRegionColumn<numDataRegionsColumn;++dataRegionColumn){const dataRegionColumnOffset=dataRegionColumn*dataRegionSizeColumns;for(let i=0;i<dataRegionSizeRows;++i){const readRowOffset=dataRegionRow*(dataRegionSizeRows+2)+1+i;const writeRowOffset=dataRegionRowOffset+i;for(let j=0;j<dataRegionSizeColumns;++j){const readColumnOffset=dataRegionColumn*(dataRegionSizeColumns+2)+1+j;if(bitMatrix.get(readColumnOffset,readRowOffset)){const writeColumnOffset=dataRegionColumnOffset+j;bitMatrixWithoutAlignment.set(writeColumnOffset,writeRowOffset);}}}}}
return bitMatrixWithoutAlignment;}}
class DataBlock{constructor(numDataCodewords,codewords){this.numDataCodewords=numDataCodewords;this.codewords=codewords;}
static getDataBlocks(rawCodewords,version){const ecBlocks=version.getECBlocks();let totalBlocks=0;const ecBlockArray=ecBlocks.getECBlocks();for(let ecBlock of ecBlockArray){totalBlocks+=ecBlock.getCount();}
const result=new Array(totalBlocks);let numResultBlocks=0;for(let ecBlock of ecBlockArray){for(let i=0;i<ecBlock.getCount();i++){const numDataCodewords=ecBlock.getDataCodewords();const numBlockCodewords=ecBlocks.getECCodewords()+numDataCodewords;result[numResultBlocks++]=new DataBlock(numDataCodewords,new Uint8Array(numBlockCodewords));}}
const longerBlocksTotalCodewords=result[0].codewords.length;const longerBlocksNumDataCodewords=longerBlocksTotalCodewords-ecBlocks.getECCodewords();const shorterBlocksNumDataCodewords=longerBlocksNumDataCodewords-1;let rawCodewordsOffset=0;for(let i=0;i<shorterBlocksNumDataCodewords;i++){for(let j=0;j<numResultBlocks;j++){result[j].codewords[i]=rawCodewords[rawCodewordsOffset++];}}
const specialVersion=version.getVersionNumber()===24;const numLongerBlocks=specialVersion?8:numResultBlocks;for(let j=0;j<numLongerBlocks;j++){result[j].codewords[longerBlocksNumDataCodewords-1]=rawCodewords[rawCodewordsOffset++];}
const max=result[0].codewords.length;for(let i=longerBlocksNumDataCodewords;i<max;i++){for(let j=0;j<numResultBlocks;j++){const jOffset=specialVersion?(j+8)%numResultBlocks:j;const iOffset=specialVersion&&jOffset>7?i-1:i;result[jOffset].codewords[iOffset]=rawCodewords[rawCodewordsOffset++];}}
if(rawCodewordsOffset!==rawCodewords.length){throw new IllegalArgumentException();}
return result;}
getNumDataCodewords(){return this.numDataCodewords;}
getCodewords(){return this.codewords;}}
class BitSource{constructor(bytes){this.bytes=bytes;this.byteOffset=0;this.bitOffset=0;}
getBitOffset(){return this.bitOffset;}
getByteOffset(){return this.byteOffset;}
readBits(numBits){if(numBits<1||numBits>32||numBits>this.available()){throw new IllegalArgumentException(''+numBits);}
let result=0;let bitOffset=this.bitOffset;let byteOffset=this.byteOffset;const bytes=this.bytes;if(bitOffset>0){const bitsLeft=8-bitOffset;const toRead=numBits<bitsLeft?numBits:bitsLeft;const bitsToNotRead=bitsLeft-toRead;const mask=(0xFF>>(8-toRead))<<bitsToNotRead;result=(bytes[byteOffset]&mask)>>bitsToNotRead;numBits-=toRead;bitOffset+=toRead;if(bitOffset===8){bitOffset=0;byteOffset++;}}
if(numBits>0){while(numBits>=8){result=(result<<8)|(bytes[byteOffset]&0xFF);byteOffset++;numBits-=8;}
if(numBits>0){const bitsToNotRead=8-numBits;const mask=(0xFF>>bitsToNotRead)<<bitsToNotRead;result=(result<<numBits)|((bytes[byteOffset]&mask)>>bitsToNotRead);bitOffset+=numBits;}}
this.bitOffset=bitOffset;this.byteOffset=byteOffset;return result;}
available(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset;}}
var Mode;(function(Mode){Mode[Mode["PAD_ENCODE"]=0]="PAD_ENCODE";Mode[Mode["ASCII_ENCODE"]=1]="ASCII_ENCODE";Mode[Mode["C40_ENCODE"]=2]="C40_ENCODE";Mode[Mode["TEXT_ENCODE"]=3]="TEXT_ENCODE";Mode[Mode["ANSIX12_ENCODE"]=4]="ANSIX12_ENCODE";Mode[Mode["EDIFACT_ENCODE"]=5]="EDIFACT_ENCODE";Mode[Mode["BASE256_ENCODE"]=6]="BASE256_ENCODE";})(Mode||(Mode={}));class DecodedBitStreamParser{static decode(bytes){const bits=new BitSource(bytes);const result=new StringBuilder();const resultTrailer=new StringBuilder();const byteSegments=new Array();let mode=Mode.ASCII_ENCODE;do{if(mode===Mode.ASCII_ENCODE){mode=this.decodeAsciiSegment(bits,result,resultTrailer);}
else{switch(mode){case Mode.C40_ENCODE:this.decodeC40Segment(bits,result);break;case Mode.TEXT_ENCODE:this.decodeTextSegment(bits,result);break;case Mode.ANSIX12_ENCODE:this.decodeAnsiX12Segment(bits,result);break;case Mode.EDIFACT_ENCODE:this.decodeEdifactSegment(bits,result);break;case Mode.BASE256_ENCODE:this.decodeBase256Segment(bits,result,byteSegments);break;default:throw new FormatException();}
mode=Mode.ASCII_ENCODE;}}while(mode!==Mode.PAD_ENCODE&&bits.available()>0);if(resultTrailer.length()>0){result.append(resultTrailer.toString());}
return new DecoderResult(bytes,result.toString(),byteSegments.length===0?null:byteSegments,null);}
static decodeAsciiSegment(bits,result,resultTrailer){let upperShift=false;do{let oneByte=bits.readBits(8);if(oneByte===0){throw new FormatException();}
else if(oneByte<=128){if(upperShift){oneByte+=128;}
result.append(String.fromCharCode(oneByte-1));return Mode.ASCII_ENCODE;}
else if(oneByte===129){return Mode.PAD_ENCODE;}
else if(oneByte<=229){const value=oneByte-130;if(value<10){result.append('0');}
result.append(''+value);}
else{switch(oneByte){case 230:return Mode.C40_ENCODE;case 231:return Mode.BASE256_ENCODE;case 232:result.append(String.fromCharCode(29));break;case 233:case 234:break;case 235:upperShift=true;break;case 236:result.append('[)>\u001E05\u001D');resultTrailer.insert(0,'\u001E\u0004');break;case 237:result.append('[)>\u001E06\u001D');resultTrailer.insert(0,'\u001E\u0004');break;case 238:return Mode.ANSIX12_ENCODE;case 239:return Mode.TEXT_ENCODE;case 240:return Mode.EDIFACT_ENCODE;case 241:break;default:if(oneByte!==254||bits.available()!==0){throw new FormatException();}
break;}}}while(bits.available()>0);return Mode.ASCII_ENCODE;}
static decodeC40Segment(bits,result){let upperShift=false;const cValues=[];let shift=0;do{if(bits.available()===8){return;}
const firstByte=bits.readBits(8);if(firstByte===254){return;}
this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(let i=0;i<3;i++){const cValue=cValues[i];switch(shift){case 0:if(cValue<3){shift=cValue+1;}
else if(cValue<this.C40_BASIC_SET_CHARS.length){const c40char=this.C40_BASIC_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(c40char.charCodeAt(0)+128));upperShift=false;}
else{result.append(c40char);}}
else{throw new FormatException();}
break;case 1:if(upperShift){result.append(String.fromCharCode(cValue+128));upperShift=false;}
else{result.append(String.fromCharCode(cValue));}
shift=0;break;case 2:if(cValue<this.C40_SHIFT2_SET_CHARS.length){const c40char=this.C40_SHIFT2_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(c40char.charCodeAt(0)+128));upperShift=false;}
else{result.append(c40char);}}
else{switch(cValue){case 27:result.append(String.fromCharCode(29));break;case 30:upperShift=true;break;default:throw new FormatException();}}
shift=0;break;case 3:if(upperShift){result.append(String.fromCharCode(cValue+224));upperShift=false;}
else{result.append(String.fromCharCode(cValue+96));}
shift=0;break;default:throw new FormatException();}}}while(bits.available()>0);}
static decodeTextSegment(bits,result){let upperShift=false;let cValues=[];let shift=0;do{if(bits.available()===8){return;}
const firstByte=bits.readBits(8);if(firstByte===254){return;}
this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(let i=0;i<3;i++){const cValue=cValues[i];switch(shift){case 0:if(cValue<3){shift=cValue+1;}
else if(cValue<this.TEXT_BASIC_SET_CHARS.length){const textChar=this.TEXT_BASIC_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(textChar.charCodeAt(0)+128));upperShift=false;}
else{result.append(textChar);}}
else{throw new FormatException();}
break;case 1:if(upperShift){result.append(String.fromCharCode(cValue+128));upperShift=false;}
else{result.append(String.fromCharCode(cValue));}
shift=0;break;case 2:if(cValue<this.TEXT_SHIFT2_SET_CHARS.length){const textChar=this.TEXT_SHIFT2_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(textChar.charCodeAt(0)+128));upperShift=false;}
else{result.append(textChar);}}
else{switch(cValue){case 27:result.append(String.fromCharCode(29));break;case 30:upperShift=true;break;default:throw new FormatException();}}
shift=0;break;case 3:if(cValue<this.TEXT_SHIFT3_SET_CHARS.length){const textChar=this.TEXT_SHIFT3_SET_CHARS[cValue];if(upperShift){result.append(String.fromCharCode(textChar.charCodeAt(0)+128));upperShift=false;}
else{result.append(textChar);}
shift=0;}
else{throw new FormatException();}
break;default:throw new FormatException();}}}while(bits.available()>0);}
static decodeAnsiX12Segment(bits,result){const cValues=[];do{if(bits.available()===8){return;}
const firstByte=bits.readBits(8);if(firstByte===254){return;}
this.parseTwoBytes(firstByte,bits.readBits(8),cValues);for(let i=0;i<3;i++){const cValue=cValues[i];switch(cValue){case 0:result.append('\r');break;case 1:result.append('*');break;case 2:result.append('>');break;case 3:result.append(' ');break;default:if(cValue<14){result.append(String.fromCharCode(cValue+44));}
else if(cValue<40){result.append(String.fromCharCode(cValue+51));}
else{throw new FormatException();}
break;}}}while(bits.available()>0);}
static parseTwoBytes(firstByte,secondByte,result){let fullBitValue=(firstByte<<8)+secondByte-1;let temp=Math.floor(fullBitValue/1600);result[0]=temp;fullBitValue-=temp*1600;temp=Math.floor(fullBitValue/40);result[1]=temp;result[2]=fullBitValue-temp*40;}
static decodeEdifactSegment(bits,result){do{if(bits.available()<=16){return;}
for(let i=0;i<4;i++){let edifactValue=bits.readBits(6);if(edifactValue===0x1F){const bitsLeft=8-bits.getBitOffset();if(bitsLeft!==8){bits.readBits(bitsLeft);}
return;}
if((edifactValue&0x20)===0){edifactValue|=0x40;}
result.append(String.fromCharCode(edifactValue));}}while(bits.available()>0);}
static decodeBase256Segment(bits,result,byteSegments){let codewordPosition=1+bits.getByteOffset();const d1=this.unrandomize255State(bits.readBits(8),codewordPosition++);let count;if(d1===0){count=bits.available()/8|0;}
else if(d1<250){count=d1;}
else{count=250*(d1-249)+this.unrandomize255State(bits.readBits(8),codewordPosition++);}
if(count<0){throw new FormatException();}
const bytes=new Uint8Array(count);for(let i=0;i<count;i++){if(bits.available()<8){throw new FormatException();}
bytes[i]=this.unrandomize255State(bits.readBits(8),codewordPosition++);}
byteSegments.push(bytes);try{result.append(StringEncoding.decode(bytes,StringUtils.ISO88591));}
catch(uee){throw new IllegalStateException('Platform does not support required encoding: '+uee.message);}}
static unrandomize255State(randomizedBase256Codeword,base256CodewordPosition){const pseudoRandomNumber=((149*base256CodewordPosition)%255)+1;const tempVariable=randomizedBase256Codeword-pseudoRandomNumber;return tempVariable>=0?tempVariable:tempVariable+256;}}
DecodedBitStreamParser.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'];DecodedBitStreamParser.C40_SHIFT2_SET_CHARS=['!','"','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\',']','^','_'];DecodedBitStreamParser.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'];DecodedBitStreamParser.TEXT_SHIFT2_SET_CHARS=DecodedBitStreamParser.C40_SHIFT2_SET_CHARS;DecodedBitStreamParser.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','{','|','}','~',String.fromCharCode(127)];class Decoder$1{constructor(){this.rsDecoder=new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);}
decode(bits){const parser=new BitMatrixParser(bits);const version=parser.getVersion();const codewords=parser.readCodewords();const dataBlocks=DataBlock.getDataBlocks(codewords,version);let totalBytes=0;for(let db of dataBlocks){totalBytes+=db.getNumDataCodewords();}
const resultBytes=new Uint8Array(totalBytes);const dataBlocksCount=dataBlocks.length;for(let j=0;j<dataBlocksCount;j++){const dataBlock=dataBlocks[j];const codewordBytes=dataBlock.getCodewords();const numDataCodewords=dataBlock.getNumDataCodewords();this.correctErrors(codewordBytes,numDataCodewords);for(let i=0;i<numDataCodewords;i++){resultBytes[i*dataBlocksCount+j]=codewordBytes[i];}}
return DecodedBitStreamParser.decode(resultBytes);}
correctErrors(codewordBytes,numDataCodewords){const codewordsInts=new Int32Array(codewordBytes);try{this.rsDecoder.decode(codewordsInts,codewordBytes.length-numDataCodewords);}
catch(ignored){throw new ChecksumException();}
for(let i=0;i<numDataCodewords;i++){codewordBytes[i]=codewordsInts[i];}}}
class Detector$1{constructor(image){this.image=image;this.rectangleDetector=new WhiteRectangleDetector(this.image);}
detect(){const cornerPoints=this.rectangleDetector.detect();let points=this.detectSolid1(cornerPoints);points=this.detectSolid2(points);points[3]=this.correctTopRight(points);if(!points[3]){throw new NotFoundException();}
points=this.shiftToModuleCenter(points);const topLeft=points[0];const bottomLeft=points[1];const bottomRight=points[2];const topRight=points[3];let dimensionTop=this.transitionsBetween(topLeft,topRight)+1;let dimensionRight=this.transitionsBetween(bottomRight,topRight)+1;if((dimensionTop&0x01)===1){dimensionTop+=1;}
if((dimensionRight&0x01)===1){dimensionRight+=1;}
if(4*dimensionTop<7*dimensionRight&&4*dimensionRight<7*dimensionTop){dimensionTop=dimensionRight=Math.max(dimensionTop,dimensionRight);}
let bits=Detector$1.sampleGrid(this.image,topLeft,bottomLeft,bottomRight,topRight,dimensionTop,dimensionRight);return new DetectorResult(bits,[topLeft,bottomLeft,bottomRight,topRight]);}
static shiftPoint(point,to,div){let x=(to.getX()-point.getX())/(div+1);let y=(to.getY()-point.getY())/(div+1);return new ResultPoint(point.getX()+x,point.getY()+y);}
static moveAway(point,fromX,fromY){let x=point.getX();let y=point.getY();if(x<fromX){x-=1;}
else{x+=1;}
if(y<fromY){y-=1;}
else{y+=1;}
return new ResultPoint(x,y);}
detectSolid1(cornerPoints){let pointA=cornerPoints[0];let pointB=cornerPoints[1];let pointC=cornerPoints[3];let pointD=cornerPoints[2];let trAB=this.transitionsBetween(pointA,pointB);let trBC=this.transitionsBetween(pointB,pointC);let trCD=this.transitionsBetween(pointC,pointD);let trDA=this.transitionsBetween(pointD,pointA);let min=trAB;let points=[pointD,pointA,pointB,pointC];if(min>trBC){min=trBC;points[0]=pointA;points[1]=pointB;points[2]=pointC;points[3]=pointD;}
if(min>trCD){min=trCD;points[0]=pointB;points[1]=pointC;points[2]=pointD;points[3]=pointA;}
if(min>trDA){points[0]=pointC;points[1]=pointD;points[2]=pointA;points[3]=pointB;}
return points;}
detectSolid2(points){let pointA=points[0];let pointB=points[1];let pointC=points[2];let pointD=points[3];let tr=this.transitionsBetween(pointA,pointD);let pointBs=Detector$1.shiftPoint(pointB,pointC,(tr+1)*4);let pointCs=Detector$1.shiftPoint(pointC,pointB,(tr+1)*4);let trBA=this.transitionsBetween(pointBs,pointA);let trCD=this.transitionsBetween(pointCs,pointD);if(trBA<trCD){points[0]=pointA;points[1]=pointB;points[2]=pointC;points[3]=pointD;}
else{points[0]=pointB;points[1]=pointC;points[2]=pointD;points[3]=pointA;}
return points;}
correctTopRight(points){let pointA=points[0];let pointB=points[1];let pointC=points[2];let pointD=points[3];let trTop=this.transitionsBetween(pointA,pointD);let trRight=this.transitionsBetween(pointB,pointD);let pointAs=Detector$1.shiftPoint(pointA,pointB,(trRight+1)*4);let pointCs=Detector$1.shiftPoint(pointC,pointB,(trTop+1)*4);trTop=this.transitionsBetween(pointAs,pointD);trRight=this.transitionsBetween(pointCs,pointD);let candidate1=new ResultPoint(pointD.getX()+(pointC.getX()-pointB.getX())/(trTop+1),pointD.getY()+(pointC.getY()-pointB.getY())/(trTop+1));let candidate2=new ResultPoint(pointD.getX()+(pointA.getX()-pointB.getX())/(trRight+1),pointD.getY()+(pointA.getY()-pointB.getY())/(trRight+1));if(!this.isValid(candidate1)){if(this.isValid(candidate2)){return candidate2;}
return null;}
if(!this.isValid(candidate2)){return candidate1;}
let sumc1=this.transitionsBetween(pointAs,candidate1)+this.transitionsBetween(pointCs,candidate1);let sumc2=this.transitionsBetween(pointAs,candidate2)+this.transitionsBetween(pointCs,candidate2);if(sumc1>sumc2){return candidate1;}
else{return candidate2;}}
shiftToModuleCenter(points){let pointA=points[0];let pointB=points[1];let pointC=points[2];let pointD=points[3];let dimH=this.transitionsBetween(pointA,pointD)+1;let dimV=this.transitionsBetween(pointC,pointD)+1;let pointAs=Detector$1.shiftPoint(pointA,pointB,dimV*4);let pointCs=Detector$1.shiftPoint(pointC,pointB,dimH*4);dimH=this.transitionsBetween(pointAs,pointD)+1;dimV=this.transitionsBetween(pointCs,pointD)+1;if((dimH&0x01)===1){dimH+=1;}
if((dimV&0x01)===1){dimV+=1;}
let centerX=(pointA.getX()+pointB.getX()+pointC.getX()+pointD.getX())/4;let centerY=(pointA.getY()+pointB.getY()+pointC.getY()+pointD.getY())/4;pointA=Detector$1.moveAway(pointA,centerX,centerY);pointB=Detector$1.moveAway(pointB,centerX,centerY);pointC=Detector$1.moveAway(pointC,centerX,centerY);pointD=Detector$1.moveAway(pointD,centerX,centerY);let pointBs;let pointDs;pointAs=Detector$1.shiftPoint(pointA,pointB,dimV*4);pointAs=Detector$1.shiftPoint(pointAs,pointD,dimH*4);pointBs=Detector$1.shiftPoint(pointB,pointA,dimV*4);pointBs=Detector$1.shiftPoint(pointBs,pointC,dimH*4);pointCs=Detector$1.shiftPoint(pointC,pointD,dimV*4);pointCs=Detector$1.shiftPoint(pointCs,pointB,dimH*4);pointDs=Detector$1.shiftPoint(pointD,pointC,dimV*4);pointDs=Detector$1.shiftPoint(pointDs,pointA,dimH*4);return[pointAs,pointBs,pointCs,pointDs];}
isValid(p){return p.getX()>=0&&p.getX()<this.image.getWidth()&&p.getY()>0&&p.getY()<this.image.getHeight();}
static sampleGrid(image,topLeft,bottomLeft,bottomRight,topRight,dimensionX,dimensionY){const sampler=GridSamplerInstance.getInstance();return sampler.sampleGrid(image,dimensionX,dimensionY,0.5,0.5,dimensionX-0.5,0.5,dimensionX-0.5,dimensionY-0.5,0.5,dimensionY-0.5,topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRight.getX(),bottomRight.getY(),bottomLeft.getX(),bottomLeft.getY());}
transitionsBetween(from,to){let fromX=Math.trunc(from.getX());let fromY=Math.trunc(from.getY());let toX=Math.trunc(to.getX());let toY=Math.trunc(to.getY());let steep=Math.abs(toY-fromY)>Math.abs(toX-fromX);if(steep){let temp=fromX;fromX=fromY;fromY=temp;temp=toX;toX=toY;toY=temp;}
let dx=Math.abs(toX-fromX);let dy=Math.abs(toY-fromY);let error=-dx/2;let ystep=fromY<toY?1:-1;let xstep=fromX<toX?1:-1;let transitions=0;let inBlack=this.image.get(steep?fromY:fromX,steep?fromX:fromY);for(let x=fromX,y=fromY;x!==toX;x+=xstep){let isBlack=this.image.get(steep?y:x,steep?x:y);if(isBlack!==inBlack){transitions++;inBlack=isBlack;}
error+=dy;if(error>0){if(y===toY){break;}
y+=ystep;error-=dx;}}
return transitions;}}
class DataMatrixReader{constructor(){this.decoder=new Decoder$1();}
decode(image,hints=null){let decoderResult;let points;if(hints!=null&&hints.has(DecodeHintType$1.PURE_BARCODE)){const bits=DataMatrixReader.extractPureBits(image.getBlackMatrix());decoderResult=this.decoder.decode(bits);points=DataMatrixReader.NO_POINTS;}
else{const detectorResult=new Detector$1(image.getBlackMatrix()).detect();decoderResult=this.decoder.decode(detectorResult.getBits());points=detectorResult.getPoints();}
const rawBytes=decoderResult.getRawBytes();const result=new Result(decoderResult.getText(),rawBytes,8*rawBytes.length,points,BarcodeFormat$1.DATA_MATRIX,System.currentTimeMillis());const byteSegments=decoderResult.getByteSegments();if(byteSegments!=null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}
const ecLevel=decoderResult.getECLevel();if(ecLevel!=null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}
return result;}
reset(){}
static extractPureBits(image){const leftTopBlack=image.getTopLeftOnBit();const rightBottomBlack=image.getBottomRightOnBit();if(leftTopBlack==null||rightBottomBlack==null){throw new NotFoundException();}
const moduleSize=this.moduleSize(leftTopBlack,image);let top=leftTopBlack[1];const bottom=rightBottomBlack[1];let left=leftTopBlack[0];const right=rightBottomBlack[0];const matrixWidth=(right-left+1)/moduleSize;const matrixHeight=(bottom-top+1)/moduleSize;if(matrixWidth<=0||matrixHeight<=0){throw new NotFoundException();}
const nudge=moduleSize/2;top+=nudge;left+=nudge;const bits=new BitMatrix(matrixWidth,matrixHeight);for(let y=0;y<matrixHeight;y++){const iOffset=top+y*moduleSize;for(let x=0;x<matrixWidth;x++){if(image.get(left+x*moduleSize,iOffset)){bits.set(x,y);}}}
return bits;}
static moduleSize(leftTopBlack,image){const width=image.getWidth();let x=leftTopBlack[0];const y=leftTopBlack[1];while(x<width&&image.get(x,y)){x++;}
if(x===width){throw new NotFoundException();}
const moduleSize=x-leftTopBlack[0];if(moduleSize===0){throw new NotFoundException();}
return moduleSize;}}
DataMatrixReader.NO_POINTS=[];class BrowserDatamatrixCodeReader extends BrowserCodeReader{constructor(timeBetweenScansMillis=500){super(new DataMatrixReader(),timeBetweenScansMillis);}}
var ErrorCorrectionLevelValues;(function(ErrorCorrectionLevelValues){ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["L"]=0]="L";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["M"]=1]="M";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["Q"]=2]="Q";ErrorCorrectionLevelValues[ErrorCorrectionLevelValues["H"]=3]="H";})(ErrorCorrectionLevelValues||(ErrorCorrectionLevelValues={}));class ErrorCorrectionLevel{constructor(value,stringValue,bits){this.value=value;this.stringValue=stringValue;this.bits=bits;ErrorCorrectionLevel.FOR_BITS.set(bits,this);ErrorCorrectionLevel.FOR_VALUE.set(value,this);}
getValue(){return this.value;}
getBits(){return this.bits;}
static fromString(s){switch(s){case'L':return ErrorCorrectionLevel.L;case'M':return ErrorCorrectionLevel.M;case'Q':return ErrorCorrectionLevel.Q;case'H':return ErrorCorrectionLevel.H;default:throw new ArgumentException(s+'not available');}}
toString(){return this.stringValue;}
equals(o){if(!(o instanceof ErrorCorrectionLevel)){return false;}
const other=o;return this.value===other.value;}
static forBits(bits){if(bits<0||bits>=ErrorCorrectionLevel.FOR_BITS.size){throw new IllegalArgumentException();}
return ErrorCorrectionLevel.FOR_BITS.get(bits);}}
ErrorCorrectionLevel.FOR_BITS=new Map();ErrorCorrectionLevel.FOR_VALUE=new Map();ErrorCorrectionLevel.L=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.L,'L',0x01);ErrorCorrectionLevel.M=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.M,'M',0x00);ErrorCorrectionLevel.Q=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.Q,'Q',0x03);ErrorCorrectionLevel.H=new ErrorCorrectionLevel(ErrorCorrectionLevelValues.H,'H',0x02);class FormatInformation{constructor(formatInfo){this.errorCorrectionLevel=ErrorCorrectionLevel.forBits((formatInfo>>3)&0x03);this.dataMask=(formatInfo&0x07);}
static numBitsDiffering(a,b){return Integer.bitCount(a^b);}
static decodeFormatInformation(maskedFormatInfo1,maskedFormatInfo2){const formatInfo=FormatInformation.doDecodeFormatInformation(maskedFormatInfo1,maskedFormatInfo2);if(formatInfo!==null){return formatInfo;}
return FormatInformation.doDecodeFormatInformation(maskedFormatInfo1^FormatInformation.FORMAT_INFO_MASK_QR,maskedFormatInfo2^FormatInformation.FORMAT_INFO_MASK_QR);}
static doDecodeFormatInformation(maskedFormatInfo1,maskedFormatInfo2){let bestDifference=Number.MAX_SAFE_INTEGER;let bestFormatInfo=0;for(const decodeInfo of FormatInformation.FORMAT_INFO_DECODE_LOOKUP){const targetInfo=decodeInfo[0];if(targetInfo===maskedFormatInfo1||targetInfo===maskedFormatInfo2){return new FormatInformation(decodeInfo[1]);}
let bitsDifference=FormatInformation.numBitsDiffering(maskedFormatInfo1,targetInfo);if(bitsDifference<bestDifference){bestFormatInfo=decodeInfo[1];bestDifference=bitsDifference;}
if(maskedFormatInfo1!==maskedFormatInfo2){bitsDifference=FormatInformation.numBitsDiffering(maskedFormatInfo2,targetInfo);if(bitsDifference<bestDifference){bestFormatInfo=decodeInfo[1];bestDifference=bitsDifference;}}}
if(bestDifference<=3){return new FormatInformation(bestFormatInfo);}
return null;}
getErrorCorrectionLevel(){return this.errorCorrectionLevel;}
getDataMask(){return this.dataMask;}
hashCode(){return(this.errorCorrectionLevel.getBits()<<3)|this.dataMask;}
equals(o){if(!(o instanceof FormatInformation)){return false;}
const other=o;return this.errorCorrectionLevel===other.errorCorrectionLevel&&this.dataMask===other.dataMask;}}
FormatInformation.FORMAT_INFO_MASK_QR=0x5412;FormatInformation.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([0x5412,0x00]),Int32Array.from([0x5125,0x01]),Int32Array.from([0x5E7C,0x02]),Int32Array.from([0x5B4B,0x03]),Int32Array.from([0x45F9,0x04]),Int32Array.from([0x40CE,0x05]),Int32Array.from([0x4F97,0x06]),Int32Array.from([0x4AA0,0x07]),Int32Array.from([0x77C4,0x08]),Int32Array.from([0x72F3,0x09]),Int32Array.from([0x7DAA,0x0A]),Int32Array.from([0x789D,0x0B]),Int32Array.from([0x662F,0x0C]),Int32Array.from([0x6318,0x0D]),Int32Array.from([0x6C41,0x0E]),Int32Array.from([0x6976,0x0F]),Int32Array.from([0x1689,0x10]),Int32Array.from([0x13BE,0x11]),Int32Array.from([0x1CE7,0x12]),Int32Array.from([0x19D0,0x13]),Int32Array.from([0x0762,0x14]),Int32Array.from([0x0255,0x15]),Int32Array.from([0x0D0C,0x16]),Int32Array.from([0x083B,0x17]),Int32Array.from([0x355F,0x18]),Int32Array.from([0x3068,0x19]),Int32Array.from([0x3F31,0x1A]),Int32Array.from([0x3A06,0x1B]),Int32Array.from([0x24B4,0x1C]),Int32Array.from([0x2183,0x1D]),Int32Array.from([0x2EDA,0x1E]),Int32Array.from([0x2BED,0x1F]),];class ECBlocks$1{constructor(ecCodewordsPerBlock,...ecBlocks){this.ecCodewordsPerBlock=ecCodewordsPerBlock;this.ecBlocks=ecBlocks;}
getECCodewordsPerBlock(){return this.ecCodewordsPerBlock;}
getNumBlocks(){let total=0;const ecBlocks=this.ecBlocks;for(const ecBlock of ecBlocks){total+=ecBlock.getCount();}
return total;}
getTotalECCodewords(){return this.ecCodewordsPerBlock*this.getNumBlocks();}
getECBlocks(){return this.ecBlocks;}}
class ECB$1{constructor(count,dataCodewords){this.count=count;this.dataCodewords=dataCodewords;}
getCount(){return this.count;}
getDataCodewords(){return this.dataCodewords;}}
class Version$1{constructor(versionNumber,alignmentPatternCenters,...ecBlocks){this.versionNumber=versionNumber;this.alignmentPatternCenters=alignmentPatternCenters;this.ecBlocks=ecBlocks;let total=0;const ecCodewords=ecBlocks[0].getECCodewordsPerBlock();const ecbArray=ecBlocks[0].getECBlocks();for(const ecBlock of ecbArray){total+=ecBlock.getCount()*(ecBlock.getDataCodewords()+ecCodewords);}
this.totalCodewords=total;}
getVersionNumber(){return this.versionNumber;}
getAlignmentPatternCenters(){return this.alignmentPatternCenters;}
getTotalCodewords(){return this.totalCodewords;}
getDimensionForVersion(){return 17+4*this.versionNumber;}
getECBlocksForLevel(ecLevel){return this.ecBlocks[ecLevel.getValue()];}
static getProvisionalVersionForDimension(dimension){if(dimension%4!==1){throw new FormatException();}
try{return this.getVersionForNumber((dimension-17)/4);}
catch(ignored){throw new FormatException();}}
static getVersionForNumber(versionNumber){if(versionNumber<1||versionNumber>40){throw new IllegalArgumentException();}
return Version$1.VERSIONS[versionNumber-1];}
static decodeVersionInformation(versionBits){let bestDifference=Number.MAX_SAFE_INTEGER;let bestVersion=0;for(let i=0;i<Version$1.VERSION_DECODE_INFO.length;i++){const targetVersion=Version$1.VERSION_DECODE_INFO[i];if(targetVersion===versionBits){return Version$1.getVersionForNumber(i+7);}
const bitsDifference=FormatInformation.numBitsDiffering(versionBits,targetVersion);if(bitsDifference<bestDifference){bestVersion=i+7;bestDifference=bitsDifference;}}
if(bestDifference<=3){return Version$1.getVersionForNumber(bestVersion);}
return null;}
buildFunctionPattern(){const dimension=this.getDimensionForVersion();const bitMatrix=new BitMatrix(dimension);bitMatrix.setRegion(0,0,9,9);bitMatrix.setRegion(dimension-8,0,8,9);bitMatrix.setRegion(0,dimension-8,9,8);const max=this.alignmentPatternCenters.length;for(let x=0;x<max;x++){const i=this.alignmentPatternCenters[x]-2;for(let y=0;y<max;y++){if((x===0&&(y===0||y===max-1))||(x===max-1&&y===0)){continue;}
bitMatrix.setRegion(this.alignmentPatternCenters[y]-2,i,5,5);}}
bitMatrix.setRegion(6,9,1,dimension-17);bitMatrix.setRegion(9,6,dimension-17,1);if(this.versionNumber>6){bitMatrix.setRegion(dimension-11,0,3,6);bitMatrix.setRegion(0,dimension-11,6,3);}
return bitMatrix;}
toString(){return''+this.versionNumber;}}
Version$1.VERSION_DECODE_INFO=Int32Array.from([0x07C94,0x085BC,0x09A99,0x0A4D3,0x0BBF6,0x0C762,0x0D847,0x0E60D,0x0F928,0x10B78,0x1145D,0x12A17,0x13532,0x149A6,0x15683,0x168C9,0x177EC,0x18EC4,0x191E1,0x1AFAB,0x1B08E,0x1CC1A,0x1D33F,0x1ED75,0x1F250,0x209D5,0x216F0,0x228BA,0x2379F,0x24B0B,0x2542E,0x26A64,0x27541,0x28C69]);Version$1.VERSIONS=[new Version$1(1,new Int32Array(0),new ECBlocks$1(7,new ECB$1(1,19)),new ECBlocks$1(10,new ECB$1(1,16)),new ECBlocks$1(13,new ECB$1(1,13)),new ECBlocks$1(17,new ECB$1(1,9))),new Version$1(2,Int32Array.from([6,18]),new ECBlocks$1(10,new ECB$1(1,34)),new ECBlocks$1(16,new ECB$1(1,28)),new ECBlocks$1(22,new ECB$1(1,22)),new ECBlocks$1(28,new ECB$1(1,16))),new Version$1(3,Int32Array.from([6,22]),new ECBlocks$1(15,new ECB$1(1,55)),new ECBlocks$1(26,new ECB$1(1,44)),new ECBlocks$1(18,new ECB$1(2,17)),new ECBlocks$1(22,new ECB$1(2,13))),new Version$1(4,Int32Array.from([6,26]),new ECBlocks$1(20,new ECB$1(1,80)),new ECBlocks$1(18,new ECB$1(2,32)),new ECBlocks$1(26,new ECB$1(2,24)),new ECBlocks$1(16,new ECB$1(4,9))),new Version$1(5,Int32Array.from([6,30]),new ECBlocks$1(26,new ECB$1(1,108)),new ECBlocks$1(24,new ECB$1(2,43)),new ECBlocks$1(18,new ECB$1(2,15),new ECB$1(2,16)),new ECBlocks$1(22,new ECB$1(2,11),new ECB$1(2,12))),new Version$1(6,Int32Array.from([6,34]),new ECBlocks$1(18,new ECB$1(2,68)),new ECBlocks$1(16,new ECB$1(4,27)),new ECBlocks$1(24,new ECB$1(4,19)),new ECBlocks$1(28,new ECB$1(4,15))),new Version$1(7,Int32Array.from([6,22,38]),new ECBlocks$1(20,new ECB$1(2,78)),new ECBlocks$1(18,new ECB$1(4,31)),new ECBlocks$1(18,new ECB$1(2,14),new ECB$1(4,15)),new ECBlocks$1(26,new ECB$1(4,13),new ECB$1(1,14))),new Version$1(8,Int32Array.from([6,24,42]),new ECBlocks$1(24,new ECB$1(2,97)),new ECBlocks$1(22,new ECB$1(2,38),new ECB$1(2,39)),new ECBlocks$1(22,new ECB$1(4,18),new ECB$1(2,19)),new ECBlocks$1(26,new ECB$1(4,14),new ECB$1(2,15))),new Version$1(9,Int32Array.from([6,26,46]),new ECBlocks$1(30,new ECB$1(2,116)),new ECBlocks$1(22,new ECB$1(3,36),new ECB$1(2,37)),new ECBlocks$1(20,new ECB$1(4,16),new ECB$1(4,17)),new ECBlocks$1(24,new ECB$1(4,12),new ECB$1(4,13))),new Version$1(10,Int32Array.from([6,28,50]),new ECBlocks$1(18,new ECB$1(2,68),new ECB$1(2,69)),new ECBlocks$1(26,new ECB$1(4,43),new ECB$1(1,44)),new ECBlocks$1(24,new ECB$1(6,19),new ECB$1(2,20)),new ECBlocks$1(28,new ECB$1(6,15),new ECB$1(2,16))),new Version$1(11,Int32Array.from([6,30,54]),new ECBlocks$1(20,new ECB$1(4,81)),new ECBlocks$1(30,new ECB$1(1,50),new ECB$1(4,51)),new ECBlocks$1(28,new ECB$1(4,22),new ECB$1(4,23)),new ECBlocks$1(24,new ECB$1(3,12),new ECB$1(8,13))),new Version$1(12,Int32Array.from([6,32,58]),new ECBlocks$1(24,new ECB$1(2,92),new ECB$1(2,93)),new ECBlocks$1(22,new ECB$1(6,36),new ECB$1(2,37)),new ECBlocks$1(26,new ECB$1(4,20),new ECB$1(6,21)),new ECBlocks$1(28,new ECB$1(7,14),new ECB$1(4,15))),new Version$1(13,Int32Array.from([6,34,62]),new ECBlocks$1(26,new ECB$1(4,107)),new ECBlocks$1(22,new ECB$1(8,37),new ECB$1(1,38)),new ECBlocks$1(24,new ECB$1(8,20),new ECB$1(4,21)),new ECBlocks$1(22,new ECB$1(12,11),new ECB$1(4,12))),new Version$1(14,Int32Array.from([6,26,46,66]),new ECBlocks$1(30,new ECB$1(3,115),new ECB$1(1,116)),new ECBlocks$1(24,new ECB$1(4,40),new ECB$1(5,41)),new ECBlocks$1(20,new ECB$1(11,16),new ECB$1(5,17)),new ECBlocks$1(24,new ECB$1(11,12),new ECB$1(5,13))),new Version$1(15,Int32Array.from([6,26,48,70]),new ECBlocks$1(22,new ECB$1(5,87),new ECB$1(1,88)),new ECBlocks$1(24,new ECB$1(5,41),new ECB$1(5,42)),new ECBlocks$1(30,new ECB$1(5,24),new ECB$1(7,25)),new ECBlocks$1(24,new ECB$1(11,12),new ECB$1(7,13))),new Version$1(16,Int32Array.from([6,26,50,74]),new ECBlocks$1(24,new ECB$1(5,98),new ECB$1(1,99)),new ECBlocks$1(28,new ECB$1(7,45),new ECB$1(3,46)),new ECBlocks$1(24,new ECB$1(15,19),new ECB$1(2,20)),new ECBlocks$1(30,new ECB$1(3,15),new ECB$1(13,16))),new Version$1(17,Int32Array.from([6,30,54,78]),new ECBlocks$1(28,new ECB$1(1,107),new ECB$1(5,108)),new ECBlocks$1(28,new ECB$1(10,46),new ECB$1(1,47)),new ECBlocks$1(28,new ECB$1(1,22),new ECB$1(15,23)),new ECBlocks$1(28,new ECB$1(2,14),new ECB$1(17,15))),new Version$1(18,Int32Array.from([6,30,56,82]),new ECBlocks$1(30,new ECB$1(5,120),new ECB$1(1,121)),new ECBlocks$1(26,new ECB$1(9,43),new ECB$1(4,44)),new ECBlocks$1(28,new ECB$1(17,22),new ECB$1(1,23)),new ECBlocks$1(28,new ECB$1(2,14),new ECB$1(19,15))),new Version$1(19,Int32Array.from([6,30,58,86]),new ECBlocks$1(28,new ECB$1(3,113),new ECB$1(4,114)),new ECBlocks$1(26,new ECB$1(3,44),new ECB$1(11,45)),new ECBlocks$1(26,new ECB$1(17,21),new ECB$1(4,22)),new ECBlocks$1(26,new ECB$1(9,13),new ECB$1(16,14))),new Version$1(20,Int32Array.from([6,34,62,90]),new ECBlocks$1(28,new ECB$1(3,107),new ECB$1(5,108)),new ECBlocks$1(26,new ECB$1(3,41),new ECB$1(13,42)),new ECBlocks$1(30,new ECB$1(15,24),new ECB$1(5,25)),new ECBlocks$1(28,new ECB$1(15,15),new ECB$1(10,16))),new Version$1(21,Int32Array.from([6,28,50,72,94]),new ECBlocks$1(28,new ECB$1(4,116),new ECB$1(4,117)),new ECBlocks$1(26,new ECB$1(17,42)),new ECBlocks$1(28,new ECB$1(17,22),new ECB$1(6,23)),new ECBlocks$1(30,new ECB$1(19,16),new ECB$1(6,17))),new Version$1(22,Int32Array.from([6,26,50,74,98]),new ECBlocks$1(28,new ECB$1(2,111),new ECB$1(7,112)),new ECBlocks$1(28,new ECB$1(17,46)),new ECBlocks$1(30,new ECB$1(7,24),new ECB$1(16,25)),new ECBlocks$1(24,new ECB$1(34,13))),new Version$1(23,Int32Array.from([6,30,54,78,102]),new ECBlocks$1(30,new ECB$1(4,121),new ECB$1(5,122)),new ECBlocks$1(28,new ECB$1(4,47),new ECB$1(14,48)),new ECBlocks$1(30,new ECB$1(11,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(16,15),new ECB$1(14,16))),new Version$1(24,Int32Array.from([6,28,54,80,106]),new ECBlocks$1(30,new ECB$1(6,117),new ECB$1(4,118)),new ECBlocks$1(28,new ECB$1(6,45),new ECB$1(14,46)),new ECBlocks$1(30,new ECB$1(11,24),new ECB$1(16,25)),new ECBlocks$1(30,new ECB$1(30,16),new ECB$1(2,17))),new Version$1(25,Int32Array.from([6,32,58,84,110]),new ECBlocks$1(26,new ECB$1(8,106),new ECB$1(4,107)),new ECBlocks$1(28,new ECB$1(8,47),new ECB$1(13,48)),new ECBlocks$1(30,new ECB$1(7,24),new ECB$1(22,25)),new ECBlocks$1(30,new ECB$1(22,15),new ECB$1(13,16))),new Version$1(26,Int32Array.from([6,30,58,86,114]),new ECBlocks$1(28,new ECB$1(10,114),new ECB$1(2,115)),new ECBlocks$1(28,new ECB$1(19,46),new ECB$1(4,47)),new ECBlocks$1(28,new ECB$1(28,22),new ECB$1(6,23)),new ECBlocks$1(30,new ECB$1(33,16),new ECB$1(4,17))),new Version$1(27,Int32Array.from([6,34,62,90,118]),new ECBlocks$1(30,new ECB$1(8,122),new ECB$1(4,123)),new ECBlocks$1(28,new ECB$1(22,45),new ECB$1(3,46)),new ECBlocks$1(30,new ECB$1(8,23),new ECB$1(26,24)),new ECBlocks$1(30,new ECB$1(12,15),new ECB$1(28,16))),new Version$1(28,Int32Array.from([6,26,50,74,98,122]),new ECBlocks$1(30,new ECB$1(3,117),new ECB$1(10,118)),new ECBlocks$1(28,new ECB$1(3,45),new ECB$1(23,46)),new ECBlocks$1(30,new ECB$1(4,24),new ECB$1(31,25)),new ECBlocks$1(30,new ECB$1(11,15),new ECB$1(31,16))),new Version$1(29,Int32Array.from([6,30,54,78,102,126]),new ECBlocks$1(30,new ECB$1(7,116),new ECB$1(7,117)),new ECBlocks$1(28,new ECB$1(21,45),new ECB$1(7,46)),new ECBlocks$1(30,new ECB$1(1,23),new ECB$1(37,24)),new ECBlocks$1(30,new ECB$1(19,15),new ECB$1(26,16))),new Version$1(30,Int32Array.from([6,26,52,78,104,130]),new ECBlocks$1(30,new ECB$1(5,115),new ECB$1(10,116)),new ECBlocks$1(28,new ECB$1(19,47),new ECB$1(10,48)),new ECBlocks$1(30,new ECB$1(15,24),new ECB$1(25,25)),new ECBlocks$1(30,new ECB$1(23,15),new ECB$1(25,16))),new Version$1(31,Int32Array.from([6,30,56,82,108,134]),new ECBlocks$1(30,new ECB$1(13,115),new ECB$1(3,116)),new ECBlocks$1(28,new ECB$1(2,46),new ECB$1(29,47)),new ECBlocks$1(30,new ECB$1(42,24),new ECB$1(1,25)),new ECBlocks$1(30,new ECB$1(23,15),new ECB$1(28,16))),new Version$1(32,Int32Array.from([6,34,60,86,112,138]),new ECBlocks$1(30,new ECB$1(17,115)),new ECBlocks$1(28,new ECB$1(10,46),new ECB$1(23,47)),new ECBlocks$1(30,new ECB$1(10,24),new ECB$1(35,25)),new ECBlocks$1(30,new ECB$1(19,15),new ECB$1(35,16))),new Version$1(33,Int32Array.from([6,30,58,86,114,142]),new ECBlocks$1(30,new ECB$1(17,115),new ECB$1(1,116)),new ECBlocks$1(28,new ECB$1(14,46),new ECB$1(21,47)),new ECBlocks$1(30,new ECB$1(29,24),new ECB$1(19,25)),new ECBlocks$1(30,new ECB$1(11,15),new ECB$1(46,16))),new Version$1(34,Int32Array.from([6,34,62,90,118,146]),new ECBlocks$1(30,new ECB$1(13,115),new ECB$1(6,116)),new ECBlocks$1(28,new ECB$1(14,46),new ECB$1(23,47)),new ECBlocks$1(30,new ECB$1(44,24),new ECB$1(7,25)),new ECBlocks$1(30,new ECB$1(59,16),new ECB$1(1,17))),new Version$1(35,Int32Array.from([6,30,54,78,102,126,150]),new ECBlocks$1(30,new ECB$1(12,121),new ECB$1(7,122)),new ECBlocks$1(28,new ECB$1(12,47),new ECB$1(26,48)),new ECBlocks$1(30,new ECB$1(39,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(22,15),new ECB$1(41,16))),new Version$1(36,Int32Array.from([6,24,50,76,102,128,154]),new ECBlocks$1(30,new ECB$1(6,121),new ECB$1(14,122)),new ECBlocks$1(28,new ECB$1(6,47),new ECB$1(34,48)),new ECBlocks$1(30,new ECB$1(46,24),new ECB$1(10,25)),new ECBlocks$1(30,new ECB$1(2,15),new ECB$1(64,16))),new Version$1(37,Int32Array.from([6,28,54,80,106,132,158]),new ECBlocks$1(30,new ECB$1(17,122),new ECB$1(4,123)),new ECBlocks$1(28,new ECB$1(29,46),new ECB$1(14,47)),new ECBlocks$1(30,new ECB$1(49,24),new ECB$1(10,25)),new ECBlocks$1(30,new ECB$1(24,15),new ECB$1(46,16))),new Version$1(38,Int32Array.from([6,32,58,84,110,136,162]),new ECBlocks$1(30,new ECB$1(4,122),new ECB$1(18,123)),new ECBlocks$1(28,new ECB$1(13,46),new ECB$1(32,47)),new ECBlocks$1(30,new ECB$1(48,24),new ECB$1(14,25)),new ECBlocks$1(30,new ECB$1(42,15),new ECB$1(32,16))),new Version$1(39,Int32Array.from([6,26,54,82,110,138,166]),new ECBlocks$1(30,new ECB$1(20,117),new ECB$1(4,118)),new ECBlocks$1(28,new ECB$1(40,47),new ECB$1(7,48)),new ECBlocks$1(30,new ECB$1(43,24),new ECB$1(22,25)),new ECBlocks$1(30,new ECB$1(10,15),new ECB$1(67,16))),new Version$1(40,Int32Array.from([6,30,58,86,114,142,170]),new ECBlocks$1(30,new ECB$1(19,118),new ECB$1(6,119)),new ECBlocks$1(28,new ECB$1(18,47),new ECB$1(31,48)),new ECBlocks$1(30,new ECB$1(34,24),new ECB$1(34,25)),new ECBlocks$1(30,new ECB$1(20,15),new ECB$1(61,16)))];var DataMaskValues;(function(DataMaskValues){DataMaskValues[DataMaskValues["DATA_MASK_000"]=0]="DATA_MASK_000";DataMaskValues[DataMaskValues["DATA_MASK_001"]=1]="DATA_MASK_001";DataMaskValues[DataMaskValues["DATA_MASK_010"]=2]="DATA_MASK_010";DataMaskValues[DataMaskValues["DATA_MASK_011"]=3]="DATA_MASK_011";DataMaskValues[DataMaskValues["DATA_MASK_100"]=4]="DATA_MASK_100";DataMaskValues[DataMaskValues["DATA_MASK_101"]=5]="DATA_MASK_101";DataMaskValues[DataMaskValues["DATA_MASK_110"]=6]="DATA_MASK_110";DataMaskValues[DataMaskValues["DATA_MASK_111"]=7]="DATA_MASK_111";})(DataMaskValues||(DataMaskValues={}));class DataMask{constructor(value,isMasked){this.value=value;this.isMasked=isMasked;}
unmaskBitMatrix(bits,dimension){for(let i=0;i<dimension;i++){for(let j=0;j<dimension;j++){if(this.isMasked(i,j)){bits.flip(j,i);}}}}}
DataMask.values=new Map([[DataMaskValues.DATA_MASK_000,new DataMask(DataMaskValues.DATA_MASK_000,(i,j)=>{return((i+j)&0x01)===0;})],[DataMaskValues.DATA_MASK_001,new DataMask(DataMaskValues.DATA_MASK_001,(i,j)=>{return(i&0x01)===0;})],[DataMaskValues.DATA_MASK_010,new DataMask(DataMaskValues.DATA_MASK_010,(i,j)=>{return j%3===0;})],[DataMaskValues.DATA_MASK_011,new DataMask(DataMaskValues.DATA_MASK_011,(i,j)=>{return(i+j)%3===0;})],[DataMaskValues.DATA_MASK_100,new DataMask(DataMaskValues.DATA_MASK_100,(i,j)=>{return((Math.floor(i/2)+Math.floor(j/3))&0x01)===0;})],[DataMaskValues.DATA_MASK_101,new DataMask(DataMaskValues.DATA_MASK_101,(i,j)=>{return(i*j)%6===0;})],[DataMaskValues.DATA_MASK_110,new DataMask(DataMaskValues.DATA_MASK_110,(i,j)=>{return((i*j)%6)<3;})],[DataMaskValues.DATA_MASK_111,new DataMask(DataMaskValues.DATA_MASK_111,(i,j)=>{return((i+j+((i*j)%3))&0x01)===0;})],]);class BitMatrixParser$1{constructor(bitMatrix){const dimension=bitMatrix.getHeight();if(dimension<21||(dimension&0x03)!==1){throw new FormatException();}
this.bitMatrix=bitMatrix;}
readFormatInformation(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==undefined){return this.parsedFormatInfo;}
let formatInfoBits1=0;for(let i=0;i<6;i++){formatInfoBits1=this.copyBit(i,8,formatInfoBits1);}
formatInfoBits1=this.copyBit(7,8,formatInfoBits1);formatInfoBits1=this.copyBit(8,8,formatInfoBits1);formatInfoBits1=this.copyBit(8,7,formatInfoBits1);for(let j=5;j>=0;j--){formatInfoBits1=this.copyBit(8,j,formatInfoBits1);}
const dimension=this.bitMatrix.getHeight();let formatInfoBits2=0;const jMin=dimension-7;for(let j=dimension-1;j>=jMin;j--){formatInfoBits2=this.copyBit(8,j,formatInfoBits2);}
for(let i=dimension-8;i<dimension;i++){formatInfoBits2=this.copyBit(i,8,formatInfoBits2);}
this.parsedFormatInfo=FormatInformation.decodeFormatInformation(formatInfoBits1,formatInfoBits2);if(this.parsedFormatInfo!==null){return this.parsedFormatInfo;}
throw new FormatException();}
readVersion(){if(this.parsedVersion!==null&&this.parsedVersion!==undefined){return this.parsedVersion;}
const dimension=this.bitMatrix.getHeight();const provisionalVersion=Math.floor((dimension-17)/4);if(provisionalVersion<=6){return Version$1.getVersionForNumber(provisionalVersion);}
let versionBits=0;const ijMin=dimension-11;for(let j=5;j>=0;j--){for(let i=dimension-9;i>=ijMin;i--){versionBits=this.copyBit(i,j,versionBits);}}
let theParsedVersion=Version$1.decodeVersionInformation(versionBits);if(theParsedVersion!==null&&theParsedVersion.getDimensionForVersion()===dimension){this.parsedVersion=theParsedVersion;return theParsedVersion;}
versionBits=0;for(let i=5;i>=0;i--){for(let j=dimension-9;j>=ijMin;j--){versionBits=this.copyBit(i,j,versionBits);}}
theParsedVersion=Version$1.decodeVersionInformation(versionBits);if(theParsedVersion!==null&&theParsedVersion.getDimensionForVersion()===dimension){this.parsedVersion=theParsedVersion;return theParsedVersion;}
throw new FormatException();}
copyBit(i,j,versionBits){const bit=this.isMirror?this.bitMatrix.get(j,i):this.bitMatrix.get(i,j);return bit?(versionBits<<1)|0x1:versionBits<<1;}
readCodewords(){const formatInfo=this.readFormatInformation();const version=this.readVersion();const dataMask=DataMask.values.get(formatInfo.getDataMask());const dimension=this.bitMatrix.getHeight();dataMask.unmaskBitMatrix(this.bitMatrix,dimension);const functionPattern=version.buildFunctionPattern();let readingUp=true;const result=new Uint8Array(version.getTotalCodewords());let resultOffset=0;let currentByte=0;let bitsRead=0;for(let j=dimension-1;j>0;j-=2){if(j===6){j--;}
for(let count=0;count<dimension;count++){const i=readingUp?dimension-1-count:count;for(let col=0;col<2;col++){if(!functionPattern.get(j-col,i)){bitsRead++;currentByte<<=1;if(this.bitMatrix.get(j-col,i)){currentByte|=1;}
if(bitsRead===8){result[resultOffset++]=currentByte;bitsRead=0;currentByte=0;}}}}
readingUp=!readingUp;}
if(resultOffset!==version.getTotalCodewords()){throw new FormatException();}
return result;}
remask(){if(this.parsedFormatInfo===null){return;}
const dataMask=DataMask.values[this.parsedFormatInfo.getDataMask()];const dimension=this.bitMatrix.getHeight();dataMask.unmaskBitMatrix(this.bitMatrix,dimension);}
setMirror(isMirror){this.parsedVersion=null;this.parsedFormatInfo=null;this.isMirror=isMirror;}
mirror(){const bitMatrix=this.bitMatrix;for(let x=0,width=bitMatrix.getWidth();x<width;x++){for(let y=x+1,height=bitMatrix.getHeight();y<height;y++){if(bitMatrix.get(x,y)!==bitMatrix.get(y,x)){bitMatrix.flip(y,x);bitMatrix.flip(x,y);}}}}}
class DataBlock$1{constructor(numDataCodewords,codewords){this.numDataCodewords=numDataCodewords;this.codewords=codewords;}
static getDataBlocks(rawCodewords,version,ecLevel){if(rawCodewords.length!==version.getTotalCodewords()){throw new IllegalArgumentException();}
const ecBlocks=version.getECBlocksForLevel(ecLevel);let totalBlocks=0;const ecBlockArray=ecBlocks.getECBlocks();for(const ecBlock of ecBlockArray){totalBlocks+=ecBlock.getCount();}
const result=new Array(totalBlocks);let numResultBlocks=0;for(const ecBlock of ecBlockArray){for(let i=0;i<ecBlock.getCount();i++){const numDataCodewords=ecBlock.getDataCodewords();const numBlockCodewords=ecBlocks.getECCodewordsPerBlock()+numDataCodewords;result[numResultBlocks++]=new DataBlock$1(numDataCodewords,new Uint8Array(numBlockCodewords));}}
const shorterBlocksTotalCodewords=result[0].codewords.length;let longerBlocksStartAt=result.length-1;while(longerBlocksStartAt>=0){const numCodewords=result[longerBlocksStartAt].codewords.length;if(numCodewords===shorterBlocksTotalCodewords){break;}
longerBlocksStartAt--;}
longerBlocksStartAt++;const shorterBlocksNumDataCodewords=shorterBlocksTotalCodewords-ecBlocks.getECCodewordsPerBlock();let rawCodewordsOffset=0;for(let i=0;i<shorterBlocksNumDataCodewords;i++){for(let j=0;j<numResultBlocks;j++){result[j].codewords[i]=rawCodewords[rawCodewordsOffset++];}}
for(let j=longerBlocksStartAt;j<numResultBlocks;j++){result[j].codewords[shorterBlocksNumDataCodewords]=rawCodewords[rawCodewordsOffset++];}
const max=result[0].codewords.length;for(let i=shorterBlocksNumDataCodewords;i<max;i++){for(let j=0;j<numResultBlocks;j++){const iOffset=j<longerBlocksStartAt?i:i+1;result[j].codewords[iOffset]=rawCodewords[rawCodewordsOffset++];}}
return result;}
getNumDataCodewords(){return this.numDataCodewords;}
getCodewords(){return this.codewords;}}
var ModeValues;(function(ModeValues){ModeValues[ModeValues["TERMINATOR"]=0]="TERMINATOR";ModeValues[ModeValues["NUMERIC"]=1]="NUMERIC";ModeValues[ModeValues["ALPHANUMERIC"]=2]="ALPHANUMERIC";ModeValues[ModeValues["STRUCTURED_APPEND"]=3]="STRUCTURED_APPEND";ModeValues[ModeValues["BYTE"]=4]="BYTE";ModeValues[ModeValues["ECI"]=5]="ECI";ModeValues[ModeValues["KANJI"]=6]="KANJI";ModeValues[ModeValues["FNC1_FIRST_POSITION"]=7]="FNC1_FIRST_POSITION";ModeValues[ModeValues["FNC1_SECOND_POSITION"]=8]="FNC1_SECOND_POSITION";ModeValues[ModeValues["HANZI"]=9]="HANZI";})(ModeValues||(ModeValues={}));class Mode$1{constructor(value,stringValue,characterCountBitsForVersions,bits){this.value=value;this.stringValue=stringValue;this.characterCountBitsForVersions=characterCountBitsForVersions;this.bits=bits;Mode$1.FOR_BITS.set(bits,this);Mode$1.FOR_VALUE.set(value,this);}
static forBits(bits){const mode=Mode$1.FOR_BITS.get(bits);if(undefined===mode){throw new IllegalArgumentException();}
return mode;}
getCharacterCountBits(version){const versionNumber=version.getVersionNumber();let offset;if(versionNumber<=9){offset=0;}
else if(versionNumber<=26){offset=1;}
else{offset=2;}
return this.characterCountBitsForVersions[offset];}
getValue(){return this.value;}
getBits(){return this.bits;}
equals(o){if(!(o instanceof Mode$1)){return false;}
const other=o;return this.value===other.value;}
toString(){return this.stringValue;}}
Mode$1.FOR_BITS=new Map();Mode$1.FOR_VALUE=new Map();Mode$1.TERMINATOR=new Mode$1(ModeValues.TERMINATOR,'TERMINATOR',Int32Array.from([0,0,0]),0x00);Mode$1.NUMERIC=new Mode$1(ModeValues.NUMERIC,'NUMERIC',Int32Array.from([10,12,14]),0x01);Mode$1.ALPHANUMERIC=new Mode$1(ModeValues.ALPHANUMERIC,'ALPHANUMERIC',Int32Array.from([9,11,13]),0x02);Mode$1.STRUCTURED_APPEND=new Mode$1(ModeValues.STRUCTURED_APPEND,'STRUCTURED_APPEND',Int32Array.from([0,0,0]),0x03);Mode$1.BYTE=new Mode$1(ModeValues.BYTE,'BYTE',Int32Array.from([8,16,16]),0x04);Mode$1.ECI=new Mode$1(ModeValues.ECI,'ECI',Int32Array.from([0,0,0]),0x07);Mode$1.KANJI=new Mode$1(ModeValues.KANJI,'KANJI',Int32Array.from([8,10,12]),0x08);Mode$1.FNC1_FIRST_POSITION=new Mode$1(ModeValues.FNC1_FIRST_POSITION,'FNC1_FIRST_POSITION',Int32Array.from([0,0,0]),0x05);Mode$1.FNC1_SECOND_POSITION=new Mode$1(ModeValues.FNC1_SECOND_POSITION,'FNC1_SECOND_POSITION',Int32Array.from([0,0,0]),0x09);Mode$1.HANZI=new Mode$1(ModeValues.HANZI,'HANZI',Int32Array.from([8,10,12]),0x0D);class DecodedBitStreamParser$1{static decode(bytes,version,ecLevel,hints){const bits=new BitSource(bytes);let result=new StringBuilder();const byteSegments=new Array();let symbolSequence=-1;let parityData=-1;try{let currentCharacterSetECI=null;let fc1InEffect=false;let mode;do{if(bits.available()<4){mode=Mode$1.TERMINATOR;}
else{const modeBits=bits.readBits(4);mode=Mode$1.forBits(modeBits);}
switch(mode){case Mode$1.TERMINATOR:break;case Mode$1.FNC1_FIRST_POSITION:case Mode$1.FNC1_SECOND_POSITION:fc1InEffect=true;break;case Mode$1.STRUCTURED_APPEND:if(bits.available()<16){throw new FormatException();}
symbolSequence=bits.readBits(8);parityData=bits.readBits(8);break;case Mode$1.ECI:const value=DecodedBitStreamParser$1.parseECIValue(bits);currentCharacterSetECI=CharacterSetECI.getCharacterSetECIByValue(value);if(currentCharacterSetECI===null){throw new FormatException();}
break;case Mode$1.HANZI:const subset=bits.readBits(4);const countHanzi=bits.readBits(mode.getCharacterCountBits(version));if(subset===DecodedBitStreamParser$1.GB2312_SUBSET){DecodedBitStreamParser$1.decodeHanziSegment(bits,result,countHanzi);}
break;default:const count=bits.readBits(mode.getCharacterCountBits(version));switch(mode){case Mode$1.NUMERIC:DecodedBitStreamParser$1.decodeNumericSegment(bits,result,count);break;case Mode$1.ALPHANUMERIC:DecodedBitStreamParser$1.decodeAlphanumericSegment(bits,result,count,fc1InEffect);break;case Mode$1.BYTE:DecodedBitStreamParser$1.decodeByteSegment(bits,result,count,currentCharacterSetECI,byteSegments,hints);break;case Mode$1.KANJI:DecodedBitStreamParser$1.decodeKanjiSegment(bits,result,count);break;default:throw new FormatException();}
break;}}while(mode!==Mode$1.TERMINATOR);}
catch(iae){throw new FormatException();}
return new DecoderResult(bytes,result.toString(),byteSegments.length===0?null:byteSegments,ecLevel===null?null:ecLevel.toString(),symbolSequence,parityData);}
static decodeHanziSegment(bits,result,count){if(count*13>bits.available()){throw new FormatException();}
const buffer=new Uint8Array(2*count);let offset=0;while(count>0){const twoBytes=bits.readBits(13);let assembledTwoBytes=(((twoBytes/0x060)<<8)&0xFFFFFFFF)|(twoBytes%0x060);if(assembledTwoBytes<0x003BF){assembledTwoBytes+=0x0A1A1;}
else{assembledTwoBytes+=0x0A6A1;}
buffer[offset]=((assembledTwoBytes>>8)&0xFF);buffer[offset+1]=(assembledTwoBytes&0xFF);offset+=2;count--;}
try{result.append(StringEncoding.decode(buffer,StringUtils.GB2312));}
catch(ignored){throw new FormatException(ignored);}}
static decodeKanjiSegment(bits,result,count){if(count*13>bits.available()){throw new FormatException();}
const buffer=new Uint8Array(2*count);let offset=0;while(count>0){const twoBytes=bits.readBits(13);let assembledTwoBytes=(((twoBytes/0x0C0)<<8)&0xFFFFFFFF)|(twoBytes%0x0C0);if(assembledTwoBytes<0x01F00){assembledTwoBytes+=0x08140;}
else{assembledTwoBytes+=0x0C140;}
buffer[offset]=(assembledTwoBytes>>8);buffer[offset+1]=assembledTwoBytes;offset+=2;count--;}
try{result.append(StringEncoding.decode(buffer,StringUtils.SHIFT_JIS));}
catch(ignored){throw new FormatException(ignored);}}
static decodeByteSegment(bits,result,count,currentCharacterSetECI,byteSegments,hints){if(8*count>bits.available()){throw new FormatException();}
const readBytes=new Uint8Array(count);for(let i=0;i<count;i++){readBytes[i]=bits.readBits(8);}
let encoding;if(currentCharacterSetECI===null){encoding=StringUtils.guessEncoding(readBytes,hints);}
else{encoding=currentCharacterSetECI.getName();}
try{result.append(StringEncoding.decode(readBytes,encoding));}
catch(ignored){throw new FormatException(ignored);}
byteSegments.push(readBytes);}
static toAlphaNumericChar(value){if(value>=DecodedBitStreamParser$1.ALPHANUMERIC_CHARS.length){throw new FormatException();}
return DecodedBitStreamParser$1.ALPHANUMERIC_CHARS[value];}
static decodeAlphanumericSegment(bits,result,count,fc1InEffect){const start=result.length();while(count>1){if(bits.available()<11){throw new FormatException();}
const nextTwoCharsBits=bits.readBits(11);result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(nextTwoCharsBits/45)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(nextTwoCharsBits%45));count-=2;}
if(count===1){if(bits.available()<6){throw new FormatException();}
result.append(DecodedBitStreamParser$1.toAlphaNumericChar(bits.readBits(6)));}
if(fc1InEffect){for(let i=start;i<result.length();i++){if(result.charAt(i)==='%'){if(i<result.length()-1&&result.charAt(i+1)==='%'){result.deleteCharAt(i+1);}
else{result.setCharAt(i,String.fromCharCode(0x1D));}}}}}
static decodeNumericSegment(bits,result,count){while(count>=3){if(bits.available()<10){throw new FormatException();}
const threeDigitsBits=bits.readBits(10);if(threeDigitsBits>=1000){throw new FormatException();}
result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits/100)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(threeDigitsBits/10)%10));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(threeDigitsBits%10));count-=3;}
if(count===2){if(bits.available()<7){throw new FormatException();}
const twoDigitsBits=bits.readBits(7);if(twoDigitsBits>=100){throw new FormatException();}
result.append(DecodedBitStreamParser$1.toAlphaNumericChar(Math.floor(twoDigitsBits/10)));result.append(DecodedBitStreamParser$1.toAlphaNumericChar(twoDigitsBits%10));}
else if(count===1){if(bits.available()<4){throw new FormatException();}
const digitBits=bits.readBits(4);if(digitBits>=10){throw new FormatException();}
result.append(DecodedBitStreamParser$1.toAlphaNumericChar(digitBits));}}
static parseECIValue(bits){const firstByte=bits.readBits(8);if((firstByte&0x80)===0){return firstByte&0x7F;}
if((firstByte&0xC0)===0x80){const secondByte=bits.readBits(8);return(((firstByte&0x3F)<<8)&0xFFFFFFFF)|secondByte;}
if((firstByte&0xE0)===0xC0){const secondThirdBytes=bits.readBits(16);return(((firstByte&0x1F)<<16)&0xFFFFFFFF)|secondThirdBytes;}
throw new FormatException();}}
DecodedBitStreamParser$1.ALPHANUMERIC_CHARS='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';DecodedBitStreamParser$1.GB2312_SUBSET=1;class QRCodeDecoderMetaData{constructor(mirrored){this.mirrored=mirrored;}
isMirrored(){return this.mirrored;}
applyMirroredCorrection(points){if(!this.mirrored||points===null||points.length<3){return;}
const bottomLeft=points[0];points[0]=points[2];points[2]=bottomLeft;}}
class Decoder$2{constructor(){this.rsDecoder=new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);}
decodeBooleanArray(image,hints){return this.decodeBitMatrix(BitMatrix.parseFromBooleanArray(image),hints);}
decodeBitMatrix(bits,hints){const parser=new BitMatrixParser$1(bits);let ex=null;try{return this.decodeBitMatrixParser(parser,hints);}
catch(e){ex=e;}
try{parser.remask();parser.setMirror(true);parser.readVersion();parser.readFormatInformation();parser.mirror();const result=this.decodeBitMatrixParser(parser,hints);result.setOther(new QRCodeDecoderMetaData(true));return result;}
catch(e){if(ex!==null){throw ex;}
throw e;}}
decodeBitMatrixParser(parser,hints){const version=parser.readVersion();const ecLevel=parser.readFormatInformation().getErrorCorrectionLevel();const codewords=parser.readCodewords();const dataBlocks=DataBlock$1.getDataBlocks(codewords,version,ecLevel);let totalBytes=0;for(const dataBlock of dataBlocks){totalBytes+=dataBlock.getNumDataCodewords();}
const resultBytes=new Uint8Array(totalBytes);let resultOffset=0;for(const dataBlock of dataBlocks){const codewordBytes=dataBlock.getCodewords();const numDataCodewords=dataBlock.getNumDataCodewords();this.correctErrors(codewordBytes,numDataCodewords);for(let i=0;i<numDataCodewords;i++){resultBytes[resultOffset++]=codewordBytes[i];}}
return DecodedBitStreamParser$1.decode(resultBytes,version,ecLevel,hints);}
correctErrors(codewordBytes,numDataCodewords){const codewordsInts=new Int32Array(codewordBytes);try{this.rsDecoder.decode(codewordsInts,codewordBytes.length-numDataCodewords);}
catch(ignored){throw new ChecksumException();}
for(let i=0;i<numDataCodewords;i++){codewordBytes[i]=codewordsInts[i];}}}
class AlignmentPattern extends ResultPoint{constructor(posX,posY,estimatedModuleSize){super(posX,posY);this.estimatedModuleSize=estimatedModuleSize;}
aboutEquals(moduleSize,i,j){if(Math.abs(i-this.getY())<=moduleSize&&Math.abs(j-this.getX())<=moduleSize){const moduleSizeDiff=Math.abs(moduleSize-this.estimatedModuleSize);return moduleSizeDiff<=1.0||moduleSizeDiff<=this.estimatedModuleSize;}
return false;}
combineEstimate(i,j,newModuleSize){const combinedX=(this.getX()+j)/2.0;const combinedY=(this.getY()+i)/2.0;const combinedModuleSize=(this.estimatedModuleSize+newModuleSize)/2.0;return new AlignmentPattern(combinedX,combinedY,combinedModuleSize);}}
class AlignmentPatternFinder{constructor(image,startX,startY,width,height,moduleSize,resultPointCallback){this.image=image;this.startX=startX;this.startY=startY;this.width=width;this.height=height;this.moduleSize=moduleSize;this.resultPointCallback=resultPointCallback;this.possibleCenters=[];this.crossCheckStateCount=new Int32Array(3);}
find(){const startX=this.startX;const height=this.height;const width=this.width;const maxJ=startX+width;const middleI=this.startY+(height/2);const stateCount=new Int32Array(3);const image=this.image;for(let iGen=0;iGen<height;iGen++){const i=middleI+((iGen&0x01)===0?Math.floor((iGen+1)/2):-Math.floor((iGen+1)/2));stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;let j=startX;while(j<maxJ&&!image.get(j,i)){j++;}
let currentState=0;while(j<maxJ){if(image.get(j,i)){if(currentState===1){stateCount[1]++;}
else{if(currentState===2){if(this.foundPatternCross(stateCount)){const confirmed=this.handlePossibleCenter(stateCount,i,j);if(confirmed!==null){return confirmed;}}
stateCount[0]=stateCount[2];stateCount[1]=1;stateCount[2]=0;currentState=1;}
else{stateCount[++currentState]++;}}}
else{if(currentState===1){currentState++;}
stateCount[currentState]++;}
j++;}
if(this.foundPatternCross(stateCount)){const confirmed=this.handlePossibleCenter(stateCount,i,maxJ);if(confirmed!==null){return confirmed;}}}
if(this.possibleCenters.length!==0){return this.possibleCenters[0];}
throw new NotFoundException();}
static centerFromEnd(stateCount,end){return(end-stateCount[2])-stateCount[1]/2.0;}
foundPatternCross(stateCount){const moduleSize=this.moduleSize;const maxVariance=moduleSize/2.0;for(let i=0;i<3;i++){if(Math.abs(moduleSize-stateCount[i])>=maxVariance){return false;}}
return true;}
crossCheckVertical(startI,centerJ,maxCount,originalStateCountTotal){const image=this.image;const maxI=image.getHeight();const stateCount=this.crossCheckStateCount;stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;let i=startI;while(i>=0&&image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i--;}
if(i<0||stateCount[1]>maxCount){return NaN;}
while(i>=0&&!image.get(centerJ,i)&&stateCount[0]<=maxCount){stateCount[0]++;i--;}
if(stateCount[0]>maxCount){return NaN;}
i=startI+1;while(i<maxI&&image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i++;}
if(i===maxI||stateCount[1]>maxCount){return NaN;}
while(i<maxI&&!image.get(centerJ,i)&&stateCount[2]<=maxCount){stateCount[2]++;i++;}
if(stateCount[2]>maxCount){return NaN;}
const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=2*originalStateCountTotal){return NaN;}
return this.foundPatternCross(stateCount)?AlignmentPatternFinder.centerFromEnd(stateCount,i):NaN;}
handlePossibleCenter(stateCount,i,j){const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2];const centerJ=AlignmentPatternFinder.centerFromEnd(stateCount,j);const centerI=this.crossCheckVertical(i,centerJ,2*stateCount[1],stateCountTotal);if(!isNaN(centerI)){const estimatedModuleSize=(stateCount[0]+stateCount[1]+stateCount[2])/3.0;for(const center of this.possibleCenters){if(center.aboutEquals(estimatedModuleSize,centerI,centerJ)){return center.combineEstimate(centerI,centerJ,estimatedModuleSize);}}
const point=new AlignmentPattern(centerJ,centerI,estimatedModuleSize);this.possibleCenters.push(point);if(this.resultPointCallback!==null&&this.resultPointCallback!==undefined){this.resultPointCallback.foundPossibleResultPoint(point);}}
return null;}}
class FinderPattern$1 extends ResultPoint{constructor(posX,posY,estimatedModuleSize,count){super(posX,posY);this.estimatedModuleSize=estimatedModuleSize;this.count=count;if(undefined===count){this.count=1;}}
getEstimatedModuleSize(){return this.estimatedModuleSize;}
getCount(){return this.count;}
aboutEquals(moduleSize,i,j){if(Math.abs(i-this.getY())<=moduleSize&&Math.abs(j-this.getX())<=moduleSize){const moduleSizeDiff=Math.abs(moduleSize-this.estimatedModuleSize);return moduleSizeDiff<=1.0||moduleSizeDiff<=this.estimatedModuleSize;}
return false;}
combineEstimate(i,j,newModuleSize){const combinedCount=this.count+1;const combinedX=(this.count*this.getX()+j)/combinedCount;const combinedY=(this.count*this.getY()+i)/combinedCount;const combinedModuleSize=(this.count*this.estimatedModuleSize+newModuleSize)/combinedCount;return new FinderPattern$1(combinedX,combinedY,combinedModuleSize,combinedCount);}}
class FinderPatternInfo{constructor(patternCenters){this.bottomLeft=patternCenters[0];this.topLeft=patternCenters[1];this.topRight=patternCenters[2];}
getBottomLeft(){return this.bottomLeft;}
getTopLeft(){return this.topLeft;}
getTopRight(){return this.topRight;}}
class FinderPatternFinder{constructor(image,resultPointCallback){this.image=image;this.resultPointCallback=resultPointCallback;this.possibleCenters=[];this.crossCheckStateCount=new Int32Array(5);this.resultPointCallback=resultPointCallback;}
getImage(){return this.image;}
getPossibleCenters(){return this.possibleCenters;}
find(hints){const tryHarder=(hints!==null&&hints!==undefined)&&undefined!==hints.get(DecodeHintType$1.TRY_HARDER);const pureBarcode=(hints!==null&&hints!==undefined)&&undefined!==hints.get(DecodeHintType$1.PURE_BARCODE);const image=this.image;const maxI=image.getHeight();const maxJ=image.getWidth();let iSkip=Math.floor((3*maxI)/(4*FinderPatternFinder.MAX_MODULES));if(iSkip<FinderPatternFinder.MIN_SKIP||tryHarder){iSkip=FinderPatternFinder.MIN_SKIP;}
let done=false;const stateCount=new Int32Array(5);for(let i=iSkip-1;i<maxI&&!done;i+=iSkip){stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;stateCount[3]=0;stateCount[4]=0;let currentState=0;for(let j=0;j<maxJ;j++){if(image.get(j,i)){if((currentState&1)===1){currentState++;}
stateCount[currentState]++;}
else{if((currentState&1)===0){if(currentState===4){if(FinderPatternFinder.foundPatternCross(stateCount)){const confirmed=this.handlePossibleCenter(stateCount,i,j,pureBarcode);if(confirmed===true){iSkip=2;if(this.hasSkipped===true){done=this.haveMultiplyConfirmedCenters();}
else{const rowSkip=this.findRowSkip();if(rowSkip>stateCount[2]){i+=rowSkip-stateCount[2]-iSkip;j=maxJ-1;}}}
else{stateCount[0]=stateCount[2];stateCount[1]=stateCount[3];stateCount[2]=stateCount[4];stateCount[3]=1;stateCount[4]=0;currentState=3;continue;}
currentState=0;stateCount[0]=0;stateCount[1]=0;stateCount[2]=0;stateCount[3]=0;stateCount[4]=0;}
else{stateCount[0]=stateCount[2];stateCount[1]=stateCount[3];stateCount[2]=stateCount[4];stateCount[3]=1;stateCount[4]=0;currentState=3;}}
else{stateCount[++currentState]++;}}
else{stateCount[currentState]++;}}}
if(FinderPatternFinder.foundPatternCross(stateCount)){const confirmed=this.handlePossibleCenter(stateCount,i,maxJ,pureBarcode);if(confirmed===true){iSkip=stateCount[0];if(this.hasSkipped){done=this.haveMultiplyConfirmedCenters();}}}}
const patternInfo=this.selectBestPatterns();ResultPoint.orderBestPatterns(patternInfo);return new FinderPatternInfo(patternInfo);}
static centerFromEnd(stateCount,end){return(end-stateCount[4]-stateCount[3])-stateCount[2]/2.0;}
static foundPatternCross(stateCount){let totalModuleSize=0;for(let i=0;i<5;i++){const count=stateCount[i];if(count===0){return false;}
totalModuleSize+=count;}
if(totalModuleSize<7){return false;}
const moduleSize=totalModuleSize/7.0;const maxVariance=moduleSize/2.0;return Math.abs(moduleSize-stateCount[0])<maxVariance&&Math.abs(moduleSize-stateCount[1])<maxVariance&&Math.abs(3.0*moduleSize-stateCount[2])<3*maxVariance&&Math.abs(moduleSize-stateCount[3])<maxVariance&&Math.abs(moduleSize-stateCount[4])<maxVariance;}
getCrossCheckStateCount(){const crossCheckStateCount=this.crossCheckStateCount;crossCheckStateCount[0]=0;crossCheckStateCount[1]=0;crossCheckStateCount[2]=0;crossCheckStateCount[3]=0;crossCheckStateCount[4]=0;return crossCheckStateCount;}
crossCheckDiagonal(startI,centerJ,maxCount,originalStateCountTotal){const stateCount=this.getCrossCheckStateCount();let i=0;const image=this.image;while(startI>=i&&centerJ>=i&&image.get(centerJ-i,startI-i)){stateCount[2]++;i++;}
if(startI<i||centerJ<i){return false;}
while(startI>=i&&centerJ>=i&&!image.get(centerJ-i,startI-i)&&stateCount[1]<=maxCount){stateCount[1]++;i++;}
if(startI<i||centerJ<i||stateCount[1]>maxCount){return false;}
while(startI>=i&&centerJ>=i&&image.get(centerJ-i,startI-i)&&stateCount[0]<=maxCount){stateCount[0]++;i++;}
if(stateCount[0]>maxCount){return false;}
const maxI=image.getHeight();const maxJ=image.getWidth();i=1;while(startI+i<maxI&&centerJ+i<maxJ&&image.get(centerJ+i,startI+i)){stateCount[2]++;i++;}
if(startI+i>=maxI||centerJ+i>=maxJ){return false;}
while(startI+i<maxI&&centerJ+i<maxJ&&!image.get(centerJ+i,startI+i)&&stateCount[3]<maxCount){stateCount[3]++;i++;}
if(startI+i>=maxI||centerJ+i>=maxJ||stateCount[3]>=maxCount){return false;}
while(startI+i<maxI&&centerJ+i<maxJ&&image.get(centerJ+i,startI+i)&&stateCount[4]<maxCount){stateCount[4]++;i++;}
if(stateCount[4]>=maxCount){return false;}
const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+stateCount[4];return Math.abs(stateCountTotal-originalStateCountTotal)<2*originalStateCountTotal&&FinderPatternFinder.foundPatternCross(stateCount);}
crossCheckVertical(startI,centerJ,maxCount,originalStateCountTotal){const image=this.image;const maxI=image.getHeight();const stateCount=this.getCrossCheckStateCount();let i=startI;while(i>=0&&image.get(centerJ,i)){stateCount[2]++;i--;}
if(i<0){return NaN;}
while(i>=0&&!image.get(centerJ,i)&&stateCount[1]<=maxCount){stateCount[1]++;i--;}
if(i<0||stateCount[1]>maxCount){return NaN;}
while(i>=0&&image.get(centerJ,i)&&stateCount[0]<=maxCount){stateCount[0]++;i--;}
if(stateCount[0]>maxCount){return NaN;}
i=startI+1;while(i<maxI&&image.get(centerJ,i)){stateCount[2]++;i++;}
if(i===maxI){return NaN;}
while(i<maxI&&!image.get(centerJ,i)&&stateCount[3]<maxCount){stateCount[3]++;i++;}
if(i===maxI||stateCount[3]>=maxCount){return NaN;}
while(i<maxI&&image.get(centerJ,i)&&stateCount[4]<maxCount){stateCount[4]++;i++;}
if(stateCount[4]>=maxCount){return NaN;}
const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+
stateCount[4];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=2*originalStateCountTotal){return NaN;}
return FinderPatternFinder.foundPatternCross(stateCount)?FinderPatternFinder.centerFromEnd(stateCount,i):NaN;}
crossCheckHorizontal(startJ,centerI,maxCount,originalStateCountTotal){const image=this.image;const maxJ=image.getWidth();const stateCount=this.getCrossCheckStateCount();let j=startJ;while(j>=0&&image.get(j,centerI)){stateCount[2]++;j--;}
if(j<0){return NaN;}
while(j>=0&&!image.get(j,centerI)&&stateCount[1]<=maxCount){stateCount[1]++;j--;}
if(j<0||stateCount[1]>maxCount){return NaN;}
while(j>=0&&image.get(j,centerI)&&stateCount[0]<=maxCount){stateCount[0]++;j--;}
if(stateCount[0]>maxCount){return NaN;}
j=startJ+1;while(j<maxJ&&image.get(j,centerI)){stateCount[2]++;j++;}
if(j===maxJ){return NaN;}
while(j<maxJ&&!image.get(j,centerI)&&stateCount[3]<maxCount){stateCount[3]++;j++;}
if(j===maxJ||stateCount[3]>=maxCount){return NaN;}
while(j<maxJ&&image.get(j,centerI)&&stateCount[4]<maxCount){stateCount[4]++;j++;}
if(stateCount[4]>=maxCount){return NaN;}
const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+
stateCount[4];if(5*Math.abs(stateCountTotal-originalStateCountTotal)>=originalStateCountTotal){return NaN;}
return FinderPatternFinder.foundPatternCross(stateCount)?FinderPatternFinder.centerFromEnd(stateCount,j):NaN;}
handlePossibleCenter(stateCount,i,j,pureBarcode){const stateCountTotal=stateCount[0]+stateCount[1]+stateCount[2]+stateCount[3]+
stateCount[4];let centerJ=FinderPatternFinder.centerFromEnd(stateCount,j);let centerI=this.crossCheckVertical(i,Math.floor(centerJ),stateCount[2],stateCountTotal);if(!isNaN(centerI)){centerJ=this.crossCheckHorizontal(Math.floor(centerJ),Math.floor(centerI),stateCount[2],stateCountTotal);if(!isNaN(centerJ)&&(!pureBarcode||this.crossCheckDiagonal(Math.floor(centerI),Math.floor(centerJ),stateCount[2],stateCountTotal))){const estimatedModuleSize=stateCountTotal/7.0;let found=false;const possibleCenters=this.possibleCenters;for(let index=0,length=possibleCenters.length;index<length;index++){const center=possibleCenters[index];if(center.aboutEquals(estimatedModuleSize,centerI,centerJ)){possibleCenters[index]=center.combineEstimate(centerI,centerJ,estimatedModuleSize);found=true;break;}}
if(!found){const point=new FinderPattern$1(centerJ,centerI,estimatedModuleSize);possibleCenters.push(point);if(this.resultPointCallback!==null&&this.resultPointCallback!==undefined){this.resultPointCallback.foundPossibleResultPoint(point);}}
return true;}}
return false;}
findRowSkip(){const max=this.possibleCenters.length;if(max<=1){return 0;}
let firstConfirmedCenter=null;for(const center of this.possibleCenters){if(center.getCount()>=FinderPatternFinder.CENTER_QUORUM){if(firstConfirmedCenter==null){firstConfirmedCenter=center;}
else{this.hasSkipped=true;return Math.floor((Math.abs(firstConfirmedCenter.getX()-center.getX())-
Math.abs(firstConfirmedCenter.getY()-center.getY()))/2);}}}
return 0;}
haveMultiplyConfirmedCenters(){let confirmedCount=0;let totalModuleSize=0.0;const max=this.possibleCenters.length;for(const pattern of this.possibleCenters){if(pattern.getCount()>=FinderPatternFinder.CENTER_QUORUM){confirmedCount++;totalModuleSize+=pattern.getEstimatedModuleSize();}}
if(confirmedCount<3){return false;}
const average=totalModuleSize/max;let totalDeviation=0.0;for(const pattern of this.possibleCenters){totalDeviation+=Math.abs(pattern.getEstimatedModuleSize()-average);}
return totalDeviation<=0.05*totalModuleSize;}
selectBestPatterns(){const startSize=this.possibleCenters.length;if(startSize<3){throw new NotFoundException();}
const possibleCenters=this.possibleCenters;let average;if(startSize>3){let totalModuleSize=0.0;let square=0.0;for(const center of this.possibleCenters){const size=center.getEstimatedModuleSize();totalModuleSize+=size;square+=size*size;}
average=totalModuleSize/startSize;let stdDev=Math.sqrt(square/startSize-average*average);possibleCenters.sort((center1,center2)=>{const dA=Math.abs(center2.getEstimatedModuleSize()-average);const dB=Math.abs(center1.getEstimatedModuleSize()-average);return dA<dB?-1:dA>dB?1:0;});const limit=Math.max(0.2*average,stdDev);for(let i=0;i<possibleCenters.length&&possibleCenters.length>3;i++){const pattern=possibleCenters[i];if(Math.abs(pattern.getEstimatedModuleSize()-average)>limit){possibleCenters.splice(i,1);i--;}}}
if(possibleCenters.length>3){let totalModuleSize=0.0;for(const possibleCenter of possibleCenters){totalModuleSize+=possibleCenter.getEstimatedModuleSize();}
average=totalModuleSize/possibleCenters.length;possibleCenters.sort((center1,center2)=>{if(center2.getCount()===center1.getCount()){const dA=Math.abs(center2.getEstimatedModuleSize()-average);const dB=Math.abs(center1.getEstimatedModuleSize()-average);return dA<dB?1:dA>dB?-1:0;}
else{return center2.getCount()-center1.getCount();}});possibleCenters.splice(3);}
return[possibleCenters[0],possibleCenters[1],possibleCenters[2]];}}
FinderPatternFinder.CENTER_QUORUM=2;FinderPatternFinder.MIN_SKIP=3;FinderPatternFinder.MAX_MODULES=57;class Detector$2{constructor(image){this.image=image;}
getImage(){return this.image;}
getResultPointCallback(){return this.resultPointCallback;}
detect(hints){this.resultPointCallback=(hints===null||hints===undefined)?null:hints.get(DecodeHintType$1.NEED_RESULT_POINT_CALLBACK);const finder=new FinderPatternFinder(this.image,this.resultPointCallback);const info=finder.find(hints);return this.processFinderPatternInfo(info);}
processFinderPatternInfo(info){const topLeft=info.getTopLeft();const topRight=info.getTopRight();const bottomLeft=info.getBottomLeft();const moduleSize=this.calculateModuleSize(topLeft,topRight,bottomLeft);if(moduleSize<1.0){throw new NotFoundException('No pattern found in proccess finder.');}
const dimension=Detector$2.computeDimension(topLeft,topRight,bottomLeft,moduleSize);const provisionalVersion=Version$1.getProvisionalVersionForDimension(dimension);const modulesBetweenFPCenters=provisionalVersion.getDimensionForVersion()-7;let alignmentPattern=null;if(provisionalVersion.getAlignmentPatternCenters().length>0){const bottomRightX=topRight.getX()-topLeft.getX()+bottomLeft.getX();const bottomRightY=topRight.getY()-topLeft.getY()+bottomLeft.getY();const correctionToTopLeft=1.0-3.0/modulesBetweenFPCenters;const estAlignmentX=Math.floor(topLeft.getX()+correctionToTopLeft*(bottomRightX-topLeft.getX()));const estAlignmentY=Math.floor(topLeft.getY()+correctionToTopLeft*(bottomRightY-topLeft.getY()));for(let i=4;i<=16;i<<=1){try{alignmentPattern=this.findAlignmentInRegion(moduleSize,estAlignmentX,estAlignmentY,i);break;}
catch(re){if(!(re instanceof NotFoundException)){throw re;}}}}
const transform=Detector$2.createTransform(topLeft,topRight,bottomLeft,alignmentPattern,dimension);const bits=Detector$2.sampleGrid(this.image,transform,dimension);let points;if(alignmentPattern===null){points=[bottomLeft,topLeft,topRight];}
else{points=[bottomLeft,topLeft,topRight,alignmentPattern];}
return new DetectorResult(bits,points);}
static createTransform(topLeft,topRight,bottomLeft,alignmentPattern,dimension){const dimMinusThree=dimension-3.5;let bottomRightX;let bottomRightY;let sourceBottomRightX;let sourceBottomRightY;if(alignmentPattern!==null){bottomRightX=alignmentPattern.getX();bottomRightY=alignmentPattern.getY();sourceBottomRightX=dimMinusThree-3.0;sourceBottomRightY=sourceBottomRightX;}
else{bottomRightX=(topRight.getX()-topLeft.getX())+bottomLeft.getX();bottomRightY=(topRight.getY()-topLeft.getY())+bottomLeft.getY();sourceBottomRightX=dimMinusThree;sourceBottomRightY=dimMinusThree;}
return PerspectiveTransform.quadrilateralToQuadrilateral(3.5,3.5,dimMinusThree,3.5,sourceBottomRightX,sourceBottomRightY,3.5,dimMinusThree,topLeft.getX(),topLeft.getY(),topRight.getX(),topRight.getY(),bottomRightX,bottomRightY,bottomLeft.getX(),bottomLeft.getY());}
static sampleGrid(image,transform,dimension){const sampler=GridSamplerInstance.getInstance();return sampler.sampleGridWithTransform(image,dimension,dimension,transform);}
static computeDimension(topLeft,topRight,bottomLeft,moduleSize){const tltrCentersDimension=MathUtils.round(ResultPoint.distance(topLeft,topRight)/moduleSize);const tlblCentersDimension=MathUtils.round(ResultPoint.distance(topLeft,bottomLeft)/moduleSize);let dimension=Math.floor((tltrCentersDimension+tlblCentersDimension)/2)+7;switch(dimension&0x03){case 0:dimension++;break;case 2:dimension--;break;case 3:throw new NotFoundException('Dimensions could be not found.');}
return dimension;}
calculateModuleSize(topLeft,topRight,bottomLeft){return(this.calculateModuleSizeOneWay(topLeft,topRight)+
this.calculateModuleSizeOneWay(topLeft,bottomLeft))/2.0;}
calculateModuleSizeOneWay(pattern,otherPattern){const moduleSizeEst1=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(pattern.getX()),Math.floor(pattern.getY()),Math.floor(otherPattern.getX()),Math.floor(otherPattern.getY()));const moduleSizeEst2=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(otherPattern.getX()),Math.floor(otherPattern.getY()),Math.floor(pattern.getX()),Math.floor(pattern.getY()));if(isNaN(moduleSizeEst1)){return moduleSizeEst2/7.0;}
if(isNaN(moduleSizeEst2)){return moduleSizeEst1/7.0;}
return(moduleSizeEst1+moduleSizeEst2)/14.0;}
sizeOfBlackWhiteBlackRunBothWays(fromX,fromY,toX,toY){let result=this.sizeOfBlackWhiteBlackRun(fromX,fromY,toX,toY);let scale=1.0;let otherToX=fromX-(toX-fromX);if(otherToX<0){scale=fromX/(fromX-otherToX);otherToX=0;}
else if(otherToX>=this.image.getWidth()){scale=(this.image.getWidth()-1-fromX)/(otherToX-fromX);otherToX=this.image.getWidth()-1;}
let otherToY=Math.floor(fromY-(toY-fromY)*scale);scale=1.0;if(otherToY<0){scale=fromY/(fromY-otherToY);otherToY=0;}
else if(otherToY>=this.image.getHeight()){scale=(this.image.getHeight()-1-fromY)/(otherToY-fromY);otherToY=this.image.getHeight()-1;}
otherToX=Math.floor(fromX+(otherToX-fromX)*scale);result+=this.sizeOfBlackWhiteBlackRun(fromX,fromY,otherToX,otherToY);return result-1.0;}
sizeOfBlackWhiteBlackRun(fromX,fromY,toX,toY){const steep=Math.abs(toY-fromY)>Math.abs(toX-fromX);if(steep){let temp=fromX;fromX=fromY;fromY=temp;temp=toX;toX=toY;toY=temp;}
const dx=Math.abs(toX-fromX);const dy=Math.abs(toY-fromY);let error=-dx/2;const xstep=fromX<toX?1:-1;const ystep=fromY<toY?1:-1;let state=0;const xLimit=toX+xstep;for(let x=fromX,y=fromY;x!==xLimit;x+=xstep){const realX=steep?y:x;const realY=steep?x:y;if((state===1)===this.image.get(realX,realY)){if(state===2){return MathUtils.distance(x,y,fromX,fromY);}
state++;}
error+=dy;if(error>0){if(y===toY){break;}
y+=ystep;error-=dx;}}
if(state===2){return MathUtils.distance(toX+xstep,toY,fromX,fromY);}
return NaN;}
findAlignmentInRegion(overallEstModuleSize,estAlignmentX,estAlignmentY,allowanceFactor){const allowance=Math.floor(allowanceFactor*overallEstModuleSize);const alignmentAreaLeftX=Math.max(0,estAlignmentX-allowance);const alignmentAreaRightX=Math.min(this.image.getWidth()-1,estAlignmentX+allowance);if(alignmentAreaRightX-alignmentAreaLeftX<overallEstModuleSize*3){throw new NotFoundException('Alignment top exceeds estimated module size.');}
const alignmentAreaTopY=Math.max(0,estAlignmentY-allowance);const alignmentAreaBottomY=Math.min(this.image.getHeight()-1,estAlignmentY+allowance);if(alignmentAreaBottomY-alignmentAreaTopY<overallEstModuleSize*3){throw new NotFoundException('Alignment bottom exceeds estimated module size.');}
const alignmentFinder=new AlignmentPatternFinder(this.image,alignmentAreaLeftX,alignmentAreaTopY,alignmentAreaRightX-alignmentAreaLeftX,alignmentAreaBottomY-alignmentAreaTopY,overallEstModuleSize,this.resultPointCallback);return alignmentFinder.find();}}
class QRCodeReader{constructor(){this.decoder=new Decoder$2();}
getDecoder(){return this.decoder;}
decode(image,hints){let decoderResult;let points;if(hints!==undefined&&hints!==null&&undefined!==hints.get(DecodeHintType$1.PURE_BARCODE)){const bits=QRCodeReader.extractPureBits(image.getBlackMatrix());decoderResult=this.decoder.decodeBitMatrix(bits,hints);points=QRCodeReader.NO_POINTS;}
else{const detectorResult=new Detector$2(image.getBlackMatrix()).detect(hints);decoderResult=this.decoder.decodeBitMatrix(detectorResult.getBits(),hints);points=detectorResult.getPoints();}
if(decoderResult.getOther()instanceof QRCodeDecoderMetaData){decoderResult.getOther().applyMirroredCorrection(points);}
const result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),undefined,points,BarcodeFormat$1.QR_CODE,undefined);const byteSegments=decoderResult.getByteSegments();if(byteSegments!==null){result.putMetadata(ResultMetadataType$1.BYTE_SEGMENTS,byteSegments);}
const ecLevel=decoderResult.getECLevel();if(ecLevel!==null){result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,ecLevel);}
if(decoderResult.hasStructuredAppend()){result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_SEQUENCE,decoderResult.getStructuredAppendSequenceNumber());result.putMetadata(ResultMetadataType$1.STRUCTURED_APPEND_PARITY,decoderResult.getStructuredAppendParity());}
return result;}
reset(){}
static extractPureBits(image){const leftTopBlack=image.getTopLeftOnBit();const rightBottomBlack=image.getBottomRightOnBit();if(leftTopBlack===null||rightBottomBlack===null){throw new NotFoundException();}
const moduleSize=this.moduleSize(leftTopBlack,image);let top=leftTopBlack[1];let bottom=rightBottomBlack[1];let left=leftTopBlack[0];let right=rightBottomBlack[0];if(left>=right||top>=bottom){throw new NotFoundException();}
if(bottom-top!==right-left){right=left+(bottom-top);if(right>=image.getWidth()){throw new NotFoundException();}}
const matrixWidth=Math.round((right-left+1)/moduleSize);const matrixHeight=Math.round((bottom-top+1)/moduleSize);if(matrixWidth<=0||matrixHeight<=0){throw new NotFoundException();}
if(matrixHeight!==matrixWidth){throw new NotFoundException();}
const nudge=Math.floor(moduleSize/2.0);top+=nudge;left+=nudge;const nudgedTooFarRight=left+Math.floor((matrixWidth-1)*moduleSize)-right;if(nudgedTooFarRight>0){if(nudgedTooFarRight>nudge){throw new NotFoundException();}
left-=nudgedTooFarRight;}
const nudgedTooFarDown=top+Math.floor((matrixHeight-1)*moduleSize)-bottom;if(nudgedTooFarDown>0){if(nudgedTooFarDown>nudge){throw new NotFoundException();}
top-=nudgedTooFarDown;}
const bits=new BitMatrix(matrixWidth,matrixHeight);for(let y=0;y<matrixHeight;y++){const iOffset=top+Math.floor(y*moduleSize);for(let x=0;x<matrixWidth;x++){if(image.get(left+Math.floor(x*moduleSize),iOffset)){bits.set(x,y);}}}
return bits;}
static moduleSize(leftTopBlack,image){const height=image.getHeight();const width=image.getWidth();let x=leftTopBlack[0];let y=leftTopBlack[1];let inBlack=true;let transitions=0;while(x<width&&y<height){if(inBlack!==image.get(x,y)){if(++transitions===5){break;}
inBlack=!inBlack;}
x++;y++;}
if(x===width||y===height){throw new NotFoundException();}
return(x-leftTopBlack[0])/7.0;}}
QRCodeReader.NO_POINTS=new Array();class PDF417Common{PDF417Common(){}
static getBitCountSum(moduleBitCount){return MathUtils.sum(moduleBitCount);}
static toIntArray(list){if(list==null||!list.length){return PDF417Common.EMPTY_INT_ARRAY;}
const result=new Int32Array(list.length);let i=0;for(const integer of list){result[i++]=integer;}
return result;}
static getCodeword(symbol){const i=Arrays.binarySearch(PDF417Common.SYMBOL_TABLE,symbol&0x3FFFF);if(i<0){return-1;}
return(PDF417Common.CODEWORD_TABLE[i]-1)%PDF417Common.NUMBER_OF_CODEWORDS;}}
PDF417Common.NUMBER_OF_CODEWORDS=929;PDF417Common.MAX_CODEWORDS_IN_BARCODE=PDF417Common.NUMBER_OF_CODEWORDS-1;PDF417Common.MIN_ROWS_IN_BARCODE=3;PDF417Common.MAX_ROWS_IN_BARCODE=90;PDF417Common.MODULES_IN_CODEWORD=17;PDF417Common.MODULES_IN_STOP_PATTERN=18;PDF417Common.BARS_IN_MODULE=8;PDF417Common.EMPTY_INT_ARRAY=new Int32Array([]);PDF417Common.SYMBOL_TABLE=Int32Array.from([0x1025e,0x1027a,0x1029e,0x102bc,0x102f2,0x102f4,0x1032e,0x1034e,0x1035c,0x10396,0x103a6,0x103ac,0x10422,0x10428,0x10436,0x10442,0x10444,0x10448,0x10450,0x1045e,0x10466,0x1046c,0x1047a,0x10482,0x1049e,0x104a0,0x104bc,0x104c6,0x104d8,0x104ee,0x104f2,0x104f4,0x10504,0x10508,0x10510,0x1051e,0x10520,0x1053c,0x10540,0x10578,0x10586,0x1058c,0x10598,0x105b0,0x105be,0x105ce,0x105dc,0x105e2,0x105e4,0x105e8,0x105f6,0x1062e,0x1064e,0x1065c,0x1068e,0x1069c,0x106b8,0x106de,0x106fa,0x10716,0x10726,0x1072c,0x10746,0x1074c,0x10758,0x1076e,0x10792,0x10794,0x107a2,0x107a4,0x107a8,0x107b6,0x10822,0x10828,0x10842,0x10848,0x10850,0x1085e,0x10866,0x1086c,0x1087a,0x10882,0x10884,0x10890,0x1089e,0x108a0,0x108bc,0x108c6,0x108cc,0x108d8,0x108ee,0x108f2,0x108f4,0x10902,0x10908,0x1091e,0x10920,0x1093c,0x10940,0x10978,0x10986,0x10998,0x109b0,0x109be,0x109ce,0x109dc,0x109e2,0x109e4,0x109e8,0x109f6,0x10a08,0x10a10,0x10a1e,0x10a20,0x10a3c,0x10a40,0x10a78,0x10af0,0x10b06,0x10b0c,0x10b18,0x10b30,0x10b3e,0x10b60,0x10b7c,0x10b8e,0x10b9c,0x10bb8,0x10bc2,0x10bc4,0x10bc8,0x10bd0,0x10bde,0x10be6,0x10bec,0x10c2e,0x10c4e,0x10c5c,0x10c62,0x10c64,0x10c68,0x10c76,0x10c8e,0x10c9c,0x10cb8,0x10cc2,0x10cc4,0x10cc8,0x10cd0,0x10cde,0x10ce6,0x10cec,0x10cfa,0x10d0e,0x10d1c,0x10d38,0x10d70,0x10d7e,0x10d82,0x10d84,0x10d88,0x10d90,0x10d9e,0x10da0,0x10dbc,0x10dc6,0x10dcc,0x10dd8,0x10dee,0x10df2,0x10df4,0x10e16,0x10e26,0x10e2c,0x10e46,0x10e58,0x10e6e,0x10e86,0x10e8c,0x10e98,0x10eb0,0x10ebe,0x10ece,0x10edc,0x10f0a,0x10f12,0x10f14,0x10f22,0x10f28,0x10f36,0x10f42,0x10f44,0x10f48,0x10f50,0x10f5e,0x10f66,0x10f6c,0x10fb2,0x10fb4,0x11022,0x11028,0x11042,0x11048,0x11050,0x1105e,0x1107a,0x11082,0x11084,0x11090,0x1109e,0x110a0,0x110bc,0x110c6,0x110cc,0x110d8,0x110ee,0x110f2,0x110f4,0x11102,0x1111e,0x11120,0x1113c,0x11140,0x11178,0x11186,0x11198,0x111b0,0x111be,0x111ce,0x111dc,0x111e2,0x111e4,0x111e8,0x111f6,0x11208,0x1121e,0x11220,0x11278,0x112f0,0x1130c,0x11330,0x1133e,0x11360,0x1137c,0x1138e,0x1139c,0x113b8,0x113c2,0x113c8,0x113d0,0x113de,0x113e6,0x113ec,0x11408,0x11410,0x1141e,0x11420,0x1143c,0x11440,0x11478,0x114f0,0x115e0,0x1160c,0x11618,0x11630,0x1163e,0x11660,0x1167c,0x116c0,0x116f8,0x1171c,0x11738,0x11770,0x1177e,0x11782,0x11784,0x11788,0x11790,0x1179e,0x117a0,0x117bc,0x117c6,0x117cc,0x117d8,0x117ee,0x1182e,0x11834,0x1184e,0x1185c,0x11862,0x11864,0x11868,0x11876,0x1188e,0x1189c,0x118b8,0x118c2,0x118c8,0x118d0,0x118de,0x118e6,0x118ec,0x118fa,0x1190e,0x1191c,0x11938,0x11970,0x1197e,0x11982,0x11984,0x11990,0x1199e,0x119a0,0x119bc,0x119c6,0x119cc,0x119d8,0x119ee,0x119f2,0x119f4,0x11a0e,0x11a1c,0x11a38,0x11a70,0x11a7e,0x11ae0,0x11afc,0x11b08,0x11b10,0x11b1e,0x11b20,0x11b3c,0x11b40,0x11b78,0x11b8c,0x11b98,0x11bb0,0x11bbe,0x11bce,0x11bdc,0x11be2,0x11be4,0x11be8,0x11bf6,0x11c16,0x11c26,0x11c2c,0x11c46,0x11c4c,0x11c58,0x11c6e,0x11c86,0x11c98,0x11cb0,0x11cbe,0x11cce,0x11cdc,0x11ce2,0x11ce4,0x11ce8,0x11cf6,0x11d06,0x11d0c,0x11d18,0x11d30,0x11d3e,0x11d60,0x11d7c,0x11d8e,0x11d9c,0x11db8,0x11dc4,0x11dc8,0x11dd0,0x11dde,0x11de6,0x11dec,0x11dfa,0x11e0a,0x11e12,0x11e14,0x11e22,0x11e24,0x11e28,0x11e36,0x11e42,0x11e44,0x11e50,0x11e5e,0x11e66,0x11e6c,0x11e82,0x11e84,0x11e88,0x11e90,0x11e9e,0x11ea0,0x11ebc,0x11ec6,0x11ecc,0x11ed8,0x11eee,0x11f1a,0x11f2e,0x11f32,0x11f34,0x11f4e,0x11f5c,0x11f62,0x11f64,0x11f68,0x11f76,0x12048,0x1205e,0x12082,0x12084,0x12090,0x1209e,0x120a0,0x120bc,0x120d8,0x120f2,0x120f4,0x12108,0x1211e,0x12120,0x1213c,0x12140,0x12178,0x12186,0x12198,0x121b0,0x121be,0x121e2,0x121e4,0x121e8,0x121f6,0x12204,0x12210,0x1221e,0x12220,0x12278,0x122f0,0x12306,0x1230c,0x12330,0x1233e,0x12360,0x1237c,0x1238e,0x1239c,0x123b8,0x123c2,0x123c8,0x123d0,0x123e6,0x123ec,0x1241e,0x12420,0x1243c,0x124f0,0x125e0,0x12618,0x1263e,0x12660,0x1267c,0x126c0,0x126f8,0x12738,0x12770,0x1277e,0x12782,0x12784,0x12790,0x1279e,0x127a0,0x127bc,0x127c6,0x127cc,0x127d8,0x127ee,0x12820,0x1283c,0x12840,0x12878,0x128f0,0x129e0,0x12bc0,0x12c18,0x12c30,0x12c3e,0x12c60,0x12c7c,0x12cc0,0x12cf8,0x12df0,0x12e1c,0x12e38,0x12e70,0x12e7e,0x12ee0,0x12efc,0x12f04,0x12f08,0x12f10,0x12f20,0x12f3c,0x12f40,0x12f78,0x12f86,0x12f8c,0x12f98,0x12fb0,0x12fbe,0x12fce,0x12fdc,0x1302e,0x1304e,0x1305c,0x13062,0x13068,0x1308e,0x1309c,0x130b8,0x130c2,0x130c8,0x130d0,0x130de,0x130ec,0x130fa,0x1310e,0x13138,0x13170,0x1317e,0x13182,0x13184,0x13190,0x1319e,0x131a0,0x131bc,0x131c6,0x131cc,0x131d8,0x131f2,0x131f4,0x1320e,0x1321c,0x13270,0x1327e,0x132e0,0x132fc,0x13308,0x1331e,0x13320,0x1333c,0x13340,0x13378,0x13386,0x13398,0x133b0,0x133be,0x133ce,0x133dc,0x133e2,0x133e4,0x133e8,0x133f6,0x1340e,0x1341c,0x13438,0x13470,0x1347e,0x134e0,0x134fc,0x135c0,0x135f8,0x13608,0x13610,0x1361e,0x13620,0x1363c,0x13640,0x13678,0x136f0,0x1370c,0x13718,0x13730,0x1373e,0x13760,0x1377c,0x1379c,0x137b8,0x137c2,0x137c4,0x137c8,0x137d0,0x137de,0x137e6,0x137ec,0x13816,0x13826,0x1382c,0x13846,0x1384c,0x13858,0x1386e,0x13874,0x13886,0x13898,0x138b0,0x138be,0x138ce,0x138dc,0x138e2,0x138e4,0x138e8,0x13906,0x1390c,0x13930,0x1393e,0x13960,0x1397c,0x1398e,0x1399c,0x139b8,0x139c8,0x139d0,0x139de,0x139e6,0x139ec,0x139fa,0x13a06,0x13a0c,0x13a18,0x13a30,0x13a3e,0x13a60,0x13a7c,0x13ac0,0x13af8,0x13b0e,0x13b1c,0x13b38,0x13b70,0x13b7e,0x13b88,0x13b90,0x13b9e,0x13ba0,0x13bbc,0x13bcc,0x13bd8,0x13bee,0x13bf2,0x13bf4,0x13c12,0x13c14,0x13c22,0x13c24,0x13c28,0x13c36,0x13c42,0x13c48,0x13c50,0x13c5e,0x13c66,0x13c6c,0x13c82,0x13c84,0x13c90,0x13c9e,0x13ca0,0x13cbc,0x13cc6,0x13ccc,0x13cd8,0x13cee,0x13d02,0x13d04,0x13d08,0x13d10,0x13d1e,0x13d20,0x13d3c,0x13d40,0x13d78,0x13d86,0x13d8c,0x13d98,0x13db0,0x13dbe,0x13dce,0x13ddc,0x13de4,0x13de8,0x13df6,0x13e1a,0x13e2e,0x13e32,0x13e34,0x13e4e,0x13e5c,0x13e62,0x13e64,0x13e68,0x13e76,0x13e8e,0x13e9c,0x13eb8,0x13ec2,0x13ec4,0x13ec8,0x13ed0,0x13ede,0x13ee6,0x13eec,0x13f26,0x13f2c,0x13f3a,0x13f46,0x13f4c,0x13f58,0x13f6e,0x13f72,0x13f74,0x14082,0x1409e,0x140a0,0x140bc,0x14104,0x14108,0x14110,0x1411e,0x14120,0x1413c,0x14140,0x14178,0x1418c,0x14198,0x141b0,0x141be,0x141e2,0x141e4,0x141e8,0x14208,0x14210,0x1421e,0x14220,0x1423c,0x14240,0x14278,0x142f0,0x14306,0x1430c,0x14318,0x14330,0x1433e,0x14360,0x1437c,0x1438e,0x143c2,0x143c4,0x143c8,0x143d0,0x143e6,0x143ec,0x14408,0x14410,0x1441e,0x14420,0x1443c,0x14440,0x14478,0x144f0,0x145e0,0x1460c,0x14618,0x14630,0x1463e,0x14660,0x1467c,0x146c0,0x146f8,0x1471c,0x14738,0x14770,0x1477e,0x14782,0x14784,0x14788,0x14790,0x147a0,0x147bc,0x147c6,0x147cc,0x147d8,0x147ee,0x14810,0x14820,0x1483c,0x14840,0x14878,0x148f0,0x149e0,0x14bc0,0x14c30,0x14c3e,0x14c60,0x14c7c,0x14cc0,0x14cf8,0x14df0,0x14e38,0x14e70,0x14e7e,0x14ee0,0x14efc,0x14f04,0x14f08,0x14f10,0x14f1e,0x14f20,0x14f3c,0x14f40,0x14f78,0x14f86,0x14f8c,0x14f98,0x14fb0,0x14fce,0x14fdc,0x15020,0x15040,0x15078,0x150f0,0x151e0,0x153c0,0x15860,0x1587c,0x158c0,0x158f8,0x159f0,0x15be0,0x15c70,0x15c7e,0x15ce0,0x15cfc,0x15dc0,0x15df8,0x15e08,0x15e10,0x15e20,0x15e40,0x15e78,0x15ef0,0x15f0c,0x15f18,0x15f30,0x15f60,0x15f7c,0x15f8e,0x15f9c,0x15fb8,0x1604e,0x1605c,0x1608e,0x1609c,0x160b8,0x160c2,0x160c4,0x160c8,0x160de,0x1610e,0x1611c,0x16138,0x16170,0x1617e,0x16184,0x16188,0x16190,0x1619e,0x161a0,0x161bc,0x161c6,0x161cc,0x161d8,0x161f2,0x161f4,0x1620e,0x1621c,0x16238,0x16270,0x1627e,0x162e0,0x162fc,0x16304,0x16308,0x16310,0x1631e,0x16320,0x1633c,0x16340,0x16378,0x16386,0x1638c,0x16398,0x163b0,0x163be,0x163ce,0x163dc,0x163e2,0x163e4,0x163e8,0x163f6,0x1640e,0x1641c,0x16438,0x16470,0x1647e,0x164e0,0x164fc,0x165c0,0x165f8,0x16610,0x1661e,0x16620,0x1663c,0x16640,0x16678,0x166f0,0x16718,0x16730,0x1673e,0x16760,0x1677c,0x1678e,0x1679c,0x167b8,0x167c2,0x167c4,0x167c8,0x167d0,0x167de,0x167e6,0x167ec,0x1681c,0x16838,0x16870,0x168e0,0x168fc,0x169c0,0x169f8,0x16bf0,0x16c10,0x16c1e,0x16c20,0x16c3c,0x16c40,0x16c78,0x16cf0,0x16de0,0x16e18,0x16e30,0x16e3e,0x16e60,0x16e7c,0x16ec0,0x16ef8,0x16f1c,0x16f38,0x16f70,0x16f7e,0x16f84,0x16f88,0x16f90,0x16f9e,0x16fa0,0x16fbc,0x16fc6,0x16fcc,0x16fd8,0x17026,0x1702c,0x17046,0x1704c,0x17058,0x1706e,0x17086,0x1708c,0x17098,0x170b0,0x170be,0x170ce,0x170dc,0x170e8,0x17106,0x1710c,0x17118,0x17130,0x1713e,0x17160,0x1717c,0x1718e,0x1719c,0x171b8,0x171c2,0x171c4,0x171c8,0x171d0,0x171de,0x171e6,0x171ec,0x171fa,0x17206,0x1720c,0x17218,0x17230,0x1723e,0x17260,0x1727c,0x172c0,0x172f8,0x1730e,0x1731c,0x17338,0x17370,0x1737e,0x17388,0x17390,0x1739e,0x173a0,0x173bc,0x173cc,0x173d8,0x173ee,0x173f2,0x173f4,0x1740c,0x17418,0x17430,0x1743e,0x17460,0x1747c,0x174c0,0x174f8,0x175f0,0x1760e,0x1761c,0x17638,0x17670,0x1767e,0x176e0,0x176fc,0x17708,0x17710,0x1771e,0x17720,0x1773c,0x17740,0x17778,0x17798,0x177b0,0x177be,0x177dc,0x177e2,0x177e4,0x177e8,0x17822,0x17824,0x17828,0x17836,0x17842,0x17844,0x17848,0x17850,0x1785e,0x17866,0x1786c,0x17882,0x17884,0x17888,0x17890,0x1789e,0x178a0,0x178bc,0x178c6,0x178cc,0x178d8,0x178ee,0x178f2,0x178f4,0x17902,0x17904,0x17908,0x17910,0x1791e,0x17920,0x1793c,0x17940,0x17978,0x17986,0x1798c,0x17998,0x179b0,0x179be,0x179ce,0x179dc,0x179e2,0x179e4,0x179e8,0x179f6,0x17a04,0x17a08,0x17a10,0x17a1e,0x17a20,0x17a3c,0x17a40,0x17a78,0x17af0,0x17b06,0x17b0c,0x17b18,0x17b30,0x17b3e,0x17b60,0x17b7c,0x17b8e,0x17b9c,0x17bb8,0x17bc4,0x17bc8,0x17bd0,0x17bde,0x17be6,0x17bec,0x17c2e,0x17c32,0x17c34,0x17c4e,0x17c5c,0x17c62,0x17c64,0x17c68,0x17c76,0x17c8e,0x17c9c,0x17cb8,0x17cc2,0x17cc4,0x17cc8,0x17cd0,0x17cde,0x17ce6,0x17cec,0x17d0e,0x17d1c,0x17d38,0x17d70,0x17d82,0x17d84,0x17d88,0x17d90,0x17d9e,0x17da0,0x17dbc,0x17dc6,0x17dcc,0x17dd8,0x17dee,0x17e26,0x17e2c,0x17e3a,0x17e46,0x17e4c,0x17e58,0x17e6e,0x17e72,0x17e74,0x17e86,0x17e8c,0x17e98,0x17eb0,0x17ece,0x17edc,0x17ee2,0x17ee4,0x17ee8,0x17ef6,0x1813a,0x18172,0x18174,0x18216,0x18226,0x1823a,0x1824c,0x18258,0x1826e,0x18272,0x18274,0x18298,0x182be,0x182e2,0x182e4,0x182e8,0x182f6,0x1835e,0x1837a,0x183ae,0x183d6,0x18416,0x18426,0x1842c,0x1843a,0x18446,0x18458,0x1846e,0x18472,0x18474,0x18486,0x184b0,0x184be,0x184ce,0x184dc,0x184e2,0x184e4,0x184e8,0x184f6,0x18506,0x1850c,0x18518,0x18530,0x1853e,0x18560,0x1857c,0x1858e,0x1859c,0x185b8,0x185c2,0x185c4,0x185c8,0x185d0,0x185de,0x185e6,0x185ec,0x185fa,0x18612,0x18614,0x18622,0x18628,0x18636,0x18642,0x18650,0x1865e,0x1867a,0x18682,0x18684,0x18688,0x18690,0x1869e,0x186a0,0x186bc,0x186c6,0x186cc,0x186d8,0x186ee,0x186f2,0x186f4,0x1872e,0x1874e,0x1875c,0x18796,0x187a6,0x187ac,0x187d2,0x187d4,0x18826,0x1882c,0x1883a,0x18846,0x1884c,0x18858,0x1886e,0x18872,0x18874,0x18886,0x18898,0x188b0,0x188be,0x188ce,0x188dc,0x188e2,0x188e4,0x188e8,0x188f6,0x1890c,0x18930,0x1893e,0x18960,0x1897c,0x1898e,0x189b8,0x189c2,0x189c8,0x189d0,0x189de,0x189e6,0x189ec,0x189fa,0x18a18,0x18a30,0x18a3e,0x18a60,0x18a7c,0x18ac0,0x18af8,0x18b1c,0x18b38,0x18b70,0x18b7e,0x18b82,0x18b84,0x18b88,0x18b90,0x18b9e,0x18ba0,0x18bbc,0x18bc6,0x18bcc,0x18bd8,0x18bee,0x18bf2,0x18bf4,0x18c22,0x18c24,0x18c28,0x18c36,0x18c42,0x18c48,0x18c50,0x18c5e,0x18c66,0x18c7a,0x18c82,0x18c84,0x18c90,0x18c9e,0x18ca0,0x18cbc,0x18ccc,0x18cf2,0x18cf4,0x18d04,0x18d08,0x18d10,0x18d1e,0x18d20,0x18d3c,0x18d40,0x18d78,0x18d86,0x18d98,0x18dce,0x18de2,0x18de4,0x18de8,0x18e2e,0x18e32,0x18e34,0x18e4e,0x18e5c,0x18e62,0x18e64,0x18e68,0x18e8e,0x18e9c,0x18eb8,0x18ec2,0x18ec4,0x18ec8,0x18ed0,0x18efa,0x18f16,0x18f26,0x18f2c,0x18f46,0x18f4c,0x18f58,0x18f6e,0x18f8a,0x18f92,0x18f94,0x18fa2,0x18fa4,0x18fa8,0x18fb6,0x1902c,0x1903a,0x19046,0x1904c,0x19058,0x19072,0x19074,0x19086,0x19098,0x190b0,0x190be,0x190ce,0x190dc,0x190e2,0x190e8,0x190f6,0x19106,0x1910c,0x19130,0x1913e,0x19160,0x1917c,0x1918e,0x1919c,0x191b8,0x191c2,0x191c8,0x191d0,0x191de,0x191e6,0x191ec,0x191fa,0x19218,0x1923e,0x19260,0x1927c,0x192c0,0x192f8,0x19338,0x19370,0x1937e,0x19382,0x19384,0x19390,0x1939e,0x193a0,0x193bc,0x193c6,0x193cc,0x193d8,0x193ee,0x193f2,0x193f4,0x19430,0x1943e,0x19460,0x1947c,0x194c0,0x194f8,0x195f0,0x19638,0x19670,0x1967e,0x196e0,0x196fc,0x19702,0x19704,0x19708,0x19710,0x19720,0x1973c,0x19740,0x19778,0x19786,0x1978c,0x19798,0x197b0,0x197be,0x197ce,0x197dc,0x197e2,0x197e4,0x197e8,0x19822,0x19824,0x19842,0x19848,0x19850,0x1985e,0x19866,0x1987a,0x19882,0x19884,0x19890,0x1989e,0x198a0,0x198bc,0x198cc,0x198f2,0x198f4,0x19902,0x19908,0x1991e,0x19920,0x1993c,0x19940,0x19978,0x19986,0x19998,0x199ce,0x199e2,0x199e4,0x199e8,0x19a08,0x19a10,0x19a1e,0x19a20,0x19a3c,0x19a40,0x19a78,0x19af0,0x19b18,0x19b3e,0x19b60,0x19b9c,0x19bc2,0x19bc4,0x19bc8,0x19bd0,0x19be6,0x19c2e,0x19c34,0x19c4e,0x19c5c,0x19c62,0x19c64,0x19c68,0x19c8e,0x19c9c,0x19cb8,0x19cc2,0x19cc8,0x19cd0,0x19ce6,0x19cfa,0x19d0e,0x19d1c,0x19d38,0x19d70,0x19d7e,0x19d82,0x19d84,0x19d88,0x19d90,0x19da0,0x19dcc,0x19df2,0x19df4,0x19e16,0x19e26,0x19e2c,0x19e46,0x19e4c,0x19e58,0x19e74,0x19e86,0x19e8c,0x19e98,0x19eb0,0x19ebe,0x19ece,0x19ee2,0x19ee4,0x19ee8,0x19f0a,0x19f12,0x19f14,0x19f22,0x19f24,0x19f28,0x19f42,0x19f44,0x19f48,0x19f50,0x19f5e,0x19f6c,0x19f9a,0x19fae,0x19fb2,0x19fb4,0x1a046,0x1a04c,0x1a072,0x1a074,0x1a086,0x1a08c,0x1a098,0x1a0b0,0x1a0be,0x1a0e2,0x1a0e4,0x1a0e8,0x1a0f6,0x1a106,0x1a10c,0x1a118,0x1a130,0x1a13e,0x1a160,0x1a17c,0x1a18e,0x1a19c,0x1a1b8,0x1a1c2,0x1a1c4,0x1a1c8,0x1a1d0,0x1a1de,0x1a1e6,0x1a1ec,0x1a218,0x1a230,0x1a23e,0x1a260,0x1a27c,0x1a2c0,0x1a2f8,0x1a31c,0x1a338,0x1a370,0x1a37e,0x1a382,0x1a384,0x1a388,0x1a390,0x1a39e,0x1a3a0,0x1a3bc,0x1a3c6,0x1a3cc,0x1a3d8,0x1a3ee,0x1a3f2,0x1a3f4,0x1a418,0x1a430,0x1a43e,0x1a460,0x1a47c,0x1a4c0,0x1a4f8,0x1a5f0,0x1a61c,0x1a638,0x1a670,0x1a67e,0x1a6e0,0x1a6fc,0x1a702,0x1a704,0x1a708,0x1a710,0x1a71e,0x1a720,0x1a73c,0x1a740,0x1a778,0x1a786,0x1a78c,0x1a798,0x1a7b0,0x1a7be,0x1a7ce,0x1a7dc,0x1a7e2,0x1a7e4,0x1a7e8,0x1a830,0x1a860,0x1a87c,0x1a8c0,0x1a8f8,0x1a9f0,0x1abe0,0x1ac70,0x1ac7e,0x1ace0,0x1acfc,0x1adc0,0x1adf8,0x1ae04,0x1ae08,0x1ae10,0x1ae20,0x1ae3c,0x1ae40,0x1ae78,0x1aef0,0x1af06,0x1af0c,0x1af18,0x1af30,0x1af3e,0x1af60,0x1af7c,0x1af8e,0x1af9c,0x1afb8,0x1afc4,0x1afc8,0x1afd0,0x1afde,0x1b042,0x1b05e,0x1b07a,0x1b082,0x1b084,0x1b088,0x1b090,0x1b09e,0x1b0a0,0x1b0bc,0x1b0cc,0x1b0f2,0x1b0f4,0x1b102,0x1b104,0x1b108,0x1b110,0x1b11e,0x1b120,0x1b13c,0x1b140,0x1b178,0x1b186,0x1b198,0x1b1ce,0x1b1e2,0x1b1e4,0x1b1e8,0x1b204,0x1b208,0x1b210,0x1b21e,0x1b220,0x1b23c,0x1b240,0x1b278,0x1b2f0,0x1b30c,0x1b33e,0x1b360,0x1b39c,0x1b3c2,0x1b3c4,0x1b3c8,0x1b3d0,0x1b3e6,0x1b410,0x1b41e,0x1b420,0x1b43c,0x1b440,0x1b478,0x1b4f0,0x1b5e0,0x1b618,0x1b660,0x1b67c,0x1b6c0,0x1b738,0x1b782,0x1b784,0x1b788,0x1b790,0x1b79e,0x1b7a0,0x1b7cc,0x1b82e,0x1b84e,0x1b85c,0x1b88e,0x1b89c,0x1b8b8,0x1b8c2,0x1b8c4,0x1b8c8,0x1b8d0,0x1b8e6,0x1b8fa,0x1b90e,0x1b91c,0x1b938,0x1b970,0x1b97e,0x1b982,0x1b984,0x1b988,0x1b990,0x1b99e,0x1b9a0,0x1b9cc,0x1b9f2,0x1b9f4,0x1ba0e,0x1ba1c,0x1ba38,0x1ba70,0x1ba7e,0x1bae0,0x1bafc,0x1bb08,0x1bb10,0x1bb20,0x1bb3c,0x1bb40,0x1bb98,0x1bbce,0x1bbe2,0x1bbe4,0x1bbe8,0x1bc16,0x1bc26,0x1bc2c,0x1bc46,0x1bc4c,0x1bc58,0x1bc72,0x1bc74,0x1bc86,0x1bc8c,0x1bc98,0x1bcb0,0x1bcbe,0x1bcce,0x1bce2,0x1bce4,0x1bce8,0x1bd06,0x1bd0c,0x1bd18,0x1bd30,0x1bd3e,0x1bd60,0x1bd7c,0x1bd9c,0x1bdc2,0x1bdc4,0x1bdc8,0x1bdd0,0x1bde6,0x1bdfa,0x1be12,0x1be14,0x1be22,0x1be24,0x1be28,0x1be42,0x1be44,0x1be48,0x1be50,0x1be5e,0x1be66,0x1be82,0x1be84,0x1be88,0x1be90,0x1be9e,0x1bea0,0x1bebc,0x1becc,0x1bef4,0x1bf1a,0x1bf2e,0x1bf32,0x1bf34,0x1bf4e,0x1bf5c,0x1bf62,0x1bf64,0x1bf68,0x1c09a,0x1c0b2,0x1c0b4,0x1c11a,0x1c132,0x1c134,0x1c162,0x1c164,0x1c168,0x1c176,0x1c1ba,0x1c21a,0x1c232,0x1c234,0x1c24e,0x1c25c,0x1c262,0x1c264,0x1c268,0x1c276,0x1c28e,0x1c2c2,0x1c2c4,0x1c2c8,0x1c2d0,0x1c2de,0x1c2e6,0x1c2ec,0x1c2fa,0x1c316,0x1c326,0x1c33a,0x1c346,0x1c34c,0x1c372,0x1c374,0x1c41a,0x1c42e,0x1c432,0x1c434,0x1c44e,0x1c45c,0x1c462,0x1c464,0x1c468,0x1c476,0x1c48e,0x1c49c,0x1c4b8,0x1c4c2,0x1c4c8,0x1c4d0,0x1c4de,0x1c4e6,0x1c4ec,0x1c4fa,0x1c51c,0x1c538,0x1c570,0x1c57e,0x1c582,0x1c584,0x1c588,0x1c590,0x1c59e,0x1c5a0,0x1c5bc,0x1c5c6,0x1c5cc,0x1c5d8,0x1c5ee,0x1c5f2,0x1c5f4,0x1c616,0x1c626,0x1c62c,0x1c63a,0x1c646,0x1c64c,0x1c658,0x1c66e,0x1c672,0x1c674,0x1c686,0x1c68c,0x1c698,0x1c6b0,0x1c6be,0x1c6ce,0x1c6dc,0x1c6e2,0x1c6e4,0x1c6e8,0x1c712,0x1c714,0x1c722,0x1c728,0x1c736,0x1c742,0x1c744,0x1c748,0x1c750,0x1c75e,0x1c766,0x1c76c,0x1c77a,0x1c7ae,0x1c7d6,0x1c7ea,0x1c81a,0x1c82e,0x1c832,0x1c834,0x1c84e,0x1c85c,0x1c862,0x1c864,0x1c868,0x1c876,0x1c88e,0x1c89c,0x1c8b8,0x1c8c2,0x1c8c8,0x1c8d0,0x1c8de,0x1c8e6,0x1c8ec,0x1c8fa,0x1c90e,0x1c938,0x1c970,0x1c97e,0x1c982,0x1c984,0x1c990,0x1c99e,0x1c9a0,0x1c9bc,0x1c9c6,0x1c9cc,0x1c9d8,0x1c9ee,0x1c9f2,0x1c9f4,0x1ca38,0x1ca70,0x1ca7e,0x1cae0,0x1cafc,0x1cb02,0x1cb04,0x1cb08,0x1cb10,0x1cb20,0x1cb3c,0x1cb40,0x1cb78,0x1cb86,0x1cb8c,0x1cb98,0x1cbb0,0x1cbbe,0x1cbce,0x1cbdc,0x1cbe2,0x1cbe4,0x1cbe8,0x1cbf6,0x1cc16,0x1cc26,0x1cc2c,0x1cc3a,0x1cc46,0x1cc58,0x1cc72,0x1cc74,0x1cc86,0x1ccb0,0x1ccbe,0x1ccce,0x1cce2,0x1cce4,0x1cce8,0x1cd06,0x1cd0c,0x1cd18,0x1cd30,0x1cd3e,0x1cd60,0x1cd7c,0x1cd9c,0x1cdc2,0x1cdc4,0x1cdc8,0x1cdd0,0x1cdde,0x1cde6,0x1cdfa,0x1ce22,0x1ce28,0x1ce42,0x1ce50,0x1ce5e,0x1ce66,0x1ce7a,0x1ce82,0x1ce84,0x1ce88,0x1ce90,0x1ce9e,0x1cea0,0x1cebc,0x1cecc,0x1cef2,0x1cef4,0x1cf2e,0x1cf32,0x1cf34,0x1cf4e,0x1cf5c,0x1cf62,0x1cf64,0x1cf68,0x1cf96,0x1cfa6,0x1cfac,0x1cfca,0x1cfd2,0x1cfd4,0x1d02e,0x1d032,0x1d034,0x1d04e,0x1d05c,0x1d062,0x1d064,0x1d068,0x1d076,0x1d08e,0x1d09c,0x1d0b8,0x1d0c2,0x1d0c4,0x1d0c8,0x1d0d0,0x1d0de,0x1d0e6,0x1d0ec,0x1d0fa,0x1d11c,0x1d138,0x1d170,0x1d17e,0x1d182,0x1d184,0x1d188,0x1d190,0x1d19e,0x1d1a0,0x1d1bc,0x1d1c6,0x1d1cc,0x1d1d8,0x1d1ee,0x1d1f2,0x1d1f4,0x1d21c,0x1d238,0x1d270,0x1d27e,0x1d2e0,0x1d2fc,0x1d302,0x1d304,0x1d308,0x1d310,0x1d31e,0x1d320,0x1d33c,0x1d340,0x1d378,0x1d386,0x1d38c,0x1d398,0x1d3b0,0x1d3be,0x1d3ce,0x1d3dc,0x1d3e2,0x1d3e4,0x1d3e8,0x1d3f6,0x1d470,0x1d47e,0x1d4e0,0x1d4fc,0x1d5c0,0x1d5f8,0x1d604,0x1d608,0x1d610,0x1d620,0x1d640,0x1d678,0x1d6f0,0x1d706,0x1d70c,0x1d718,0x1d730,0x1d73e,0x1d760,0x1d77c,0x1d78e,0x1d79c,0x1d7b8,0x1d7c2,0x1d7c4,0x1d7c8,0x1d7d0,0x1d7de,0x1d7e6,0x1d7ec,0x1d826,0x1d82c,0x1d83a,0x1d846,0x1d84c,0x1d858,0x1d872,0x1d874,0x1d886,0x1d88c,0x1d898,0x1d8b0,0x1d8be,0x1d8ce,0x1d8e2,0x1d8e4,0x1d8e8,0x1d8f6,0x1d90c,0x1d918,0x1d930,0x1d93e,0x1d960,0x1d97c,0x1d99c,0x1d9c2,0x1d9c4,0x1d9c8,0x1d9d0,0x1d9e6,0x1d9fa,0x1da0c,0x1da18,0x1da30,0x1da3e,0x1da60,0x1da7c,0x1dac0,0x1daf8,0x1db38,0x1db82,0x1db84,0x1db88,0x1db90,0x1db9e,0x1dba0,0x1dbcc,0x1dbf2,0x1dbf4,0x1dc22,0x1dc42,0x1dc44,0x1dc48,0x1dc50,0x1dc5e,0x1dc66,0x1dc7a,0x1dc82,0x1dc84,0x1dc88,0x1dc90,0x1dc9e,0x1dca0,0x1dcbc,0x1dccc,0x1dcf2,0x1dcf4,0x1dd04,0x1dd08,0x1dd10,0x1dd1e,0x1dd20,0x1dd3c,0x1dd40,0x1dd78,0x1dd86,0x1dd98,0x1ddce,0x1dde2,0x1dde4,0x1dde8,0x1de2e,0x1de32,0x1de34,0x1de4e,0x1de5c,0x1de62,0x1de64,0x1de68,0x1de8e,0x1de9c,0x1deb8,0x1dec2,0x1dec4,0x1dec8,0x1ded0,0x1dee6,0x1defa,0x1df16,0x1df26,0x1df2c,0x1df46,0x1df4c,0x1df58,0x1df72,0x1df74,0x1df8a,0x1df92,0x1df94,0x1dfa2,0x1dfa4,0x1dfa8,0x1e08a,0x1e092,0x1e094,0x1e0a2,0x1e0a4,0x1e0a8,0x1e0b6,0x1e0da,0x1e10a,0x1e112,0x1e114,0x1e122,0x1e124,0x1e128,0x1e136,0x1e142,0x1e144,0x1e148,0x1e150,0x1e166,0x1e16c,0x1e17a,0x1e19a,0x1e1b2,0x1e1b4,0x1e20a,0x1e212,0x1e214,0x1e222,0x1e224,0x1e228,0x1e236,0x1e242,0x1e248,0x1e250,0x1e25e,0x1e266,0x1e26c,0x1e27a,0x1e282,0x1e284,0x1e288,0x1e290,0x1e2a0,0x1e2bc,0x1e2c6,0x1e2cc,0x1e2d8,0x1e2ee,0x1e2f2,0x1e2f4,0x1e31a,0x1e332,0x1e334,0x1e35c,0x1e362,0x1e364,0x1e368,0x1e3ba,0x1e40a,0x1e412,0x1e414,0x1e422,0x1e428,0x1e436,0x1e442,0x1e448,0x1e450,0x1e45e,0x1e466,0x1e46c,0x1e47a,0x1e482,0x1e484,0x1e490,0x1e49e,0x1e4a0,0x1e4bc,0x1e4c6,0x1e4cc,0x1e4d8,0x1e4ee,0x1e4f2,0x1e4f4,0x1e502,0x1e504,0x1e508,0x1e510,0x1e51e,0x1e520,0x1e53c,0x1e540,0x1e578,0x1e586,0x1e58c,0x1e598,0x1e5b0,0x1e5be,0x1e5ce,0x1e5dc,0x1e5e2,0x1e5e4,0x1e5e8,0x1e5f6,0x1e61a,0x1e62e,0x1e632,0x1e634,0x1e64e,0x1e65c,0x1e662,0x1e668,0x1e68e,0x1e69c,0x1e6b8,0x1e6c2,0x1e6c4,0x1e6c8,0x1e6d0,0x1e6e6,0x1e6fa,0x1e716,0x1e726,0x1e72c,0x1e73a,0x1e746,0x1e74c,0x1e758,0x1e772,0x1e774,0x1e792,0x1e794,0x1e7a2,0x1e7a4,0x1e7a8,0x1e7b6,0x1e812,0x1e814,0x1e822,0x1e824,0x1e828,0x1e836,0x1e842,0x1e844,0x1e848,0x1e850,0x1e85e,0x1e866,0x1e86c,0x1e87a,0x1e882,0x1e884,0x1e888,0x1e890,0x1e89e,0x1e8a0,0x1e8bc,0x1e8c6,0x1e8cc,0x1e8d8,0x1e8ee,0x1e8f2,0x1e8f4,0x1e902,0x1e904,0x1e908,0x1e910,0x1e920,0x1e93c,0x1e940,0x1e978,0x1e986,0x1e98c,0x1e998,0x1e9b0,0x1e9be,0x1e9ce,0x1e9dc,0x1e9e2,0x1e9e4,0x1e9e8,0x1e9f6,0x1ea04,0x1ea08,0x1ea10,0x1ea20,0x1ea40,0x1ea78,0x1eaf0,0x1eb06,0x1eb0c,0x1eb18,0x1eb30,0x1eb3e,0x1eb60,0x1eb7c,0x1eb8e,0x1eb9c,0x1ebb8,0x1ebc2,0x1ebc4,0x1ebc8,0x1ebd0,0x1ebde,0x1ebe6,0x1ebec,0x1ec1a,0x1ec2e,0x1ec32,0x1ec34,0x1ec4e,0x1ec5c,0x1ec62,0x1ec64,0x1ec68,0x1ec8e,0x1ec9c,0x1ecb8,0x1ecc2,0x1ecc4,0x1ecc8,0x1ecd0,0x1ece6,0x1ecfa,0x1ed0e,0x1ed1c,0x1ed38,0x1ed70,0x1ed7e,0x1ed82,0x1ed84,0x1ed88,0x1ed90,0x1ed9e,0x1eda0,0x1edcc,0x1edf2,0x1edf4,0x1ee16,0x1ee26,0x1ee2c,0x1ee3a,0x1ee46,0x1ee4c,0x1ee58,0x1ee6e,0x1ee72,0x1ee74,0x1ee86,0x1ee8c,0x1ee98,0x1eeb0,0x1eebe,0x1eece,0x1eedc,0x1eee2,0x1eee4,0x1eee8,0x1ef12,0x1ef22,0x1ef24,0x1ef28,0x1ef36,0x1ef42,0x1ef44,0x1ef48,0x1ef50,0x1ef5e,0x1ef66,0x1ef6c,0x1ef7a,0x1efae,0x1efb2,0x1efb4,0x1efd6,0x1f096,0x1f0a6,0x1f0ac,0x1f0ba,0x1f0ca,0x1f0d2,0x1f0d4,0x1f116,0x1f126,0x1f12c,0x1f13a,0x1f146,0x1f14c,0x1f158,0x1f16e,0x1f172,0x1f174,0x1f18a,0x1f192,0x1f194,0x1f1a2,0x1f1a4,0x1f1a8,0x1f1da,0x1f216,0x1f226,0x1f22c,0x1f23a,0x1f246,0x1f258,0x1f26e,0x1f272,0x1f274,0x1f286,0x1f28c,0x1f298,0x1f2b0,0x1f2be,0x1f2ce,0x1f2dc,0x1f2e2,0x1f2e4,0x1f2e8,0x1f2f6,0x1f30a,0x1f312,0x1f314,0x1f322,0x1f328,0x1f342,0x1f344,0x1f348,0x1f350,0x1f35e,0x1f366,0x1f37a,0x1f39a,0x1f3ae,0x1f3b2,0x1f3b4,0x1f416,0x1f426,0x1f42c,0x1f43a,0x1f446,0x1f44c,0x1f458,0x1f46e,0x1f472,0x1f474,0x1f486,0x1f48c,0x1f498,0x1f4b0,0x1f4be,0x1f4ce,0x1f4dc,0x1f4e2,0x1f4e4,0x1f4e8,0x1f4f6,0x1f506,0x1f50c,0x1f518,0x1f530,0x1f53e,0x1f560,0x1f57c,0x1f58e,0x1f59c,0x1f5b8,0x1f5c2,0x1f5c4,0x1f5c8,0x1f5d0,0x1f5de,0x1f5e6,0x1f5ec,0x1f5fa,0x1f60a,0x1f612,0x1f614,0x1f622,0x1f624,0x1f628,0x1f636,0x1f642,0x1f644,0x1f648,0x1f650,0x1f65e,0x1f666,0x1f67a,0x1f682,0x1f684,0x1f688,0x1f690,0x1f69e,0x1f6a0,0x1f6bc,0x1f6cc,0x1f6f2,0x1f6f4,0x1f71a,0x1f72e,0x1f732,0x1f734,0x1f74e,0x1f75c,0x1f762,0x1f764,0x1f768,0x1f776,0x1f796,0x1f7a6,0x1f7ac,0x1f7ba,0x1f7d2,0x1f7d4,0x1f89a,0x1f8ae,0x1f8b2,0x1f8b4,0x1f8d6,0x1f8ea,0x1f91a,0x1f92e,0x1f932,0x1f934,0x1f94e,0x1f95c,0x1f962,0x1f964,0x1f968,0x1f976,0x1f996,0x1f9a6,0x1f9ac,0x1f9ba,0x1f9ca,0x1f9d2,0x1f9d4,0x1fa1a,0x1fa2e,0x1fa32,0x1fa34,0x1fa4e,0x1fa5c,0x1fa62,0x1fa64,0x1fa68,0x1fa76,0x1fa8e,0x1fa9c,0x1fab8,0x1fac2,0x1fac4,0x1fac8,0x1fad0,0x1fade,0x1fae6,0x1faec,0x1fb16,0x1fb26,0x1fb2c,0x1fb3a,0x1fb46,0x1fb4c,0x1fb58,0x1fb6e,0x1fb72,0x1fb74,0x1fb8a,0x1fb92,0x1fb94,0x1fba2,0x1fba4,0x1fba8,0x1fbb6,0x1fbda]);PDF417Common.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,2000,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,1000,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 PDF417DetectorResult{constructor(bits,points){this.bits=bits;this.points=points;}
getBits(){return this.bits;}
getPoints(){return this.points;}}
class Detector$3{static detectMultiple(image,hints,multiple){let bitMatrix=image.getBlackMatrix();let barcodeCoordinates=Detector$3.detect(multiple,bitMatrix);if(!barcodeCoordinates.length){bitMatrix=bitMatrix.clone();bitMatrix.rotate180();barcodeCoordinates=Detector$3.detect(multiple,bitMatrix);}
return new PDF417DetectorResult(bitMatrix,barcodeCoordinates);}
static detect(multiple,bitMatrix){const barcodeCoordinates=new Array();let row=0;let column=0;let foundBarcodeInRow=false;while(row<bitMatrix.getHeight()){const vertices=Detector$3.findVertices(bitMatrix,row,column);if(vertices[0]==null&&vertices[3]==null){if(!foundBarcodeInRow){break;}
foundBarcodeInRow=false;column=0;for(const barcodeCoordinate of barcodeCoordinates){if(barcodeCoordinate[1]!=null){row=Math.trunc(Math.max(row,barcodeCoordinate[1].getY()));}
if(barcodeCoordinate[3]!=null){row=Math.max(row,Math.trunc(barcodeCoordinate[3].getY()));}}
row+=Detector$3.ROW_STEP;continue;}
foundBarcodeInRow=true;barcodeCoordinates.push(vertices);if(!multiple){break;}
if(vertices[2]!=null){column=Math.trunc(vertices[2].getX());row=Math.trunc(vertices[2].getY());}
else{column=Math.trunc(vertices[4].getX());row=Math.trunc(vertices[4].getY());}}
return barcodeCoordinates;}
static findVertices(matrix,startRow,startColumn){const height=matrix.getHeight();const width=matrix.getWidth();const result=new Array(8);Detector$3.copyToResult(result,Detector$3.findRowsWithPattern(matrix,height,width,startRow,startColumn,Detector$3.START_PATTERN),Detector$3.INDEXES_START_PATTERN);if(result[4]!=null){startColumn=Math.trunc(result[4].getX());startRow=Math.trunc(result[4].getY());}
Detector$3.copyToResult(result,Detector$3.findRowsWithPattern(matrix,height,width,startRow,startColumn,Detector$3.STOP_PATTERN),Detector$3.INDEXES_STOP_PATTERN);return result;}
static copyToResult(result,tmpResult,destinationIndexes){for(let i=0;i<destinationIndexes.length;i++){result[destinationIndexes[i]]=tmpResult[i];}}
static findRowsWithPattern(matrix,height,width,startRow,startColumn,pattern){const result=new Array(4);let found=false;const counters=new Int32Array(pattern.length);for(;startRow<height;startRow+=Detector$3.ROW_STEP){let loc=Detector$3.findGuardPattern(matrix,startColumn,startRow,width,false,pattern,counters);if(loc!=null){while(startRow>0){const previousRowLoc=Detector$3.findGuardPattern(matrix,startColumn,--startRow,width,false,pattern,counters);if(previousRowLoc!=null){loc=previousRowLoc;}
else{startRow++;break;}}
result[0]=new ResultPoint(loc[0],startRow);result[1]=new ResultPoint(loc[1],startRow);found=true;break;}}
let stopRow=startRow+1;if(found){let skippedRowCount=0;let previousRowLoc=Int32Array.from([Math.trunc(result[0].getX()),Math.trunc(result[1].getX())]);for(;stopRow<height;stopRow++){const loc=Detector$3.findGuardPattern(matrix,previousRowLoc[0],stopRow,width,false,pattern,counters);if(loc!=null&&Math.abs(previousRowLoc[0]-loc[0])<Detector$3.MAX_PATTERN_DRIFT&&Math.abs(previousRowLoc[1]-loc[1])<Detector$3.MAX_PATTERN_DRIFT){previousRowLoc=loc;skippedRowCount=0;}
else{if(skippedRowCount>Detector$3.SKIPPED_ROW_COUNT_MAX){break;}
else{skippedRowCount++;}}}
stopRow-=skippedRowCount+1;result[2]=new ResultPoint(previousRowLoc[0],stopRow);result[3]=new ResultPoint(previousRowLoc[1],stopRow);}
if(stopRow-startRow<Detector$3.BARCODE_MIN_HEIGHT){Arrays.fill(result,null);}
return result;}
static findGuardPattern(matrix,column,row,width,whiteFirst,pattern,counters){Arrays.fillWithin(counters,0,counters.length,0);let patternStart=column;let pixelDrift=0;while(matrix.get(patternStart,row)&&patternStart>0&&pixelDrift++<Detector$3.MAX_PIXEL_DRIFT){patternStart--;}
let x=patternStart;let counterPosition=0;let patternLength=pattern.length;for(let isWhite=whiteFirst;x<width;x++){let pixel=matrix.get(x,row);if(pixel!==isWhite){counters[counterPosition]++;}
else{if(counterPosition===patternLength-1){if(Detector$3.patternMatchVariance(counters,pattern,Detector$3.MAX_INDIVIDUAL_VARIANCE)<Detector$3.MAX_AVG_VARIANCE){return new Int32Array([patternStart,x]);}
patternStart+=counters[0]+counters[1];System.arraycopy(counters,2,counters,0,counterPosition-1);counters[counterPosition-1]=0;counters[counterPosition]=0;counterPosition--;}
else{counterPosition++;}
counters[counterPosition]=1;isWhite=!isWhite;}}
if(counterPosition===patternLength-1&&Detector$3.patternMatchVariance(counters,pattern,Detector$3.MAX_INDIVIDUAL_VARIANCE)<Detector$3.MAX_AVG_VARIANCE){return new Int32Array([patternStart,x-1]);}
return null;}
static patternMatchVariance(counters,pattern,maxIndividualVariance){let numCounters=counters.length;let total=0;let patternLength=0;for(let i=0;i<numCounters;i++){total+=counters[i];patternLength+=pattern[i];}
if(total<patternLength){return Infinity;}
let unitBarWidth=total/patternLength;maxIndividualVariance*=unitBarWidth;let totalVariance=0.0;for(let x=0;x<numCounters;x++){let counter=counters[x];let scaledPattern=pattern[x]*unitBarWidth;let variance=counter>scaledPattern?counter-scaledPattern:scaledPattern-counter;if(variance>maxIndividualVariance){return Infinity;}
totalVariance+=variance;}
return totalVariance/total;}}
Detector$3.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]);Detector$3.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]);Detector$3.MAX_AVG_VARIANCE=0.42;Detector$3.MAX_INDIVIDUAL_VARIANCE=0.8;Detector$3.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]);Detector$3.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]);Detector$3.MAX_PIXEL_DRIFT=3;Detector$3.MAX_PATTERN_DRIFT=5;Detector$3.SKIPPED_ROW_COUNT_MAX=25;Detector$3.ROW_STEP=5;Detector$3.BARCODE_MIN_HEIGHT=10;class ModulusPoly{constructor(field,coefficients){if(coefficients.length===0){throw new IllegalArgumentException();}
this.field=field;let coefficientsLength=coefficients.length;if(coefficientsLength>1&&coefficients[0]===0){let firstNonZero=1;while(firstNonZero<coefficientsLength&&coefficients[firstNonZero]===0){firstNonZero++;}
if(firstNonZero===coefficientsLength){this.coefficients=new Int32Array([0]);}
else{this.coefficients=new Int32Array(coefficientsLength-firstNonZero);System.arraycopy(coefficients,firstNonZero,this.coefficients,0,this.coefficients.length);}}
else{this.coefficients=coefficients;}}
getCoefficients(){return this.coefficients;}
getDegree(){return this.coefficients.length-1;}
isZero(){return this.coefficients[0]===0;}
getCoefficient(degree){return this.coefficients[this.coefficients.length-1-degree];}
evaluateAt(a){if(a===0){return this.getCoefficient(0);}
if(a===1){let sum=0;for(let coefficient of this.coefficients){sum=this.field.add(sum,coefficient);}
return sum;}
let result=this.coefficients[0];let size=this.coefficients.length;for(let i=1;i<size;i++){result=this.field.add(this.field.multiply(a,result),this.coefficients[i]);}
return result;}
add(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}
if(this.isZero()){return other;}
if(other.isZero()){return this;}
let smallerCoefficients=this.coefficients;let largerCoefficients=other.coefficients;if(smallerCoefficients.length>largerCoefficients.length){let temp=smallerCoefficients;smallerCoefficients=largerCoefficients;largerCoefficients=temp;}
let sumDiff=new Int32Array(largerCoefficients.length);let lengthDiff=largerCoefficients.length-smallerCoefficients.length;System.arraycopy(largerCoefficients,0,sumDiff,0,lengthDiff);for(let i=lengthDiff;i<largerCoefficients.length;i++){sumDiff[i]=this.field.add(smallerCoefficients[i-lengthDiff],largerCoefficients[i]);}
return new ModulusPoly(this.field,sumDiff);}
subtract(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}
if(other.isZero()){return this;}
return this.add(other.negative());}
multiply(other){if(other instanceof ModulusPoly){return this.multiplyOther(other);}
return this.multiplyScalar(other);}
multiplyOther(other){if(!this.field.equals(other.field)){throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');}
if(this.isZero()||other.isZero()){return new ModulusPoly(this.field,new Int32Array([0]));}
let aCoefficients=this.coefficients;let aLength=aCoefficients.length;let bCoefficients=other.coefficients;let bLength=bCoefficients.length;let product=new Int32Array(aLength+bLength-1);for(let i=0;i<aLength;i++){let aCoeff=aCoefficients[i];for(let j=0;j<bLength;j++){product[i+j]=this.field.add(product[i+j],this.field.multiply(aCoeff,bCoefficients[j]));}}
return new ModulusPoly(this.field,product);}
negative(){let size=this.coefficients.length;let negativeCoefficients=new Int32Array(size);for(let i=0;i<size;i++){negativeCoefficients[i]=this.field.subtract(0,this.coefficients[i]);}
return new ModulusPoly(this.field,negativeCoefficients);}
multiplyScalar(scalar){if(scalar===0){return new ModulusPoly(this.field,new Int32Array([0]));}
if(scalar===1){return this;}
let size=this.coefficients.length;let product=new Int32Array(size);for(let i=0;i<size;i++){product[i]=this.field.multiply(this.coefficients[i],scalar);}
return new ModulusPoly(this.field,product);}
multiplyByMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}
if(coefficient===0){return new ModulusPoly(this.field,new Int32Array([0]));}
let size=this.coefficients.length;let product=new Int32Array(size+degree);for(let i=0;i<size;i++){product[i]=this.field.multiply(this.coefficients[i],coefficient);}
return new ModulusPoly(this.field,product);}
toString(){let result=new StringBuilder();for(let degree=this.getDegree();degree>=0;degree--){let coefficient=this.getCoefficient(degree);if(coefficient!==0){if(coefficient<0){result.append(' - ');coefficient=-coefficient;}
else{if(result.length()>0){result.append(' + ');}}
if(degree===0||coefficient!==1){result.append(coefficient);}
if(degree!==0){if(degree===1){result.append('x');}
else{result.append('x^');result.append(degree);}}}}
return result.toString();}}
class ModulusBase{add(a,b){return(a+b)%this.modulus;}
subtract(a,b){return(this.modulus+a-b)%this.modulus;}
exp(a){return this.expTable[a];}
log(a){if(a===0){throw new IllegalArgumentException();}
return this.logTable[a];}
inverse(a){if(a===0){throw new ArithmeticException();}
return this.expTable[this.modulus-this.logTable[a]-1];}
multiply(a,b){if(a===0||b===0){return 0;}
return this.expTable[(this.logTable[a]+this.logTable[b])%(this.modulus-1)];}
getSize(){return this.modulus;}
equals(o){return o===this;}}
class ModulusGF extends ModulusBase{constructor(modulus,generator){super();this.modulus=modulus;this.expTable=new Int32Array(modulus);this.logTable=new Int32Array(modulus);let x=1;for(let i=0;i<modulus;i++){this.expTable[i]=x;x=(x*generator)%modulus;}
for(let i=0;i<modulus-1;i++){this.logTable[this.expTable[i]]=i;}
this.zero=new ModulusPoly(this,new Int32Array([0]));this.one=new ModulusPoly(this,new Int32Array([1]));}
getZero(){return this.zero;}
getOne(){return this.one;}
buildMonomial(degree,coefficient){if(degree<0){throw new IllegalArgumentException();}
if(coefficient===0){return this.zero;}
let coefficients=new Int32Array(degree+1);coefficients[0]=coefficient;return new ModulusPoly(this,coefficients);}}
ModulusGF.PDF417_GF=new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS,3);class ErrorCorrection{constructor(){this.field=ModulusGF.PDF417_GF;}
decode(received,numECCodewords,erasures){let poly=new ModulusPoly(this.field,received);let S=new Int32Array(numECCodewords);let error=false;for(let i=numECCodewords;i>0;i--){let evaluation=poly.evaluateAt(this.field.exp(i));S[numECCodewords-i]=evaluation;if(evaluation!==0){error=true;}}
if(!error){return 0;}
let knownErrors=this.field.getOne();if(erasures!=null){for(const erasure of erasures){let b=this.field.exp(received.length-1-erasure);let term=new ModulusPoly(this.field,new Int32Array([this.field.subtract(0,b),1]));knownErrors=knownErrors.multiply(term);}}
let syndrome=new ModulusPoly(this.field,S);let sigmaOmega=this.runEuclideanAlgorithm(this.field.buildMonomial(numECCodewords,1),syndrome,numECCodewords);let sigma=sigmaOmega[0];let omega=sigmaOmega[1];let errorLocations=this.findErrorLocations(sigma);let errorMagnitudes=this.findErrorMagnitudes(omega,sigma,errorLocations);for(let i=0;i<errorLocations.length;i++){let position=received.length-1-this.field.log(errorLocations[i]);if(position<0){throw ChecksumException.getChecksumInstance();}
received[position]=this.field.subtract(received[position],errorMagnitudes[i]);}
return errorLocations.length;}
runEuclideanAlgorithm(a,b,R){if(a.getDegree()<b.getDegree()){let temp=a;a=b;b=temp;}
let rLast=a;let r=b;let tLast=this.field.getZero();let t=this.field.getOne();while(r.getDegree()>=Math.round(R/2)){let rLastLast=rLast;let tLastLast=tLast;rLast=r;tLast=t;if(rLast.isZero()){throw ChecksumException.getChecksumInstance();}
r=rLastLast;let q=this.field.getZero();let denominatorLeadingTerm=rLast.getCoefficient(rLast.getDegree());let dltInverse=this.field.inverse(denominatorLeadingTerm);while(r.getDegree()>=rLast.getDegree()&&!r.isZero()){let degreeDiff=r.getDegree()-rLast.getDegree();let scale=this.field.multiply(r.getCoefficient(r.getDegree()),dltInverse);q=q.add(this.field.buildMonomial(degreeDiff,scale));r=r.subtract(rLast.multiplyByMonomial(degreeDiff,scale));}
t=q.multiply(tLast).subtract(tLastLast).negative();}
let sigmaTildeAtZero=t.getCoefficient(0);if(sigmaTildeAtZero===0){throw ChecksumException.getChecksumInstance();}
let inverse=this.field.inverse(sigmaTildeAtZero);let sigma=t.multiply(inverse);let omega=r.multiply(inverse);return[sigma,omega];}
findErrorLocations(errorLocator){let numErrors=errorLocator.getDegree();let result=new Int32Array(numErrors);let e=0;for(let i=1;i<this.field.getSize()&&e<numErrors;i++){if(errorLocator.evaluateAt(i)===0){result[e]=this.field.inverse(i);e++;}}
if(e!==numErrors){throw ChecksumException.getChecksumInstance();}
return result;}
findErrorMagnitudes(errorEvaluator,errorLocator,errorLocations){let errorLocatorDegree=errorLocator.getDegree();let formalDerivativeCoefficients=new Int32Array(errorLocatorDegree);for(let i=1;i<=errorLocatorDegree;i++){formalDerivativeCoefficients[errorLocatorDegree-i]=this.field.multiply(i,errorLocator.getCoefficient(i));}
let formalDerivative=new ModulusPoly(this.field,formalDerivativeCoefficients);let s=errorLocations.length;let result=new Int32Array(s);for(let i=0;i<s;i++){let xiInverse=this.field.inverse(errorLocations[i]);let numerator=this.field.subtract(0,errorEvaluator.evaluateAt(xiInverse));let denominator=this.field.inverse(formalDerivative.evaluateAt(xiInverse));result[i]=this.field.multiply(numerator,denominator);}
return result;}}
class BoundingBox{constructor(image,topLeft,bottomLeft,topRight,bottomRight){if(image instanceof BoundingBox){this.constructor_2(image);}
else{this.constructor_1(image,topLeft,bottomLeft,topRight,bottomRight);}}
constructor_1(image,topLeft,bottomLeft,topRight,bottomRight){const leftUnspecified=topLeft==null||bottomLeft==null;const rightUnspecified=topRight==null||bottomRight==null;if(leftUnspecified&&rightUnspecified){throw new NotFoundException();}
if(leftUnspecified){topLeft=new ResultPoint(0,topRight.getY());bottomLeft=new ResultPoint(0,bottomRight.getY());}
else if(rightUnspecified){topRight=new ResultPoint(image.getWidth()-1,topLeft.getY());bottomRight=new ResultPoint(image.getWidth()-1,bottomLeft.getY());}
this.image=image;this.topLeft=topLeft;this.bottomLeft=bottomLeft;this.topRight=topRight;this.bottomRight=bottomRight;this.minX=Math.trunc(Math.min(topLeft.getX(),bottomLeft.getX()));this.maxX=Math.trunc(Math.max(topRight.getX(),bottomRight.getX()));this.minY=Math.trunc(Math.min(topLeft.getY(),topRight.getY()));this.maxY=Math.trunc(Math.max(bottomLeft.getY(),bottomRight.getY()));}
constructor_2(boundingBox){this.image=boundingBox.image;this.topLeft=boundingBox.getTopLeft();this.bottomLeft=boundingBox.getBottomLeft();this.topRight=boundingBox.getTopRight();this.bottomRight=boundingBox.getBottomRight();this.minX=boundingBox.getMinX();this.maxX=boundingBox.getMaxX();this.minY=boundingBox.getMinY();this.maxY=boundingBox.getMaxY();}
static merge(leftBox,rightBox){if(leftBox==null){return rightBox;}
if(rightBox==null){return leftBox;}
return new BoundingBox(leftBox.image,leftBox.topLeft,leftBox.bottomLeft,rightBox.topRight,rightBox.bottomRight);}
addMissingRows(missingStartRows,missingEndRows,isLeft){let newTopLeft=this.topLeft;let newBottomLeft=this.bottomLeft;let newTopRight=this.topRight;let newBottomRight=this.bottomRight;if(missingStartRows>0){let top=isLeft?this.topLeft:this.topRight;let newMinY=Math.trunc(top.getY()-missingStartRows);if(newMinY<0){newMinY=0;}
let newTop=new ResultPoint(top.getX(),newMinY);if(isLeft){newTopLeft=newTop;}
else{newTopRight=newTop;}}
if(missingEndRows>0){let bottom=isLeft?this.bottomLeft:this.bottomRight;let newMaxY=Math.trunc(bottom.getY()+missingEndRows);if(newMaxY>=this.image.getHeight()){newMaxY=this.image.getHeight()-1;}
let newBottom=new ResultPoint(bottom.getX(),newMaxY);if(isLeft){newBottomLeft=newBottom;}
else{newBottomRight=newBottom;}}
return new BoundingBox(this.image,newTopLeft,newBottomLeft,newTopRight,newBottomRight);}
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 BarcodeMetadata{constructor(columnCount,rowCountUpperPart,rowCountLowerPart,errorCorrectionLevel){this.columnCount=columnCount;this.errorCorrectionLevel=errorCorrectionLevel;this.rowCountUpperPart=rowCountUpperPart;this.rowCountLowerPart=rowCountLowerPart;this.rowCount=rowCountUpperPart+rowCountLowerPart;}
getColumnCount(){return this.columnCount;}
getErrorCorrectionLevel(){return this.errorCorrectionLevel;}
getRowCount(){return this.rowCount;}
getRowCountUpperPart(){return this.rowCountUpperPart;}
getRowCountLowerPart(){return this.rowCountLowerPart;}}
class Formatter{constructor(){this.buffer='';}
static form(str,arr){let i=-1;function callback(exp,p0,p1,p2,p3,p4){if(exp==='%%')
return'%';if(arr[++i]===undefined)
return undefined;exp=p2?parseInt(p2.substr(1)):undefined;let base=p3?parseInt(p3.substr(1)):undefined;let val;switch(p4){case's':val=arr[i];break;case'c':val=arr[i][0];break;case'f':val=parseFloat(arr[i]).toFixed(exp);break;case'p':val=parseFloat(arr[i]).toPrecision(exp);break;case'e':val=parseFloat(arr[i]).toExponential(exp);break;case'x':val=parseInt(arr[i]).toString(base?base:16);break;case'd':val=parseFloat(parseInt(arr[i],base?base:10).toPrecision(exp)).toFixed(0);break;}
val=typeof val==='object'?JSON.stringify(val):(+val).toString(base);let size=parseInt(p1);let ch=p1&&(p1[0]+'')==='0'?'0':' ';while(val.length<size)
val=p0!==undefined?val+ch:ch+val;return val;}
let regex=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return str.replace(regex,callback);}
format(append,...args){this.buffer+=Formatter.form(append,args);}
toString(){return this.buffer;}}
class DetectionResultColumn{constructor(boundingBox){this.boundingBox=new BoundingBox(boundingBox);this.codewords=new Array(boundingBox.getMaxY()-boundingBox.getMinY()+1);}
getCodewordNearby(imageRow){let codeword=this.getCodeword(imageRow);if(codeword!=null){return codeword;}
for(let i=1;i<DetectionResultColumn.MAX_NEARBY_DISTANCE;i++){let nearImageRow=this.imageRowToCodewordIndex(imageRow)-i;if(nearImageRow>=0){codeword=this.codewords[nearImageRow];if(codeword!=null){return codeword;}}
nearImageRow=this.imageRowToCodewordIndex(imageRow)+i;if(nearImageRow<this.codewords.length){codeword=this.codewords[nearImageRow];if(codeword!=null){return codeword;}}}
return null;}
imageRowToCodewordIndex(imageRow){return imageRow-this.boundingBox.getMinY();}
setCodeword(imageRow,codeword){this.codewords[this.imageRowToCodewordIndex(imageRow)]=codeword;}
getCodeword(imageRow){return this.codewords[this.imageRowToCodewordIndex(imageRow)];}
getBoundingBox(){return this.boundingBox;}
getCodewords(){return this.codewords;}
toString(){const formatter=new Formatter();let row=0;for(const codeword of this.codewords){if(codeword==null){formatter.format('%3d:    |   %n',row++);continue;}
formatter.format('%3d: %3d|%3d%n',row++,codeword.getRowNumber(),codeword.getValue());}
return formatter.toString();}}
DetectionResultColumn.MAX_NEARBY_DISTANCE=5;class BarcodeValue{constructor(){this.values=new Map();}
setValue(value){value=Math.trunc(value);let confidence=this.values.get(value);if(confidence==null){confidence=0;}
confidence++;this.values.set(value,confidence);}
getValue(){let maxConfidence=-1;let result=new Array();for(const[key,value]of this.values.entries()){const entry={getKey:()=>key,getValue:()=>value,};if(entry.getValue()>maxConfidence){maxConfidence=entry.getValue();result=[];result.push(entry.getKey());}
else if(entry.getValue()===maxConfidence){result.push(entry.getKey());}}
return PDF417Common.toIntArray(result);}
getConfidence(value){return this.values.get(value);}}
class DetectionResultRowIndicatorColumn extends DetectionResultColumn{constructor(boundingBox,isLeft){super(boundingBox);this._isLeft=isLeft;}
setRowNumbers(){for(let codeword of this.getCodewords()){if(codeword!=null){codeword.setRowNumberAsRowIndicatorColumn();}}}
adjustCompleteIndicatorColumnRowNumbers(barcodeMetadata){let codewords=this.getCodewords();this.setRowNumbers();this.removeIncorrectCodewords(codewords,barcodeMetadata);let boundingBox=this.getBoundingBox();let top=this._isLeft?boundingBox.getTopLeft():boundingBox.getTopRight();let bottom=this._isLeft?boundingBox.getBottomLeft():boundingBox.getBottomRight();let firstRow=this.imageRowToCodewordIndex(Math.trunc(top.getY()));let lastRow=this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));let barcodeRow=-1;let maxRowHeight=1;let currentRowHeight=0;for(let codewordsRow=firstRow;codewordsRow<lastRow;codewordsRow++){if(codewords[codewordsRow]==null){continue;}
let codeword=codewords[codewordsRow];let rowDifference=codeword.getRowNumber()-barcodeRow;if(rowDifference===0){currentRowHeight++;}
else if(rowDifference===1){maxRowHeight=Math.max(maxRowHeight,currentRowHeight);currentRowHeight=1;barcodeRow=codeword.getRowNumber();}
else if(rowDifference<0||codeword.getRowNumber()>=barcodeMetadata.getRowCount()||rowDifference>codewordsRow){codewords[codewordsRow]=null;}
else{let checkedRows;if(maxRowHeight>2){checkedRows=(maxRowHeight-2)*rowDifference;}
else{checkedRows=rowDifference;}
let closePreviousCodewordFound=checkedRows>=codewordsRow;for(let i=1;i<=checkedRows&&!closePreviousCodewordFound;i++){closePreviousCodewordFound=codewords[codewordsRow-i]!=null;}
if(closePreviousCodewordFound){codewords[codewordsRow]=null;}
else{barcodeRow=codeword.getRowNumber();currentRowHeight=1;}}}}
getRowHeights(){let barcodeMetadata=this.getBarcodeMetadata();if(barcodeMetadata==null){return null;}
this.adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata);let result=new Int32Array(barcodeMetadata.getRowCount());for(let codeword of this.getCodewords()){if(codeword!=null){let rowNumber=codeword.getRowNumber();if(rowNumber>=result.length){continue;}
result[rowNumber]++;}}
return result;}
adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata){let boundingBox=this.getBoundingBox();let top=this._isLeft?boundingBox.getTopLeft():boundingBox.getTopRight();let bottom=this._isLeft?boundingBox.getBottomLeft():boundingBox.getBottomRight();let firstRow=this.imageRowToCodewordIndex(Math.trunc(top.getY()));let lastRow=this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));let codewords=this.getCodewords();let barcodeRow=-1;for(let codewordsRow=firstRow;codewordsRow<lastRow;codewordsRow++){if(codewords[codewordsRow]==null){continue;}
let codeword=codewords[codewordsRow];codeword.setRowNumberAsRowIndicatorColumn();let rowDifference=codeword.getRowNumber()-barcodeRow;if(rowDifference===0);else if(rowDifference===1){barcodeRow=codeword.getRowNumber();}
else if(codeword.getRowNumber()>=barcodeMetadata.getRowCount()){codewords[codewordsRow]=null;}
else{barcodeRow=codeword.getRowNumber();}}}
getBarcodeMetadata(){let codewords=this.getCodewords();let barcodeColumnCount=new BarcodeValue();let barcodeRowCountUpperPart=new BarcodeValue();let barcodeRowCountLowerPart=new BarcodeValue();let barcodeECLevel=new BarcodeValue();for(let codeword of codewords){if(codeword==null){continue;}
codeword.setRowNumberAsRowIndicatorColumn();let rowIndicatorValue=codeword.getValue()%30;let codewordRowNumber=codeword.getRowNumber();if(!this._isLeft){codewordRowNumber+=2;}
switch(codewordRowNumber%3){case 0:barcodeRowCountUpperPart.setValue(rowIndicatorValue*3+1);break;case 1:barcodeECLevel.setValue(rowIndicatorValue/3);barcodeRowCountLowerPart.setValue(rowIndicatorValue%3);break;case 2:barcodeColumnCount.setValue(rowIndicatorValue+1);break;}}
if((barcodeColumnCount.getValue().length===0)||(barcodeRowCountUpperPart.getValue().length===0)||(barcodeRowCountLowerPart.getValue().length===0)||(barcodeECLevel.getValue().length===0)||barcodeColumnCount.getValue()[0]<1||barcodeRowCountUpperPart.getValue()[0]+barcodeRowCountLowerPart.getValue()[0]<PDF417Common.MIN_ROWS_IN_BARCODE||barcodeRowCountUpperPart.getValue()[0]+barcodeRowCountLowerPart.getValue()[0]>PDF417Common.MAX_ROWS_IN_BARCODE){return null;}
let barcodeMetadata=new BarcodeMetadata(barcodeColumnCount.getValue()[0],barcodeRowCountUpperPart.getValue()[0],barcodeRowCountLowerPart.getValue()[0],barcodeECLevel.getValue()[0]);this.removeIncorrectCodewords(codewords,barcodeMetadata);return barcodeMetadata;}
removeIncorrectCodewords(codewords,barcodeMetadata){for(let codewordRow=0;codewordRow<codewords.length;codewordRow++){let codeword=codewords[codewordRow];if(codewords[codewordRow]==null){continue;}
let rowIndicatorValue=codeword.getValue()%30;let codewordRowNumber=codeword.getRowNumber();if(codewordRowNumber>barcodeMetadata.getRowCount()){codewords[codewordRow]=null;continue;}
if(!this._isLeft){codewordRowNumber+=2;}
switch(codewordRowNumber%3){case 0:if(rowIndicatorValue*3+1!==barcodeMetadata.getRowCountUpperPart()){codewords[codewordRow]=null;}
break;case 1:if(Math.trunc(rowIndicatorValue/3)!==barcodeMetadata.getErrorCorrectionLevel()||rowIndicatorValue%3!==barcodeMetadata.getRowCountLowerPart()){codewords[codewordRow]=null;}
break;case 2:if(rowIndicatorValue+1!==barcodeMetadata.getColumnCount()){codewords[codewordRow]=null;}
break;}}}
isLeft(){return this._isLeft;}
toString(){return'IsLeft: '+this._isLeft+'\n'+super.toString();}}
class DetectionResult{constructor(barcodeMetadata,boundingBox){this.ADJUST_ROW_NUMBER_SKIP=2;this.barcodeMetadata=barcodeMetadata;this.barcodeColumnCount=barcodeMetadata.getColumnCount();this.boundingBox=boundingBox;this.detectionResultColumns=new Array(this.barcodeColumnCount+2);}
getDetectionResultColumns(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]);this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);let unadjustedCodewordCount=PDF417Common.MAX_CODEWORDS_IN_BARCODE;let previousUnadjustedCount;do{previousUnadjustedCount=unadjustedCodewordCount;unadjustedCodewordCount=this.adjustRowNumbersAndGetCount();}while(unadjustedCodewordCount>0&&unadjustedCodewordCount<previousUnadjustedCount);return this.detectionResultColumns;}
adjustIndicatorColumnRowNumbers(detectionResultColumn){if(detectionResultColumn!=null){detectionResultColumn.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata);}}
adjustRowNumbersAndGetCount(){let unadjustedCount=this.adjustRowNumbersByRow();if(unadjustedCount===0){return 0;}
for(let barcodeColumn=1;barcodeColumn<this.barcodeColumnCount+1;barcodeColumn++){let codewords=this.detectionResultColumns[barcodeColumn].getCodewords();for(let codewordsRow=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}
if(!codewords[codewordsRow].hasValidRowNumber()){this.adjustRowNumbers(barcodeColumn,codewordsRow,codewords);}}}
return unadjustedCount;}
adjustRowNumbersByRow(){this.adjustRowNumbersFromBothRI();let unadjustedCount=this.adjustRowNumbersFromLRI();return unadjustedCount+this.adjustRowNumbersFromRRI();}
adjustRowNumbersFromBothRI(){if(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null){return;}
let LRIcodewords=this.detectionResultColumns[0].getCodewords();let RRIcodewords=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let codewordsRow=0;codewordsRow<LRIcodewords.length;codewordsRow++){if(LRIcodewords[codewordsRow]!=null&&RRIcodewords[codewordsRow]!=null&&LRIcodewords[codewordsRow].getRowNumber()===RRIcodewords[codewordsRow].getRowNumber()){for(let barcodeColumn=1;barcodeColumn<=this.barcodeColumnCount;barcodeColumn++){let codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword==null){continue;}
codeword.setRowNumber(LRIcodewords[codewordsRow].getRowNumber());if(!codeword.hasValidRowNumber()){this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow]=null;}}}}}
adjustRowNumbersFromRRI(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null){return 0;}
let unadjustedCount=0;let codewords=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords();for(let codewordsRow=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}
let rowIndicatorRowNumber=codewords[codewordsRow].getRowNumber();let invalidRowCounts=0;for(let barcodeColumn=this.barcodeColumnCount+1;barcodeColumn>0&&invalidRowCounts<this.ADJUST_ROW_NUMBER_SKIP;barcodeColumn--){let codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword!=null){invalidRowCounts=DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword);if(!codeword.hasValidRowNumber()){unadjustedCount++;}}}}
return unadjustedCount;}
adjustRowNumbersFromLRI(){if(this.detectionResultColumns[0]==null){return 0;}
let unadjustedCount=0;let codewords=this.detectionResultColumns[0].getCodewords();for(let codewordsRow=0;codewordsRow<codewords.length;codewordsRow++){if(codewords[codewordsRow]==null){continue;}
let rowIndicatorRowNumber=codewords[codewordsRow].getRowNumber();let invalidRowCounts=0;for(let barcodeColumn=1;barcodeColumn<this.barcodeColumnCount+1&&invalidRowCounts<this.ADJUST_ROW_NUMBER_SKIP;barcodeColumn++){let codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword!=null){invalidRowCounts=DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword);if(!codeword.hasValidRowNumber()){unadjustedCount++;}}}}
return unadjustedCount;}
static adjustRowNumberIfValid(rowIndicatorRowNumber,invalidRowCounts,codeword){if(codeword==null){return invalidRowCounts;}
if(!codeword.hasValidRowNumber()){if(codeword.isValidRowNumber(rowIndicatorRowNumber)){codeword.setRowNumber(rowIndicatorRowNumber);invalidRowCounts=0;}
else{++invalidRowCounts;}}
return invalidRowCounts;}
adjustRowNumbers(barcodeColumn,codewordsRow,codewords){if(this.detectionResultColumns[barcodeColumn-1]==null){return;}
let codeword=codewords[codewordsRow];let previousColumnCodewords=this.detectionResultColumns[barcodeColumn-1].getCodewords();let nextColumnCodewords=previousColumnCodewords;if(this.detectionResultColumns[barcodeColumn+1]!=null){nextColumnCodewords=this.detectionResultColumns[barcodeColumn+1].getCodewords();}
let otherCodewords=new Array(14);otherCodewords[2]=previousColumnCodewords[codewordsRow];otherCodewords[3]=nextColumnCodewords[codewordsRow];if(codewordsRow>0){otherCodewords[0]=codewords[codewordsRow-1];otherCodewords[4]=previousColumnCodewords[codewordsRow-1];otherCodewords[5]=nextColumnCodewords[codewordsRow-1];}
if(codewordsRow>1){otherCodewords[8]=codewords[codewordsRow-2];otherCodewords[10]=previousColumnCodewords[codewordsRow-2];otherCodewords[11]=nextColumnCodewords[codewordsRow-2];}
if(codewordsRow<codewords.length-1){otherCodewords[1]=codewords[codewordsRow+1];otherCodewords[6]=previousColumnCodewords[codewordsRow+1];otherCodewords[7]=nextColumnCodewords[codewordsRow+1];}
if(codewordsRow<codewords.length-2){otherCodewords[9]=codewords[codewordsRow+2];otherCodewords[12]=previousColumnCodewords[codewordsRow+2];otherCodewords[13]=nextColumnCodewords[codewordsRow+2];}
for(let otherCodeword of otherCodewords){if(DetectionResult.adjustRowNumber(codeword,otherCodeword)){return;}}}
static adjustRowNumber(codeword,otherCodeword){if(otherCodeword==null){return false;}
if(otherCodeword.hasValidRowNumber()&&otherCodeword.getBucket()===codeword.getBucket()){codeword.setRowNumber(otherCodeword.getRowNumber());return true;}
return false;}
getBarcodeColumnCount(){return this.barcodeColumnCount;}
getBarcodeRowCount(){return this.barcodeMetadata.getRowCount();}
getBarcodeECLevel(){return this.barcodeMetadata.getErrorCorrectionLevel();}
setBoundingBox(boundingBox){this.boundingBox=boundingBox;}
getBoundingBox(){return this.boundingBox;}
setDetectionResultColumn(barcodeColumn,detectionResultColumn){this.detectionResultColumns[barcodeColumn]=detectionResultColumn;}
getDetectionResultColumn(barcodeColumn){return this.detectionResultColumns[barcodeColumn];}
toString(){let rowIndicatorColumn=this.detectionResultColumns[0];if(rowIndicatorColumn==null){rowIndicatorColumn=this.detectionResultColumns[this.barcodeColumnCount+1];}
let formatter=new Formatter();for(let codewordsRow=0;codewordsRow<rowIndicatorColumn.getCodewords().length;codewordsRow++){formatter.format('CW %3d:',codewordsRow);for(let barcodeColumn=0;barcodeColumn<this.barcodeColumnCount+2;barcodeColumn++){if(this.detectionResultColumns[barcodeColumn]==null){formatter.format('    |   ');continue;}
let codeword=this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];if(codeword==null){formatter.format('    |   ');continue;}
formatter.format(' %3d|%3d',codeword.getRowNumber(),codeword.getValue());}
formatter.format('%n');}
return formatter.toString();}}
class Codeword{constructor(startX,endX,bucket,value){this.rowNumber=Codeword.BARCODE_ROW_UNKNOWN;this.startX=Math.trunc(startX);this.endX=Math.trunc(endX);this.bucket=Math.trunc(bucket);this.value=Math.trunc(value);}
hasValidRowNumber(){return this.isValidRowNumber(this.rowNumber);}
isValidRowNumber(rowNumber){return rowNumber!==Codeword.BARCODE_ROW_UNKNOWN&&this.bucket===(rowNumber%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(rowNumber){this.rowNumber=rowNumber;}
toString(){return this.rowNumber+'|'+this.value;}}
Codeword.BARCODE_ROW_UNKNOWN=-1;class PDF417CodewordDecoder{static initialize(){for(let i=0;i<PDF417Common.SYMBOL_TABLE.length;i++){let currentSymbol=PDF417Common.SYMBOL_TABLE[i];let currentBit=currentSymbol&0x1;for(let j=0;j<PDF417Common.BARS_IN_MODULE;j++){let size=0.0;while((currentSymbol&0x1)===currentBit){size+=1.0;currentSymbol>>=1;}
currentBit=currentSymbol&0x1;if(!PDF417CodewordDecoder.RATIOS_TABLE[i]){PDF417CodewordDecoder.RATIOS_TABLE[i]=new Array(PDF417Common.BARS_IN_MODULE);}
PDF417CodewordDecoder.RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE-j-1]=Math.fround(size/PDF417Common.MODULES_IN_CODEWORD);}}
this.bSymbolTableReady=true;}
static getDecodedValue(moduleBitCount){let decodedValue=PDF417CodewordDecoder.getDecodedCodewordValue(PDF417CodewordDecoder.sampleBitCounts(moduleBitCount));if(decodedValue!==-1){return decodedValue;}
return PDF417CodewordDecoder.getClosestDecodedValue(moduleBitCount);}
static sampleBitCounts(moduleBitCount){let bitCountSum=MathUtils.sum(moduleBitCount);let result=new Int32Array(PDF417Common.BARS_IN_MODULE);let bitCountIndex=0;let sumPreviousBits=0;for(let i=0;i<PDF417Common.MODULES_IN_CODEWORD;i++){let sampleIndex=bitCountSum/(2*PDF417Common.MODULES_IN_CODEWORD)+
(i*bitCountSum)/PDF417Common.MODULES_IN_CODEWORD;if(sumPreviousBits+moduleBitCount[bitCountIndex]<=sampleIndex){sumPreviousBits+=moduleBitCount[bitCountIndex];bitCountIndex++;}
result[bitCountIndex]++;}
return result;}
static getDecodedCodewordValue(moduleBitCount){let decodedValue=PDF417CodewordDecoder.getBitValue(moduleBitCount);return PDF417Common.getCodeword(decodedValue)===-1?-1:decodedValue;}
static getBitValue(moduleBitCount){let result=0;for(let i=0;i<moduleBitCount.length;i++){for(let bit=0;bit<moduleBitCount[i];bit++){result=(result<<1)|(i%2===0?1:0);}}
return Math.trunc(result);}
static getClosestDecodedValue(moduleBitCount){let bitCountSum=MathUtils.sum(moduleBitCount);let bitCountRatios=new Array(PDF417Common.BARS_IN_MODULE);if(bitCountSum>1){for(let i=0;i<bitCountRatios.length;i++){bitCountRatios[i]=Math.fround(moduleBitCount[i]/bitCountSum);}}
let bestMatchError=Float.MAX_VALUE;let bestMatch=-1;if(!this.bSymbolTableReady){PDF417CodewordDecoder.initialize();}
for(let j=0;j<PDF417CodewordDecoder.RATIOS_TABLE.length;j++){let error=0.0;let ratioTableRow=PDF417CodewordDecoder.RATIOS_TABLE[j];for(let k=0;k<PDF417Common.BARS_IN_MODULE;k++){let diff=Math.fround(ratioTableRow[k]-bitCountRatios[k]);error+=Math.fround(diff*diff);if(error>=bestMatchError){break;}}
if(error<bestMatchError){bestMatchError=error;bestMatch=PDF417Common.SYMBOL_TABLE[j];}}
return bestMatch;}}
PDF417CodewordDecoder.bSymbolTableReady=false;PDF417CodewordDecoder.RATIOS_TABLE=new Array(PDF417Common.SYMBOL_TABLE.length).map(x=>x=new Array(PDF417Common.BARS_IN_MODULE));class PDF417ResultMetadata{constructor(){this.segmentCount=-1;this.fileSize=-1;this.timestamp=-1;this.checksum=-1;}
getSegmentIndex(){return this.segmentIndex;}
setSegmentIndex(segmentIndex){this.segmentIndex=segmentIndex;}
getFileId(){return this.fileId;}
setFileId(fileId){this.fileId=fileId;}
getOptionalData(){return this.optionalData;}
setOptionalData(optionalData){this.optionalData=optionalData;}
isLastSegment(){return this.lastSegment;}
setLastSegment(lastSegment){this.lastSegment=lastSegment;}
getSegmentCount(){return this.segmentCount;}
setSegmentCount(segmentCount){this.segmentCount=segmentCount;}
getSender(){return this.sender||null;}
setSender(sender){this.sender=sender;}
getAddressee(){return this.addressee||null;}
setAddressee(addressee){this.addressee=addressee;}
getFileName(){return this.fileName;}
setFileName(fileName){this.fileName=fileName;}
getFileSize(){return this.fileSize;}
setFileSize(fileSize){this.fileSize=fileSize;}
getChecksum(){return this.checksum;}
setChecksum(checksum){this.checksum=checksum;}
getTimestamp(){return this.timestamp;}
setTimestamp(timestamp){this.timestamp=timestamp;}}
class Long{static parseLong(num,radix=undefined){return parseInt(num,radix);}}
class NullPointerException extends Exception{}
NullPointerException.kind='NullPointerException';class OutputStream{writeBytes(b){this.writeBytesOffset(b,0,b.length);}
writeBytesOffset(b,off,len){if(b==null){throw new NullPointerException();}
else if((off<0)||(off>b.length)||(len<0)||((off+len)>b.length)||((off+len)<0)){throw new IndexOutOfBoundsException();}
else if(len===0){return;}
for(let i=0;i<len;i++){this.write(b[off+i]);}}
flush(){}
close(){}}
class OutOfMemoryError extends Exception{}
class ByteArrayOutputStream extends OutputStream{constructor(size=32){super();this.count=0;if(size<0){throw new IllegalArgumentException('Negative initial size: '
+size);}
this.buf=new Uint8Array(size);}
ensureCapacity(minCapacity){if(minCapacity-this.buf.length>0)
this.grow(minCapacity);}
grow(minCapacity){let oldCapacity=this.buf.length;let newCapacity=oldCapacity<<1;if(newCapacity-minCapacity<0)
newCapacity=minCapacity;if(newCapacity<0){if(minCapacity<0)
throw new OutOfMemoryError();newCapacity=Integer.MAX_VALUE;}
this.buf=Arrays.copyOfUint8Array(this.buf,newCapacity);}
write(b){this.ensureCapacity(this.count+1);this.buf[this.count]=b;this.count+=1;}
writeBytesOffset(b,off,len){if((off<0)||(off>b.length)||(len<0)||((off+len)-b.length>0)){throw new IndexOutOfBoundsException();}
this.ensureCapacity(this.count+len);System.arraycopy(b,off,this.buf,this.count,len);this.count+=len;}
writeTo(out){out.writeBytesOffset(this.buf,0,this.count);}
reset(){this.count=0;}
toByteArray(){return Arrays.copyOfUint8Array(this.buf,this.count);}
size(){return this.count;}
toString(param){if(!param){return this.toString_void();}
if(typeof param==='string'){return this.toString_string(param);}
return this.toString_number(param);}
toString_void(){return new String(this.buf).toString();}
toString_string(charsetName){return new String(this.buf).toString();}
toString_number(hibyte){return new String(this.buf).toString();}
close(){}}
var Mode$2;(function(Mode){Mode[Mode["ALPHA"]=0]="ALPHA";Mode[Mode["LOWER"]=1]="LOWER";Mode[Mode["MIXED"]=2]="MIXED";Mode[Mode["PUNCT"]=3]="PUNCT";Mode[Mode["ALPHA_SHIFT"]=4]="ALPHA_SHIFT";Mode[Mode["PUNCT_SHIFT"]=5]="PUNCT_SHIFT";})(Mode$2||(Mode$2={}));function getBigIntConstructor(){if(typeof window!=='undefined'){return window['BigInt']||null;}
if(typeof global!=='undefined'){return global['BigInt']||null;}
if(typeof self!=='undefined'){return self['BigInt']||null;}
throw new Error('Can\'t search globals for BigInt!');}
let BigInteger;function createBigInt(num){if(typeof BigInteger==='undefined'){BigInteger=getBigIntConstructor();}
if(BigInteger===null){throw new Error('BigInt is not supported!');}
return BigInteger(num);}
function getEXP900(){let EXP900=[];EXP900[0]=createBigInt(1);let nineHundred=createBigInt(900);EXP900[1]=nineHundred;for(let i=2;i<16;i++){EXP900[i]=EXP900[i-1]*nineHundred;}
return EXP900;}
class DecodedBitStreamParser$2{static decode(codewords,ecLevel){let result=new StringBuilder('');let encoding=CharacterSetECI.ISO8859_1;result.enableDecoding(encoding);let codeIndex=1;let code=codewords[codeIndex++];let resultMetadata=new PDF417ResultMetadata();while(codeIndex<codewords[0]){switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,result);break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:codeIndex=DecodedBitStreamParser$2.byteCompaction(code,codewords,encoding,codeIndex,result);break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(codewords[codeIndex++]);break;case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex,result);break;case DecodedBitStreamParser$2.ECI_CHARSET:let charsetECI=CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]);break;case DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE:codeIndex+=2;break;case DecodedBitStreamParser$2.ECI_USER_DEFINED:codeIndex++;break;case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:codeIndex=DecodedBitStreamParser$2.decodeMacroBlock(codewords,codeIndex,resultMetadata);break;case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:throw new FormatException();default:codeIndex--;codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,result);break;}
if(codeIndex<codewords.length){code=codewords[codeIndex++];}
else{throw FormatException.getFormatInstance();}}
if(result.length()===0){throw FormatException.getFormatInstance();}
let decoderResult=new DecoderResult(null,result.toString(),null,ecLevel);decoderResult.setOther(resultMetadata);return decoderResult;}
static decodeMacroBlock(codewords,codeIndex,resultMetadata){if(codeIndex+DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS>codewords[0]){throw FormatException.getFormatInstance();}
let segmentIndexArray=new Int32Array(DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS);for(let i=0;i<DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS;i++,codeIndex++){segmentIndexArray[i]=codewords[codeIndex];}
resultMetadata.setSegmentIndex(Integer.parseInt(DecodedBitStreamParser$2.decodeBase900toBase10(segmentIndexArray,DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS)));let fileId=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex,fileId);resultMetadata.setFileId(fileId.toString());let optionalFieldsStart=-1;if(codewords[codeIndex]===DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD){optionalFieldsStart=codeIndex+1;}
while(codeIndex<codewords[0]){switch(codewords[codeIndex]){case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:codeIndex++;switch(codewords[codeIndex]){case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:let fileName=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,fileName);resultMetadata.setFileName(fileName.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER:let sender=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,sender);resultMetadata.setSender(sender.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:let addressee=new StringBuilder();codeIndex=DecodedBitStreamParser$2.textCompaction(codewords,codeIndex+1,addressee);resultMetadata.setAddressee(addressee.toString());break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:let segmentCount=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,segmentCount);resultMetadata.setSegmentCount(Integer.parseInt(segmentCount.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:let timestamp=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,timestamp);resultMetadata.setTimestamp(Long.parseLong(timestamp.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:let checksum=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,checksum);resultMetadata.setChecksum(Integer.parseInt(checksum.toString()));break;case DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:let fileSize=new StringBuilder();codeIndex=DecodedBitStreamParser$2.numericCompaction(codewords,codeIndex+1,fileSize);resultMetadata.setFileSize(Long.parseLong(fileSize.toString()));break;default:throw FormatException.getFormatInstance();}
break;case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex++;resultMetadata.setLastSegment(true);break;default:throw FormatException.getFormatInstance();}}
if(optionalFieldsStart!==-1){let optionalFieldsLength=codeIndex-optionalFieldsStart;if(resultMetadata.isLastSegment()){optionalFieldsLength--;}
resultMetadata.setOptionalData(Arrays.copyOfRange(codewords,optionalFieldsStart,optionalFieldsStart+optionalFieldsLength));}
return codeIndex;}
static textCompaction(codewords,codeIndex,result){let textCompactionData=new Int32Array((codewords[0]-codeIndex)*2);let byteCompactionData=new Int32Array((codewords[0]-codeIndex)*2);let index=0;let end=false;while((codeIndex<codewords[0])&&!end){let code=codewords[codeIndex++];if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){textCompactionData[index]=code/30;textCompactionData[index+1]=code%30;index+=2;}
else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:textCompactionData[index++]=DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH;break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:textCompactionData[index]=DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE;code=codewords[codeIndex++];byteCompactionData[index]=code;index++;break;}}}
DecodedBitStreamParser$2.decodeTextCompaction(textCompactionData,byteCompactionData,index,result);return codeIndex;}
static decodeTextCompaction(textCompactionData,byteCompactionData,length,result){let subMode=Mode$2.ALPHA;let priorToShiftMode=Mode$2.ALPHA;let i=0;while(i<length){let subModeCh=textCompactionData[i];let ch='';switch(subMode){case Mode$2.ALPHA:if(subModeCh<26){ch=String.fromCharCode(65+subModeCh);}
else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.LL:subMode=Mode$2.LOWER;break;case DecodedBitStreamParser$2.ML:subMode=Mode$2.MIXED;break;case DecodedBitStreamParser$2.PS:priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;case Mode$2.LOWER:if(subModeCh<26){ch=String.fromCharCode(97+subModeCh);}
else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.AS:priorToShiftMode=subMode;subMode=Mode$2.ALPHA_SHIFT;break;case DecodedBitStreamParser$2.ML:subMode=Mode$2.MIXED;break;case DecodedBitStreamParser$2.PS:priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;case Mode$2.MIXED:if(subModeCh<DecodedBitStreamParser$2.PL){ch=DecodedBitStreamParser$2.MIXED_CHARS[subModeCh];}
else{switch(subModeCh){case DecodedBitStreamParser$2.PL:subMode=Mode$2.PUNCT;break;case 26:ch=' ';break;case DecodedBitStreamParser$2.LL:subMode=Mode$2.LOWER;break;case DecodedBitStreamParser$2.AL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.PS:priorToShiftMode=subMode;subMode=Mode$2.PUNCT_SHIFT;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;case Mode$2.PUNCT:if(subModeCh<DecodedBitStreamParser$2.PAL){ch=DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];}
else{switch(subModeCh){case DecodedBitStreamParser$2.PAL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;case Mode$2.ALPHA_SHIFT:subMode=priorToShiftMode;if(subModeCh<26){ch=String.fromCharCode(65+subModeCh);}
else{switch(subModeCh){case 26:ch=' ';break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;case Mode$2.PUNCT_SHIFT:subMode=priorToShiftMode;if(subModeCh<DecodedBitStreamParser$2.PAL){ch=DecodedBitStreamParser$2.PUNCT_CHARS[subModeCh];}
else{switch(subModeCh){case DecodedBitStreamParser$2.PAL:subMode=Mode$2.ALPHA;break;case DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:result.append(byteCompactionData[i]);break;case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:subMode=Mode$2.ALPHA;break;}}
break;}
if(ch!==''){result.append(ch);}
i++;}}
static byteCompaction(mode,codewords,encoding,codeIndex,result){let decodedBytes=new ByteArrayOutputStream();let count=0;let value=0;let end=false;switch(mode){case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:let byteCompactedCodewords=new Int32Array(6);let nextCode=codewords[codeIndex++];while((codeIndex<codewords[0])&&!end){byteCompactedCodewords[count++]=nextCode;value=900*value+nextCode;nextCode=codewords[codeIndex++];switch(nextCode){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;default:if((count%5===0)&&(count>0)){for(let j=0;j<6;++j){decodedBytes.write(Number(createBigInt(value)>>createBigInt(8*(5-j))));}
value=0;count=0;}
break;}}
if(codeIndex===codewords[0]&&nextCode<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){byteCompactedCodewords[count++]=nextCode;}
for(let i=0;i<count;i++){decodedBytes.write(byteCompactedCodewords[i]);}
break;case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:while(codeIndex<codewords[0]&&!end){let code=codewords[codeIndex++];if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){count++;value=900*value+code;}
else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;}}
if((count%5===0)&&(count>0)){for(let j=0;j<6;++j){decodedBytes.write(Number(createBigInt(value)>>createBigInt(8*(5-j))));}
value=0;count=0;}}
break;}
result.append(StringEncoding.decode(decodedBytes.toByteArray(),encoding));return codeIndex;}
static numericCompaction(codewords,codeIndex,result){let count=0;let end=false;let numericCodewords=new Int32Array(DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS);while(codeIndex<codewords[0]&&!end){let code=codewords[codeIndex++];if(codeIndex===codewords[0]){end=true;}
if(code<DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH){numericCodewords[count]=code;count++;}
else{switch(code){case DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH:case DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR:codeIndex--;end=true;break;}}
if((count%DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS===0||code===DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH||end)&&count>0){result.append(DecodedBitStreamParser$2.decodeBase900toBase10(numericCodewords,count));count=0;}}
return codeIndex;}
static decodeBase900toBase10(codewords,count){let result=createBigInt(0);for(let i=0;i<count;i++){result+=DecodedBitStreamParser$2.EXP900[count-i-1]*createBigInt(codewords[i]);}
let resultString=result.toString();if(resultString.charAt(0)!=='1'){throw new FormatException();}
return resultString.substring(1);}}
DecodedBitStreamParser$2.TEXT_COMPACTION_MODE_LATCH=900;DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH=901;DecodedBitStreamParser$2.NUMERIC_COMPACTION_MODE_LATCH=902;DecodedBitStreamParser$2.BYTE_COMPACTION_MODE_LATCH_6=924;DecodedBitStreamParser$2.ECI_USER_DEFINED=925;DecodedBitStreamParser$2.ECI_GENERAL_PURPOSE=926;DecodedBitStreamParser$2.ECI_CHARSET=927;DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928;DecodedBitStreamParser$2.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923;DecodedBitStreamParser$2.MACRO_PDF417_TERMINATOR=922;DecodedBitStreamParser$2.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913;DecodedBitStreamParser$2.MAX_NUMERIC_CODEWORDS=15;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5;DecodedBitStreamParser$2.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6;DecodedBitStreamParser$2.PL=25;DecodedBitStreamParser$2.LL=27;DecodedBitStreamParser$2.AS=27;DecodedBitStreamParser$2.ML=28;DecodedBitStreamParser$2.AL=28;DecodedBitStreamParser$2.PS=29;DecodedBitStreamParser$2.PAL=29;DecodedBitStreamParser$2.PUNCT_CHARS=';<>@[\\]_`~!\r\t,:\n-.$/"|*()?{}\'';DecodedBitStreamParser$2.MIXED_CHARS='0123456789&\r\t,:#-.$/+%*=^';DecodedBitStreamParser$2.EXP900=getBigIntConstructor()?getEXP900():[];DecodedBitStreamParser$2.NUMBER_OF_SEQUENCE_CODEWORDS=2;class PDF417ScanningDecoder{constructor(){}
static decode(image,imageTopLeft,imageBottomLeft,imageTopRight,imageBottomRight,minCodewordWidth,maxCodewordWidth){let boundingBox=new BoundingBox(image,imageTopLeft,imageBottomLeft,imageTopRight,imageBottomRight);let leftRowIndicatorColumn=null;let rightRowIndicatorColumn=null;let detectionResult;for(let firstPass=true;;firstPass=false){if(imageTopLeft!=null){leftRowIndicatorColumn=PDF417ScanningDecoder.getRowIndicatorColumn(image,boundingBox,imageTopLeft,true,minCodewordWidth,maxCodewordWidth);}
if(imageTopRight!=null){rightRowIndicatorColumn=PDF417ScanningDecoder.getRowIndicatorColumn(image,boundingBox,imageTopRight,false,minCodewordWidth,maxCodewordWidth);}
detectionResult=PDF417ScanningDecoder.merge(leftRowIndicatorColumn,rightRowIndicatorColumn);if(detectionResult==null){throw NotFoundException.getNotFoundInstance();}
let resultBox=detectionResult.getBoundingBox();if(firstPass&&resultBox!=null&&(resultBox.getMinY()<boundingBox.getMinY()||resultBox.getMaxY()>boundingBox.getMaxY())){boundingBox=resultBox;}
else{break;}}
detectionResult.setBoundingBox(boundingBox);let maxBarcodeColumn=detectionResult.getBarcodeColumnCount()+1;detectionResult.setDetectionResultColumn(0,leftRowIndicatorColumn);detectionResult.setDetectionResultColumn(maxBarcodeColumn,rightRowIndicatorColumn);let leftToRight=leftRowIndicatorColumn!=null;for(let barcodeColumnCount=1;barcodeColumnCount<=maxBarcodeColumn;barcodeColumnCount++){let barcodeColumn=leftToRight?barcodeColumnCount:maxBarcodeColumn-barcodeColumnCount;if(detectionResult.getDetectionResultColumn(barcodeColumn)!==undefined){continue;}
let detectionResultColumn;if(barcodeColumn===0||barcodeColumn===maxBarcodeColumn){detectionResultColumn=new DetectionResultRowIndicatorColumn(boundingBox,barcodeColumn===0);}
else{detectionResultColumn=new DetectionResultColumn(boundingBox);}
detectionResult.setDetectionResultColumn(barcodeColumn,detectionResultColumn);let startColumn=-1;let previousStartColumn=startColumn;for(let imageRow=boundingBox.getMinY();imageRow<=boundingBox.getMaxY();imageRow++){startColumn=PDF417ScanningDecoder.getStartColumn(detectionResult,barcodeColumn,imageRow,leftToRight);if(startColumn<0||startColumn>boundingBox.getMaxX()){if(previousStartColumn===-1){continue;}
startColumn=previousStartColumn;}
let codeword=PDF417ScanningDecoder.detectCodeword(image,boundingBox.getMinX(),boundingBox.getMaxX(),leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth);if(codeword!=null){detectionResultColumn.setCodeword(imageRow,codeword);previousStartColumn=startColumn;minCodewordWidth=Math.min(minCodewordWidth,codeword.getWidth());maxCodewordWidth=Math.max(maxCodewordWidth,codeword.getWidth());}}}
return PDF417ScanningDecoder.createDecoderResult(detectionResult);}
static merge(leftRowIndicatorColumn,rightRowIndicatorColumn){if(leftRowIndicatorColumn==null&&rightRowIndicatorColumn==null){return null;}
let barcodeMetadata=PDF417ScanningDecoder.getBarcodeMetadata(leftRowIndicatorColumn,rightRowIndicatorColumn);if(barcodeMetadata==null){return null;}
let boundingBox=BoundingBox.merge(PDF417ScanningDecoder.adjustBoundingBox(leftRowIndicatorColumn),PDF417ScanningDecoder.adjustBoundingBox(rightRowIndicatorColumn));return new DetectionResult(barcodeMetadata,boundingBox);}
static adjustBoundingBox(rowIndicatorColumn){if(rowIndicatorColumn==null){return null;}
let rowHeights=rowIndicatorColumn.getRowHeights();if(rowHeights==null){return null;}
let maxRowHeight=PDF417ScanningDecoder.getMax(rowHeights);let missingStartRows=0;for(let rowHeight of rowHeights){missingStartRows+=maxRowHeight-rowHeight;if(rowHeight>0){break;}}
let codewords=rowIndicatorColumn.getCodewords();for(let row=0;missingStartRows>0&&codewords[row]==null;row++){missingStartRows--;}
let missingEndRows=0;for(let row=rowHeights.length-1;row>=0;row--){missingEndRows+=maxRowHeight-rowHeights[row];if(rowHeights[row]>0){break;}}
for(let row=codewords.length-1;missingEndRows>0&&codewords[row]==null;row--){missingEndRows--;}
return rowIndicatorColumn.getBoundingBox().addMissingRows(missingStartRows,missingEndRows,rowIndicatorColumn.isLeft());}
static getMax(values){let maxValue=-1;for(let value of values){maxValue=Math.max(maxValue,value);}
return maxValue;}
static getBarcodeMetadata(leftRowIndicatorColumn,rightRowIndicatorColumn){let leftBarcodeMetadata;if(leftRowIndicatorColumn==null||(leftBarcodeMetadata=leftRowIndicatorColumn.getBarcodeMetadata())==null){return rightRowIndicatorColumn==null?null:rightRowIndicatorColumn.getBarcodeMetadata();}
let rightBarcodeMetadata;if(rightRowIndicatorColumn==null||(rightBarcodeMetadata=rightRowIndicatorColumn.getBarcodeMetadata())==null){return leftBarcodeMetadata;}
if(leftBarcodeMetadata.getColumnCount()!==rightBarcodeMetadata.getColumnCount()&&leftBarcodeMetadata.getErrorCorrectionLevel()!==rightBarcodeMetadata.getErrorCorrectionLevel()&&leftBarcodeMetadata.getRowCount()!==rightBarcodeMetadata.getRowCount()){return null;}
return leftBarcodeMetadata;}
static getRowIndicatorColumn(image,boundingBox,startPoint,leftToRight,minCodewordWidth,maxCodewordWidth){let rowIndicatorColumn=new DetectionResultRowIndicatorColumn(boundingBox,leftToRight);for(let i=0;i<2;i++){let increment=i===0?1:-1;let startColumn=Math.trunc(Math.trunc(startPoint.getX()));for(let imageRow=Math.trunc(Math.trunc(startPoint.getY()));imageRow<=boundingBox.getMaxY()&&imageRow>=boundingBox.getMinY();imageRow+=increment){let codeword=PDF417ScanningDecoder.detectCodeword(image,0,image.getWidth(),leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth);if(codeword!=null){rowIndicatorColumn.setCodeword(imageRow,codeword);if(leftToRight){startColumn=codeword.getStartX();}
else{startColumn=codeword.getEndX();}}}}
return rowIndicatorColumn;}
static adjustCodewordCount(detectionResult,barcodeMatrix){let barcodeMatrix01=barcodeMatrix[0][1];let numberOfCodewords=barcodeMatrix01.getValue();let calculatedNumberOfCodewords=detectionResult.getBarcodeColumnCount()*detectionResult.getBarcodeRowCount()-
PDF417ScanningDecoder.getNumberOfECCodeWords(detectionResult.getBarcodeECLevel());if(numberOfCodewords.length===0){if(calculatedNumberOfCodewords<1||calculatedNumberOfCodewords>PDF417Common.MAX_CODEWORDS_IN_BARCODE){throw NotFoundException.getNotFoundInstance();}
barcodeMatrix01.setValue(calculatedNumberOfCodewords);}
else if(numberOfCodewords[0]!==calculatedNumberOfCodewords){barcodeMatrix01.setValue(calculatedNumberOfCodewords);}}
static createDecoderResult(detectionResult){let barcodeMatrix=PDF417ScanningDecoder.createBarcodeMatrix(detectionResult);PDF417ScanningDecoder.adjustCodewordCount(detectionResult,barcodeMatrix);let erasures=new Array();let codewords=new Int32Array(detectionResult.getBarcodeRowCount()*detectionResult.getBarcodeColumnCount());let ambiguousIndexValuesList=[];let ambiguousIndexesList=new Array();for(let row=0;row<detectionResult.getBarcodeRowCount();row++){for(let column=0;column<detectionResult.getBarcodeColumnCount();column++){let values=barcodeMatrix[row][column+1].getValue();let codewordIndex=row*detectionResult.getBarcodeColumnCount()+column;if(values.length===0){erasures.push(codewordIndex);}
else if(values.length===1){codewords[codewordIndex]=values[0];}
else{ambiguousIndexesList.push(codewordIndex);ambiguousIndexValuesList.push(values);}}}
let ambiguousIndexValues=new Array(ambiguousIndexValuesList.length);for(let i=0;i<ambiguousIndexValues.length;i++){ambiguousIndexValues[i]=ambiguousIndexValuesList[i];}
return PDF417ScanningDecoder.createDecoderResultFromAmbiguousValues(detectionResult.getBarcodeECLevel(),codewords,PDF417Common.toIntArray(erasures),PDF417Common.toIntArray(ambiguousIndexesList),ambiguousIndexValues);}
static createDecoderResultFromAmbiguousValues(ecLevel,codewords,erasureArray,ambiguousIndexes,ambiguousIndexValues){let ambiguousIndexCount=new Int32Array(ambiguousIndexes.length);let tries=100;while(tries-->0){for(let i=0;i<ambiguousIndexCount.length;i++){codewords[ambiguousIndexes[i]]=ambiguousIndexValues[i][ambiguousIndexCount[i]];}
try{return PDF417ScanningDecoder.decodeCodewords(codewords,ecLevel,erasureArray);}
catch(err){let ignored=err instanceof ChecksumException;if(!ignored){throw err;}}
if(ambiguousIndexCount.length===0){throw ChecksumException.getChecksumInstance();}
for(let i=0;i<ambiguousIndexCount.length;i++){if(ambiguousIndexCount[i]<ambiguousIndexValues[i].length-1){ambiguousIndexCount[i]++;break;}
else{ambiguousIndexCount[i]=0;if(i===ambiguousIndexCount.length-1){throw ChecksumException.getChecksumInstance();}}}}
throw ChecksumException.getChecksumInstance();}
static createBarcodeMatrix(detectionResult){let barcodeMatrix=Array.from({length:detectionResult.getBarcodeRowCount()},()=>new Array(detectionResult.getBarcodeColumnCount()+2));for(let row=0;row<barcodeMatrix.length;row++){for(let column=0;column<barcodeMatrix[row].length;column++){barcodeMatrix[row][column]=new BarcodeValue();}}
let column=0;for(let detectionResultColumn of detectionResult.getDetectionResultColumns()){if(detectionResultColumn!=null){for(let codeword of detectionResultColumn.getCodewords()){if(codeword!=null){let rowNumber=codeword.getRowNumber();if(rowNumber>=0){if(rowNumber>=barcodeMatrix.length){continue;}
barcodeMatrix[rowNumber][column].setValue(codeword.getValue());}}}}
column++;}
return barcodeMatrix;}
static isValidBarcodeColumn(detectionResult,barcodeColumn){return barcodeColumn>=0&&barcodeColumn<=detectionResult.getBarcodeColumnCount()+1;}
static getStartColumn(detectionResult,barcodeColumn,imageRow,leftToRight){let offset=leftToRight?1:-1;let codeword=null;if(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){codeword=detectionResult.getDetectionResultColumn(barcodeColumn-offset).getCodeword(imageRow);}
if(codeword!=null){return leftToRight?codeword.getEndX():codeword.getStartX();}
codeword=detectionResult.getDetectionResultColumn(barcodeColumn).getCodewordNearby(imageRow);if(codeword!=null){return leftToRight?codeword.getStartX():codeword.getEndX();}
if(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){codeword=detectionResult.getDetectionResultColumn(barcodeColumn-offset).getCodewordNearby(imageRow);}
if(codeword!=null){return leftToRight?codeword.getEndX():codeword.getStartX();}
let skippedColumns=0;while(PDF417ScanningDecoder.isValidBarcodeColumn(detectionResult,barcodeColumn-offset)){barcodeColumn-=offset;for(let previousRowCodeword of detectionResult.getDetectionResultColumn(barcodeColumn).getCodewords()){if(previousRowCodeword!=null){return(leftToRight?previousRowCodeword.getEndX():previousRowCodeword.getStartX())+
offset*skippedColumns*(previousRowCodeword.getEndX()-previousRowCodeword.getStartX());}}
skippedColumns++;}
return leftToRight?detectionResult.getBoundingBox().getMinX():detectionResult.getBoundingBox().getMaxX();}
static detectCodeword(image,minColumn,maxColumn,leftToRight,startColumn,imageRow,minCodewordWidth,maxCodewordWidth){startColumn=PDF417ScanningDecoder.adjustCodewordStartColumn(image,minColumn,maxColumn,leftToRight,startColumn,imageRow);let moduleBitCount=PDF417ScanningDecoder.getModuleBitCount(image,minColumn,maxColumn,leftToRight,startColumn,imageRow);if(moduleBitCount==null){return null;}
let endColumn;let codewordBitCount=MathUtils.sum(moduleBitCount);if(leftToRight){endColumn=startColumn+codewordBitCount;}
else{for(let i=0;i<moduleBitCount.length/2;i++){let tmpCount=moduleBitCount[i];moduleBitCount[i]=moduleBitCount[moduleBitCount.length-1-i];moduleBitCount[moduleBitCount.length-1-i]=tmpCount;}
endColumn=startColumn;startColumn=endColumn-codewordBitCount;}
if(!PDF417ScanningDecoder.checkCodewordSkew(codewordBitCount,minCodewordWidth,maxCodewordWidth)){return null;}
let decodedValue=PDF417CodewordDecoder.getDecodedValue(moduleBitCount);let codeword=PDF417Common.getCodeword(decodedValue);if(codeword===-1){return null;}
return new Codeword(startColumn,endColumn,PDF417ScanningDecoder.getCodewordBucketNumber(decodedValue),codeword);}
static getModuleBitCount(image,minColumn,maxColumn,leftToRight,startColumn,imageRow){let imageColumn=startColumn;let moduleBitCount=new Int32Array(8);let moduleNumber=0;let increment=leftToRight?1:-1;let previousPixelValue=leftToRight;while((leftToRight?imageColumn<maxColumn:imageColumn>=minColumn)&&moduleNumber<moduleBitCount.length){if(image.get(imageColumn,imageRow)===previousPixelValue){moduleBitCount[moduleNumber]++;imageColumn+=increment;}
else{moduleNumber++;previousPixelValue=!previousPixelValue;}}
if(moduleNumber===moduleBitCount.length||((imageColumn===(leftToRight?maxColumn:minColumn))&&moduleNumber===moduleBitCount.length-1)){return moduleBitCount;}
return null;}
static getNumberOfECCodeWords(barcodeECLevel){return 2<<barcodeECLevel;}
static adjustCodewordStartColumn(image,minColumn,maxColumn,leftToRight,codewordStartColumn,imageRow){let correctedStartColumn=codewordStartColumn;let increment=leftToRight?-1:1;for(let i=0;i<2;i++){while((leftToRight?correctedStartColumn>=minColumn:correctedStartColumn<maxColumn)&&leftToRight===image.get(correctedStartColumn,imageRow)){if(Math.abs(codewordStartColumn-correctedStartColumn)>PDF417ScanningDecoder.CODEWORD_SKEW_SIZE){return codewordStartColumn;}
correctedStartColumn+=increment;}
increment=-increment;leftToRight=!leftToRight;}
return correctedStartColumn;}
static checkCodewordSkew(codewordSize,minCodewordWidth,maxCodewordWidth){return minCodewordWidth-PDF417ScanningDecoder.CODEWORD_SKEW_SIZE<=codewordSize&&codewordSize<=maxCodewordWidth+PDF417ScanningDecoder.CODEWORD_SKEW_SIZE;}
static decodeCodewords(codewords,ecLevel,erasures){if(codewords.length===0){throw FormatException.getFormatInstance();}
let numECCodewords=1<<(ecLevel+1);let correctedErrorsCount=PDF417ScanningDecoder.correctErrors(codewords,erasures,numECCodewords);PDF417ScanningDecoder.verifyCodewordCount(codewords,numECCodewords);let decoderResult=DecodedBitStreamParser$2.decode(codewords,''+ecLevel);decoderResult.setErrorsCorrected(correctedErrorsCount);decoderResult.setErasures(erasures.length);return decoderResult;}
static correctErrors(codewords,erasures,numECCodewords){if(erasures!=null&&erasures.length>numECCodewords/2+PDF417ScanningDecoder.MAX_ERRORS||numECCodewords<0||numECCodewords>PDF417ScanningDecoder.MAX_EC_CODEWORDS){throw ChecksumException.getChecksumInstance();}
return PDF417ScanningDecoder.errorCorrection.decode(codewords,numECCodewords,erasures);}
static verifyCodewordCount(codewords,numECCodewords){if(codewords.length<4){throw FormatException.getFormatInstance();}
let numberOfCodewords=codewords[0];if(numberOfCodewords>codewords.length){throw FormatException.getFormatInstance();}
if(numberOfCodewords===0){if(numECCodewords<codewords.length){codewords[0]=codewords.length-numECCodewords;}
else{throw FormatException.getFormatInstance();}}}
static getBitCountForCodeword(codeword){let result=new Int32Array(8);let previousValue=0;let i=result.length-1;while(true){if((codeword&0x1)!==previousValue){previousValue=codeword&0x1;i--;if(i<0){break;}}
result[i]++;codeword>>=1;}
return result;}
static getCodewordBucketNumber(codeword){if(codeword instanceof Int32Array){return this.getCodewordBucketNumber_Int32Array(codeword);}
return this.getCodewordBucketNumber_number(codeword);}
static getCodewordBucketNumber_number(codeword){return PDF417ScanningDecoder.getCodewordBucketNumber(PDF417ScanningDecoder.getBitCountForCodeword(codeword));}
static getCodewordBucketNumber_Int32Array(moduleBitCount){return(moduleBitCount[0]-moduleBitCount[2]+moduleBitCount[4]-moduleBitCount[6]+9)%9;}
static toString(barcodeMatrix){let formatter=new Formatter();for(let row=0;row<barcodeMatrix.length;row++){formatter.format('Row %2d: ',row);for(let column=0;column<barcodeMatrix[row].length;column++){let barcodeValue=barcodeMatrix[row][column];if(barcodeValue.getValue().length===0){formatter.format('        ',null);}
else{formatter.format('%4d(%2d)',barcodeValue.getValue()[0],barcodeValue.getConfidence(barcodeValue.getValue()[0]));}}
formatter.format('%n');}
return formatter.toString();}}
PDF417ScanningDecoder.CODEWORD_SKEW_SIZE=2;PDF417ScanningDecoder.MAX_ERRORS=3;PDF417ScanningDecoder.MAX_EC_CODEWORDS=512;PDF417ScanningDecoder.errorCorrection=new ErrorCorrection();class PDF417Reader{decode(image,hints=null){let result=PDF417Reader.decode(image,hints,false);if(result==null||result.length===0||result[0]==null){throw NotFoundException.getNotFoundInstance();}
return result[0];}
decodeMultiple(image,hints=null){try{return PDF417Reader.decode(image,hints,true);}
catch(ignored){if(ignored instanceof FormatException||ignored instanceof ChecksumException){throw NotFoundException.getNotFoundInstance();}
throw ignored;}}
static decode(image,hints,multiple){const results=new Array();const detectorResult=Detector$3.detectMultiple(image,hints,multiple);for(const points of detectorResult.getPoints()){const decoderResult=PDF417ScanningDecoder.decode(detectorResult.getBits(),points[4],points[5],points[6],points[7],PDF417Reader.getMinCodewordWidth(points),PDF417Reader.getMaxCodewordWidth(points));const result=new Result(decoderResult.getText(),decoderResult.getRawBytes(),undefined,points,BarcodeFormat$1.PDF_417);result.putMetadata(ResultMetadataType$1.ERROR_CORRECTION_LEVEL,decoderResult.getECLevel());const pdf417ResultMetadata=decoderResult.getOther();if(pdf417ResultMetadata!=null){result.putMetadata(ResultMetadataType$1.PDF417_EXTRA_METADATA,pdf417ResultMetadata);}
results.push(result);}
return results.map(x=>x);}
static getMaxWidth(p1,p2){if(p1==null||p2==null){return 0;}
return Math.trunc(Math.abs(p1.getX()-p2.getX()));}
static getMinWidth(p1,p2){if(p1==null||p2==null){return Integer.MAX_VALUE;}
return Math.trunc(Math.abs(p1.getX()-p2.getX()));}
static getMaxCodewordWidth(p){return Math.floor(Math.max(Math.max(PDF417Reader.getMaxWidth(p[0],p[4]),PDF417Reader.getMaxWidth(p[6],p[2])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN),Math.max(PDF417Reader.getMaxWidth(p[1],p[5]),PDF417Reader.getMaxWidth(p[7],p[3])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN)));}
static getMinCodewordWidth(p){return Math.floor(Math.min(Math.min(PDF417Reader.getMinWidth(p[0],p[4]),PDF417Reader.getMinWidth(p[6],p[2])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN),Math.min(PDF417Reader.getMinWidth(p[1],p[5]),PDF417Reader.getMinWidth(p[7],p[3])*PDF417Common.MODULES_IN_CODEWORD/PDF417Common.MODULES_IN_STOP_PATTERN)));}
reset(){}}
class ReaderException extends Exception{}
ReaderException.kind='ReaderException';class MultiFormatReader{decode(image,hints){this.setHints(hints);return this.decodeInternal(image);}
decodeWithState(image){if(this.readers===null||this.readers===undefined){this.setHints(null);}
return this.decodeInternal(image);}
setHints(hints){this.hints=hints;const tryHarder=hints!==null&&hints!==undefined&&undefined!==hints.get(DecodeHintType$1.TRY_HARDER);const formats=hints===null||hints===undefined?null:hints.get(DecodeHintType$1.POSSIBLE_FORMATS);const readers=new Array();if(formats!==null&&formats!==undefined){const addOneDReader=formats.some(f=>f===BarcodeFormat$1.UPC_A||f===BarcodeFormat$1.UPC_E||f===BarcodeFormat$1.EAN_13||f===BarcodeFormat$1.EAN_8||f===BarcodeFormat$1.CODABAR||f===BarcodeFormat$1.CODE_39||f===BarcodeFormat$1.CODE_93||f===BarcodeFormat$1.CODE_128||f===BarcodeFormat$1.ITF||f===BarcodeFormat$1.RSS_14||f===BarcodeFormat$1.RSS_EXPANDED);if(addOneDReader&&!tryHarder){readers.push(new MultiFormatOneDReader(hints));}
if(formats.includes(BarcodeFormat$1.QR_CODE)){readers.push(new QRCodeReader());}
if(formats.includes(BarcodeFormat$1.DATA_MATRIX)){readers.push(new DataMatrixReader());}
if(formats.includes(BarcodeFormat$1.AZTEC)){readers.push(new AztecReader());}
if(formats.includes(BarcodeFormat$1.PDF_417)){readers.push(new PDF417Reader());}
if(addOneDReader&&tryHarder){readers.push(new MultiFormatOneDReader(hints));}}
if(readers.length===0){if(!tryHarder){readers.push(new MultiFormatOneDReader(hints));}
readers.push(new QRCodeReader());readers.push(new DataMatrixReader());readers.push(new AztecReader());readers.push(new PDF417Reader());if(tryHarder){readers.push(new MultiFormatOneDReader(hints));}}
this.readers=readers;}
reset(){if(this.readers!==null){for(const reader of this.readers){reader.reset();}}}
decodeInternal(image){if(this.readers===null){throw new ReaderException('No readers where selected, nothing can be read.');}
for(const reader of this.readers){try{return reader.decode(image,this.hints);}
catch(ex){if(ex instanceof ReaderException){continue;}}}
throw new NotFoundException('No MultiFormat Readers were able to detect the code.');}}
class BrowserMultiFormatReader extends BrowserCodeReader{constructor(hints=null,timeBetweenScansMillis=500){const reader=new MultiFormatReader();reader.setHints(hints);super(reader,timeBetweenScansMillis);}
decodeBitmap(binaryBitmap){return this.reader.decodeWithState(binaryBitmap);}}
class BrowserPDF417Reader extends BrowserCodeReader{constructor(timeBetweenScansMillis=500){super(new PDF417Reader(),timeBetweenScansMillis);}}
class BrowserQRCodeReader extends BrowserCodeReader{constructor(timeBetweenScansMillis=500){super(new QRCodeReader(),timeBetweenScansMillis);}}
var EncodeHintType;(function(EncodeHintType){EncodeHintType[EncodeHintType["ERROR_CORRECTION"]=0]="ERROR_CORRECTION";EncodeHintType[EncodeHintType["CHARACTER_SET"]=1]="CHARACTER_SET";EncodeHintType[EncodeHintType["DATA_MATRIX_SHAPE"]=2]="DATA_MATRIX_SHAPE";EncodeHintType[EncodeHintType["DATA_MATRIX_COMPACT"]=3]="DATA_MATRIX_COMPACT";EncodeHintType[EncodeHintType["MIN_SIZE"]=4]="MIN_SIZE";EncodeHintType[EncodeHintType["MAX_SIZE"]=5]="MAX_SIZE";EncodeHintType[EncodeHintType["MARGIN"]=6]="MARGIN";EncodeHintType[EncodeHintType["PDF417_COMPACT"]=7]="PDF417_COMPACT";EncodeHintType[EncodeHintType["PDF417_COMPACTION"]=8]="PDF417_COMPACTION";EncodeHintType[EncodeHintType["PDF417_DIMENSIONS"]=9]="PDF417_DIMENSIONS";EncodeHintType[EncodeHintType["AZTEC_LAYERS"]=10]="AZTEC_LAYERS";EncodeHintType[EncodeHintType["QR_VERSION"]=11]="QR_VERSION";EncodeHintType[EncodeHintType["GS1_FORMAT"]=12]="GS1_FORMAT";EncodeHintType[EncodeHintType["FORCE_C40"]=13]="FORCE_C40";})(EncodeHintType||(EncodeHintType={}));var EncodeHintType$1=EncodeHintType;class ReedSolomonEncoder{constructor(field){this.field=field;this.cachedGenerators=[];this.cachedGenerators.push(new GenericGFPoly(field,Int32Array.from([1])));}
buildGenerator(degree){const cachedGenerators=this.cachedGenerators;if(degree>=cachedGenerators.length){let lastGenerator=cachedGenerators[cachedGenerators.length-1];const field=this.field;for(let d=cachedGenerators.length;d<=degree;d++){const nextGenerator=lastGenerator.multiply(new GenericGFPoly(field,Int32Array.from([1,field.exp(d-1+field.getGeneratorBase())])));cachedGenerators.push(nextGenerator);lastGenerator=nextGenerator;}}
return cachedGenerators[degree];}
encode(toEncode,ecBytes){if(ecBytes===0){throw new IllegalArgumentException('No error correction bytes');}
const dataBytes=toEncode.length-ecBytes;if(dataBytes<=0){throw new IllegalArgumentException('No data bytes provided');}
const generator=this.buildGenerator(ecBytes);const infoCoefficients=new Int32Array(dataBytes);System.arraycopy(toEncode,0,infoCoefficients,0,dataBytes);let info=new GenericGFPoly(this.field,infoCoefficients);info=info.multiplyByMonomial(ecBytes,1);const remainder=info.divide(generator)[1];const coefficients=remainder.getCoefficients();const numZeroCoefficients=ecBytes-coefficients.length;for(let i=0;i<numZeroCoefficients;i++){toEncode[dataBytes+i]=0;}
System.arraycopy(coefficients,0,toEncode,dataBytes+numZeroCoefficients,coefficients.length);}}
class MaskUtil{constructor(){}
static applyMaskPenaltyRule1(matrix){return MaskUtil.applyMaskPenaltyRule1Internal(matrix,true)+MaskUtil.applyMaskPenaltyRule1Internal(matrix,false);}
static applyMaskPenaltyRule2(matrix){let penalty=0;const array=matrix.getArray();const width=matrix.getWidth();const height=matrix.getHeight();for(let y=0;y<height-1;y++){const arrayY=array[y];for(let x=0;x<width-1;x++){const value=arrayY[x];if(value===arrayY[x+1]&&value===array[y+1][x]&&value===array[y+1][x+1]){penalty++;}}}
return MaskUtil.N2*penalty;}
static applyMaskPenaltyRule3(matrix){let numPenalties=0;const array=matrix.getArray();const width=matrix.getWidth();const height=matrix.getHeight();for(let y=0;y<height;y++){for(let x=0;x<width;x++){const arrayY=array[y];if(x+6<width&&arrayY[x]===1&&arrayY[x+1]===0&&arrayY[x+2]===1&&arrayY[x+3]===1&&arrayY[x+4]===1&&arrayY[x+5]===0&&arrayY[x+6]===1&&(MaskUtil.isWhiteHorizontal(arrayY,x-4,x)||MaskUtil.isWhiteHorizontal(arrayY,x+7,x+11))){numPenalties++;}
if(y+6<height&&array[y][x]===1&&array[y+1][x]===0&&array[y+2][x]===1&&array[y+3][x]===1&&array[y+4][x]===1&&array[y+5][x]===0&&array[y+6][x]===1&&(MaskUtil.isWhiteVertical(array,x,y-4,y)||MaskUtil.isWhiteVertical(array,x,y+7,y+11))){numPenalties++;}}}
return numPenalties*MaskUtil.N3;}
static isWhiteHorizontal(rowArray,from,to){from=Math.max(from,0);to=Math.min(to,rowArray.length);for(let i=from;i<to;i++){if(rowArray[i]===1){return false;}}
return true;}
static isWhiteVertical(array,col,from,to){from=Math.max(from,0);to=Math.min(to,array.length);for(let i=from;i<to;i++){if(array[i][col]===1){return false;}}
return true;}
static applyMaskPenaltyRule4(matrix){let numDarkCells=0;const array=matrix.getArray();const width=matrix.getWidth();const height=matrix.getHeight();for(let y=0;y<height;y++){const arrayY=array[y];for(let x=0;x<width;x++){if(arrayY[x]===1){numDarkCells++;}}}
const numTotalCells=matrix.getHeight()*matrix.getWidth();const fivePercentVariances=Math.floor(Math.abs(numDarkCells*2-numTotalCells)*10/numTotalCells);return fivePercentVariances*MaskUtil.N4;}
static getDataMaskBit(maskPattern,x,y){let intermediate;let temp;switch(maskPattern){case 0:intermediate=(y+x)&0x1;break;case 1:intermediate=y&0x1;break;case 2:intermediate=x%3;break;case 3:intermediate=(y+x)%3;break;case 4:intermediate=(Math.floor(y/2)+Math.floor(x/3))&0x1;break;case 5:temp=y*x;intermediate=(temp&0x1)+(temp%3);break;case 6:temp=y*x;intermediate=((temp&0x1)+(temp%3))&0x1;break;case 7:temp=y*x;intermediate=((temp%3)+((y+x)&0x1))&0x1;break;default:throw new IllegalArgumentException('Invalid mask pattern: '+maskPattern);}
return intermediate===0;}
static applyMaskPenaltyRule1Internal(matrix,isHorizontal){let penalty=0;const iLimit=isHorizontal?matrix.getHeight():matrix.getWidth();const jLimit=isHorizontal?matrix.getWidth():matrix.getHeight();const array=matrix.getArray();for(let i=0;i<iLimit;i++){let numSameBitCells=0;let prevBit=-1;for(let j=0;j<jLimit;j++){const bit=isHorizontal?array[i][j]:array[j][i];if(bit===prevBit){numSameBitCells++;}
else{if(numSameBitCells>=5){penalty+=MaskUtil.N1+(numSameBitCells-5);}
numSameBitCells=1;prevBit=bit;}}
if(numSameBitCells>=5){penalty+=MaskUtil.N1+(numSameBitCells-5);}}
return penalty;}}
MaskUtil.N1=3;MaskUtil.N2=3;MaskUtil.N3=40;MaskUtil.N4=10;class ByteMatrix{constructor(width,height){this.width=width;this.height=height;const bytes=new Array(height);for(let i=0;i!==height;i++){bytes[i]=new Uint8Array(width);}
this.bytes=bytes;}
getHeight(){return this.height;}
getWidth(){return this.width;}
get(x,y){return this.bytes[y][x];}
getArray(){return this.bytes;}
setNumber(x,y,value){this.bytes[y][x]=value;}
setBoolean(x,y,value){this.bytes[y][x]=(value?1:0);}
clear(value){for(const aByte of this.bytes){Arrays.fill(aByte,value);}}
equals(o){if(!(o instanceof ByteMatrix)){return false;}
const other=o;if(this.width!==other.width){return false;}
if(this.height!==other.height){return false;}
for(let y=0,height=this.height;y<height;++y){const bytesY=this.bytes[y];const otherBytesY=other.bytes[y];for(let x=0,width=this.width;x<width;++x){if(bytesY[x]!==otherBytesY[x]){return false;}}}
return true;}
toString(){const result=new StringBuilder();for(let y=0,height=this.height;y<height;++y){const bytesY=this.bytes[y];for(let x=0,width=this.width;x<width;++x){switch(bytesY[x]){case 0:result.append(' 0');break;case 1:result.append(' 1');break;default:result.append('  ');break;}}
result.append('\n');}
return result.toString();}}
class QRCode{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 result=new StringBuilder();result.append('<<\n');result.append(' mode: ');result.append(this.mode?this.mode.toString():'null');result.append('\n ecLevel: ');result.append(this.ecLevel?this.ecLevel.toString():'null');result.append('\n version: ');result.append(this.version?this.version.toString():'null');result.append('\n maskPattern: ');result.append(this.maskPattern.toString());if(this.matrix){result.append('\n matrix:\n');result.append(this.matrix.toString());}
else{result.append('\n matrix: null\n');}
result.append('>>\n');return result.toString();}
setMode(value){this.mode=value;}
setECLevel(value){this.ecLevel=value;}
setVersion(version){this.version=version;}
setMaskPattern(value){this.maskPattern=value;}
setMatrix(value){this.matrix=value;}
static isValidMaskPattern(maskPattern){return maskPattern>=0&&maskPattern<QRCode.NUM_MASK_PATTERNS;}}
QRCode.NUM_MASK_PATTERNS=8;class WriterException extends Exception{}
WriterException.kind='WriterException';class MatrixUtil{constructor(){}
static clearMatrix(matrix){matrix.clear(255);}
static buildMatrix(dataBits,ecLevel,version,maskPattern,matrix){MatrixUtil.clearMatrix(matrix);MatrixUtil.embedBasicPatterns(version,matrix);MatrixUtil.embedTypeInfo(ecLevel,maskPattern,matrix);MatrixUtil.maybeEmbedVersionInfo(version,matrix);MatrixUtil.embedDataBits(dataBits,maskPattern,matrix);}
static embedBasicPatterns(version,matrix){MatrixUtil.embedPositionDetectionPatternsAndSeparators(matrix);MatrixUtil.embedDarkDotAtLeftBottomCorner(matrix);MatrixUtil.maybeEmbedPositionAdjustmentPatterns(version,matrix);MatrixUtil.embedTimingPatterns(matrix);}
static embedTypeInfo(ecLevel,maskPattern,matrix){const typeInfoBits=new BitArray();MatrixUtil.makeTypeInfoBits(ecLevel,maskPattern,typeInfoBits);for(let i=0,size=typeInfoBits.getSize();i<size;++i){const bit=typeInfoBits.get(typeInfoBits.getSize()-1-i);const coordinates=MatrixUtil.TYPE_INFO_COORDINATES[i];const x1=coordinates[0];const y1=coordinates[1];matrix.setBoolean(x1,y1,bit);if(i<8){const x2=matrix.getWidth()-i-1;const y2=8;matrix.setBoolean(x2,y2,bit);}
else{const x2=8;const y2=matrix.getHeight()-7+(i-8);matrix.setBoolean(x2,y2,bit);}}}
static maybeEmbedVersionInfo(version,matrix){if(version.getVersionNumber()<7){return;}
const versionInfoBits=new BitArray();MatrixUtil.makeVersionInfoBits(version,versionInfoBits);let bitIndex=6*3-1;for(let i=0;i<6;++i){for(let j=0;j<3;++j){const bit=versionInfoBits.get(bitIndex);bitIndex--;matrix.setBoolean(i,matrix.getHeight()-11+j,bit);matrix.setBoolean(matrix.getHeight()-11+j,i,bit);}}}
static embedDataBits(dataBits,maskPattern,matrix){let bitIndex=0;let direction=-1;let x=matrix.getWidth()-1;let y=matrix.getHeight()-1;while(x>0){if(x===6){x-=1;}
while(y>=0&&y<matrix.getHeight()){for(let i=0;i<2;++i){const xx=x-i;if(!MatrixUtil.isEmpty(matrix.get(xx,y))){continue;}
let bit;if(bitIndex<dataBits.getSize()){bit=dataBits.get(bitIndex);++bitIndex;}
else{bit=false;}
if(maskPattern!==255&&MaskUtil.getDataMaskBit(maskPattern,xx,y)){bit=!bit;}
matrix.setBoolean(xx,y,bit);}
y+=direction;}
direction=-direction;y+=direction;x-=2;}
if(bitIndex!==dataBits.getSize()){throw new WriterException('Not all bits consumed: '+bitIndex+'/'+dataBits.getSize());}}
static findMSBSet(value){return 32-Integer.numberOfLeadingZeros(value);}
static calculateBCHCode(value,poly){if(poly===0){throw new IllegalArgumentException('0 polynomial');}
const msbSetInPoly=MatrixUtil.findMSBSet(poly);value<<=msbSetInPoly-1;while(MatrixUtil.findMSBSet(value)>=msbSetInPoly){value^=poly<<(MatrixUtil.findMSBSet(value)-msbSetInPoly);}
return value;}
static makeTypeInfoBits(ecLevel,maskPattern,bits){if(!QRCode.isValidMaskPattern(maskPattern)){throw new WriterException('Invalid mask pattern');}
const typeInfo=(ecLevel.getBits()<<3)|maskPattern;bits.appendBits(typeInfo,5);const bchCode=MatrixUtil.calculateBCHCode(typeInfo,MatrixUtil.TYPE_INFO_POLY);bits.appendBits(bchCode,10);const maskBits=new BitArray();maskBits.appendBits(MatrixUtil.TYPE_INFO_MASK_PATTERN,15);bits.xor(maskBits);if(bits.getSize()!==15){throw new WriterException('should not happen but we got: '+bits.getSize());}}
static makeVersionInfoBits(version,bits){bits.appendBits(version.getVersionNumber(),6);const bchCode=MatrixUtil.calculateBCHCode(version.getVersionNumber(),MatrixUtil.VERSION_INFO_POLY);bits.appendBits(bchCode,12);if(bits.getSize()!==18){throw new WriterException('should not happen but we got: '+bits.getSize());}}
static isEmpty(value){return value===255;}
static embedTimingPatterns(matrix){for(let i=8;i<matrix.getWidth()-8;++i){const bit=(i+1)%2;if(MatrixUtil.isEmpty(matrix.get(i,6))){matrix.setNumber(i,6,bit);}
if(MatrixUtil.isEmpty(matrix.get(6,i))){matrix.setNumber(6,i,bit);}}}
static embedDarkDotAtLeftBottomCorner(matrix){if(matrix.get(8,matrix.getHeight()-8)===0){throw new WriterException();}
matrix.setNumber(8,matrix.getHeight()-8,1);}
static embedHorizontalSeparationPattern(xStart,yStart,matrix){for(let x=0;x<8;++x){if(!MatrixUtil.isEmpty(matrix.get(xStart+x,yStart))){throw new WriterException();}
matrix.setNumber(xStart+x,yStart,0);}}
static embedVerticalSeparationPattern(xStart,yStart,matrix){for(let y=0;y<7;++y){if(!MatrixUtil.isEmpty(matrix.get(xStart,yStart+y))){throw new WriterException();}
matrix.setNumber(xStart,yStart+y,0);}}
static embedPositionAdjustmentPattern(xStart,yStart,matrix){for(let y=0;y<5;++y){const patternY=MatrixUtil.POSITION_ADJUSTMENT_PATTERN[y];for(let x=0;x<5;++x){matrix.setNumber(xStart+x,yStart+y,patternY[x]);}}}
static embedPositionDetectionPattern(xStart,yStart,matrix){for(let y=0;y<7;++y){const patternY=MatrixUtil.POSITION_DETECTION_PATTERN[y];for(let x=0;x<7;++x){matrix.setNumber(xStart+x,yStart+y,patternY[x]);}}}
static embedPositionDetectionPatternsAndSeparators(matrix){const pdpWidth=MatrixUtil.POSITION_DETECTION_PATTERN[0].length;MatrixUtil.embedPositionDetectionPattern(0,0,matrix);MatrixUtil.embedPositionDetectionPattern(matrix.getWidth()-pdpWidth,0,matrix);MatrixUtil.embedPositionDetectionPattern(0,matrix.getWidth()-pdpWidth,matrix);const hspWidth=8;MatrixUtil.embedHorizontalSeparationPattern(0,hspWidth-1,matrix);MatrixUtil.embedHorizontalSeparationPattern(matrix.getWidth()-hspWidth,hspWidth-1,matrix);MatrixUtil.embedHorizontalSeparationPattern(0,matrix.getWidth()-hspWidth,matrix);const vspSize=7;MatrixUtil.embedVerticalSeparationPattern(vspSize,0,matrix);MatrixUtil.embedVerticalSeparationPattern(matrix.getHeight()-vspSize-1,0,matrix);MatrixUtil.embedVerticalSeparationPattern(vspSize,matrix.getHeight()-vspSize,matrix);}
static maybeEmbedPositionAdjustmentPatterns(version,matrix){if(version.getVersionNumber()<2){return;}
const index=version.getVersionNumber()-1;const coordinates=MatrixUtil.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[index];for(let i=0,length=coordinates.length;i!==length;i++){const y=coordinates[i];if(y>=0){for(let j=0;j!==length;j++){const x=coordinates[j];if(x>=0&&MatrixUtil.isEmpty(matrix.get(x,y))){MatrixUtil.embedPositionAdjustmentPattern(x-2,y-2,matrix);}}}}}}
MatrixUtil.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]),]);MatrixUtil.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]),]);MatrixUtil.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]),]);MatrixUtil.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]),]);MatrixUtil.VERSION_INFO_POLY=0x1f25;MatrixUtil.TYPE_INFO_POLY=0x537;MatrixUtil.TYPE_INFO_MASK_PATTERN=0x5412;class BlockPair{constructor(dataBytes,errorCorrectionBytes){this.dataBytes=dataBytes;this.errorCorrectionBytes=errorCorrectionBytes;}
getDataBytes(){return this.dataBytes;}
getErrorCorrectionBytes(){return this.errorCorrectionBytes;}}
class Encoder{constructor(){}
static calculateMaskPenalty(matrix){return MaskUtil.applyMaskPenaltyRule1(matrix)
+MaskUtil.applyMaskPenaltyRule2(matrix)
+MaskUtil.applyMaskPenaltyRule3(matrix)
+MaskUtil.applyMaskPenaltyRule4(matrix);}
static encode(content,ecLevel,hints=null){let encoding=Encoder.DEFAULT_BYTE_MODE_ENCODING;const hasEncodingHint=hints!==null&&undefined!==hints.get(EncodeHintType$1.CHARACTER_SET);if(hasEncodingHint){encoding=hints.get(EncodeHintType$1.CHARACTER_SET).toString();}
const mode=this.chooseMode(content,encoding);const headerBits=new BitArray();if(mode===Mode$1.BYTE&&(hasEncodingHint||Encoder.DEFAULT_BYTE_MODE_ENCODING!==encoding)){const eci=CharacterSetECI.getCharacterSetECIByName(encoding);if(eci!==undefined){this.appendECI(eci,headerBits);}}
this.appendModeInfo(mode,headerBits);const dataBits=new BitArray();this.appendBytes(content,mode,dataBits,encoding);let version;if(hints!==null&&undefined!==hints.get(EncodeHintType$1.QR_VERSION)){const versionNumber=Number.parseInt(hints.get(EncodeHintType$1.QR_VERSION).toString(),10);version=Version$1.getVersionForNumber(versionNumber);const bitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,version);if(!this.willFit(bitsNeeded,version,ecLevel)){throw new WriterException('Data too big for requested version');}}
else{version=this.recommendVersion(ecLevel,mode,headerBits,dataBits);}
const headerAndDataBits=new BitArray();headerAndDataBits.appendBitArray(headerBits);const numLetters=mode===Mode$1.BYTE?dataBits.getSizeInBytes():content.length;this.appendLengthInfo(numLetters,version,mode,headerAndDataBits);headerAndDataBits.appendBitArray(dataBits);const ecBlocks=version.getECBlocksForLevel(ecLevel);const numDataBytes=version.getTotalCodewords()-ecBlocks.getTotalECCodewords();this.terminateBits(numDataBytes,headerAndDataBits);const finalBits=this.interleaveWithECBytes(headerAndDataBits,version.getTotalCodewords(),numDataBytes,ecBlocks.getNumBlocks());const qrCode=new QRCode();qrCode.setECLevel(ecLevel);qrCode.setMode(mode);qrCode.setVersion(version);const dimension=version.getDimensionForVersion();const matrix=new ByteMatrix(dimension,dimension);const maskPattern=this.chooseMaskPattern(finalBits,ecLevel,version,matrix);qrCode.setMaskPattern(maskPattern);MatrixUtil.buildMatrix(finalBits,ecLevel,version,maskPattern,matrix);qrCode.setMatrix(matrix);return qrCode;}
static recommendVersion(ecLevel,mode,headerBits,dataBits){const provisionalBitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,Version$1.getVersionForNumber(1));const provisionalVersion=this.chooseVersion(provisionalBitsNeeded,ecLevel);const bitsNeeded=this.calculateBitsNeeded(mode,headerBits,dataBits,provisionalVersion);return this.chooseVersion(bitsNeeded,ecLevel);}
static calculateBitsNeeded(mode,headerBits,dataBits,version){return headerBits.getSize()+mode.getCharacterCountBits(version)+dataBits.getSize();}
static getAlphanumericCode(code){if(code<Encoder.ALPHANUMERIC_TABLE.length){return Encoder.ALPHANUMERIC_TABLE[code];}
return-1;}
static chooseMode(content,encoding=null){if(CharacterSetECI.SJIS.getName()===encoding&&this.isOnlyDoubleByteKanji(content)){return Mode$1.KANJI;}
let hasNumeric=false;let hasAlphanumeric=false;for(let i=0,length=content.length;i<length;++i){const c=content.charAt(i);if(Encoder.isDigit(c)){hasNumeric=true;}
else if(this.getAlphanumericCode(c.charCodeAt(0))!==-1){hasAlphanumeric=true;}
else{return Mode$1.BYTE;}}
if(hasAlphanumeric){return Mode$1.ALPHANUMERIC;}
if(hasNumeric){return Mode$1.NUMERIC;}
return Mode$1.BYTE;}
static isOnlyDoubleByteKanji(content){let bytes;try{bytes=StringEncoding.encode(content,CharacterSetECI.SJIS);}
catch(ignored){return false;}
const length=bytes.length;if(length%2!==0){return false;}
for(let i=0;i<length;i+=2){const byte1=bytes[i]&0xFF;if((byte1<0x81||byte1>0x9F)&&(byte1<0xE0||byte1>0xEB)){return false;}}
return true;}
static chooseMaskPattern(bits,ecLevel,version,matrix){let minPenalty=Number.MAX_SAFE_INTEGER;let bestMaskPattern=-1;for(let maskPattern=0;maskPattern<QRCode.NUM_MASK_PATTERNS;maskPattern++){MatrixUtil.buildMatrix(bits,ecLevel,version,maskPattern,matrix);let penalty=this.calculateMaskPenalty(matrix);if(penalty<minPenalty){minPenalty=penalty;bestMaskPattern=maskPattern;}}
return bestMaskPattern;}
static chooseVersion(numInputBits,ecLevel){for(let versionNum=1;versionNum<=40;versionNum++){const version=Version$1.getVersionForNumber(versionNum);if(Encoder.willFit(numInputBits,version,ecLevel)){return version;}}
throw new WriterException('Data too big');}
static willFit(numInputBits,version,ecLevel){const numBytes=version.getTotalCodewords();const ecBlocks=version.getECBlocksForLevel(ecLevel);const numEcBytes=ecBlocks.getTotalECCodewords();const numDataBytes=numBytes-numEcBytes;const totalInputBytes=(numInputBits+7)/8;return numDataBytes>=totalInputBytes;}
static terminateBits(numDataBytes,bits){const capacity=numDataBytes*8;if(bits.getSize()>capacity){throw new WriterException('data bits cannot fit in the QR Code'+bits.getSize()+' > '+
capacity);}
for(let i=0;i<4&&bits.getSize()<capacity;++i){bits.appendBit(false);}
const numBitsInLastByte=bits.getSize()&0x07;if(numBitsInLastByte>0){for(let i=numBitsInLastByte;i<8;i++){bits.appendBit(false);}}
const numPaddingBytes=numDataBytes-bits.getSizeInBytes();for(let i=0;i<numPaddingBytes;++i){bits.appendBits((i&0x01)===0?0xEC:0x11,8);}
if(bits.getSize()!==capacity){throw new WriterException('Bits size does not equal capacity');}}
static getNumDataBytesAndNumECBytesForBlockID(numTotalBytes,numDataBytes,numRSBlocks,blockID,numDataBytesInBlock,numECBytesInBlock){if(blockID>=numRSBlocks){throw new WriterException('Block ID too large');}
const numRsBlocksInGroup2=numTotalBytes%numRSBlocks;const numRsBlocksInGroup1=numRSBlocks-numRsBlocksInGroup2;const numTotalBytesInGroup1=Math.floor(numTotalBytes/numRSBlocks);const numTotalBytesInGroup2=numTotalBytesInGroup1+1;const numDataBytesInGroup1=Math.floor(numDataBytes/numRSBlocks);const numDataBytesInGroup2=numDataBytesInGroup1+1;const numEcBytesInGroup1=numTotalBytesInGroup1-numDataBytesInGroup1;const numEcBytesInGroup2=numTotalBytesInGroup2-numDataBytesInGroup2;if(numEcBytesInGroup1!==numEcBytesInGroup2){throw new WriterException('EC bytes mismatch');}
if(numRSBlocks!==numRsBlocksInGroup1+numRsBlocksInGroup2){throw new WriterException('RS blocks mismatch');}
if(numTotalBytes!==((numDataBytesInGroup1+numEcBytesInGroup1)*numRsBlocksInGroup1)+
((numDataBytesInGroup2+numEcBytesInGroup2)*numRsBlocksInGroup2)){throw new WriterException('Total bytes mismatch');}
if(blockID<numRsBlocksInGroup1){numDataBytesInBlock[0]=numDataBytesInGroup1;numECBytesInBlock[0]=numEcBytesInGroup1;}
else{numDataBytesInBlock[0]=numDataBytesInGroup2;numECBytesInBlock[0]=numEcBytesInGroup2;}}
static interleaveWithECBytes(bits,numTotalBytes,numDataBytes,numRSBlocks){if(bits.getSizeInBytes()!==numDataBytes){throw new WriterException('Number of bits and data bytes does not match');}
let dataBytesOffset=0;let maxNumDataBytes=0;let maxNumEcBytes=0;const blocks=new Array();for(let i=0;i<numRSBlocks;++i){const numDataBytesInBlock=new Int32Array(1);const numEcBytesInBlock=new Int32Array(1);Encoder.getNumDataBytesAndNumECBytesForBlockID(numTotalBytes,numDataBytes,numRSBlocks,i,numDataBytesInBlock,numEcBytesInBlock);const size=numDataBytesInBlock[0];const dataBytes=new Uint8Array(size);bits.toBytes(8*dataBytesOffset,dataBytes,0,size);const ecBytes=Encoder.generateECBytes(dataBytes,numEcBytesInBlock[0]);blocks.push(new BlockPair(dataBytes,ecBytes));maxNumDataBytes=Math.max(maxNumDataBytes,size);maxNumEcBytes=Math.max(maxNumEcBytes,ecBytes.length);dataBytesOffset+=numDataBytesInBlock[0];}
if(numDataBytes!==dataBytesOffset){throw new WriterException('Data bytes does not match offset');}
const result=new BitArray();for(let i=0;i<maxNumDataBytes;++i){for(const block of blocks){const dataBytes=block.getDataBytes();if(i<dataBytes.length){result.appendBits(dataBytes[i],8);}}}
for(let i=0;i<maxNumEcBytes;++i){for(const block of blocks){const ecBytes=block.getErrorCorrectionBytes();if(i<ecBytes.length){result.appendBits(ecBytes[i],8);}}}
if(numTotalBytes!==result.getSizeInBytes()){throw new WriterException('Interleaving error: '+numTotalBytes+' and '+
result.getSizeInBytes()+' differ.');}
return result;}
static generateECBytes(dataBytes,numEcBytesInBlock){const numDataBytes=dataBytes.length;const toEncode=new Int32Array(numDataBytes+numEcBytesInBlock);for(let i=0;i<numDataBytes;i++){toEncode[i]=dataBytes[i]&0xFF;}
new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode,numEcBytesInBlock);const ecBytes=new Uint8Array(numEcBytesInBlock);for(let i=0;i<numEcBytesInBlock;i++){ecBytes[i]=toEncode[numDataBytes+i];}
return ecBytes;}
static appendModeInfo(mode,bits){bits.appendBits(mode.getBits(),4);}
static appendLengthInfo(numLetters,version,mode,bits){const numBits=mode.getCharacterCountBits(version);if(numLetters>=(1<<numBits)){throw new WriterException(numLetters+' is bigger than '+((1<<numBits)-1));}
bits.appendBits(numLetters,numBits);}
static appendBytes(content,mode,bits,encoding){switch(mode){case Mode$1.NUMERIC:Encoder.appendNumericBytes(content,bits);break;case Mode$1.ALPHANUMERIC:Encoder.appendAlphanumericBytes(content,bits);break;case Mode$1.BYTE:Encoder.append8BitBytes(content,bits,encoding);break;case Mode$1.KANJI:Encoder.appendKanjiBytes(content,bits);break;default:throw new WriterException('Invalid mode: '+mode);}}
static getDigit(singleCharacter){return singleCharacter.charCodeAt(0)-48;}
static isDigit(singleCharacter){const cn=Encoder.getDigit(singleCharacter);return cn>=0&&cn<=9;}
static appendNumericBytes(content,bits){const length=content.length;let i=0;while(i<length){const num1=Encoder.getDigit(content.charAt(i));if(i+2<length){const num2=Encoder.getDigit(content.charAt(i+1));const num3=Encoder.getDigit(content.charAt(i+2));bits.appendBits(num1*100+num2*10+num3,10);i+=3;}
else if(i+1<length){const num2=Encoder.getDigit(content.charAt(i+1));bits.appendBits(num1*10+num2,7);i+=2;}
else{bits.appendBits(num1,4);i++;}}}
static appendAlphanumericBytes(content,bits){const length=content.length;let i=0;while(i<length){const code1=Encoder.getAlphanumericCode(content.charCodeAt(i));if(code1===-1){throw new WriterException();}
if(i+1<length){const code2=Encoder.getAlphanumericCode(content.charCodeAt(i+1));if(code2===-1){throw new WriterException();}
bits.appendBits(code1*45+code2,11);i+=2;}
else{bits.appendBits(code1,6);i++;}}}
static append8BitBytes(content,bits,encoding){let bytes;try{bytes=StringEncoding.encode(content,encoding);}
catch(uee){throw new WriterException(uee);}
for(let i=0,length=bytes.length;i!==length;i++){const b=bytes[i];bits.appendBits(b,8);}}
static appendKanjiBytes(content,bits){let bytes;try{bytes=StringEncoding.encode(content,CharacterSetECI.SJIS);}
catch(uee){throw new WriterException(uee);}
const length=bytes.length;for(let i=0;i<length;i+=2){const byte1=bytes[i]&0xFF;const byte2=bytes[i+1]&0xFF;const code=((byte1<<8)&0xFFFFFFFF)|byte2;let subtracted=-1;if(code>=0x8140&&code<=0x9ffc){subtracted=code-0x8140;}
else if(code>=0xe040&&code<=0xebbf){subtracted=code-0xc140;}
if(subtracted===-1){throw new WriterException('Invalid byte sequence');}
const encoded=((subtracted>>8)*0xc0)+(subtracted&0xff);bits.appendBits(encoded,13);}}
static appendECI(eci,bits){bits.appendBits(Mode$1.ECI.getBits(),4);bits.appendBits(eci.getValue(),8);}}
Encoder.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,]);Encoder.DEFAULT_BYTE_MODE_ENCODING=CharacterSetECI.UTF8.getName();class BrowserQRCodeSvgWriter{write(contents,width,height,hints=null){if(contents.length===0){throw new IllegalArgumentException('Found empty contents');}
if(width<0||height<0){throw new IllegalArgumentException('Requested dimensions are too small: '+width+'x'+height);}
let errorCorrectionLevel=ErrorCorrectionLevel.L;let quietZone=BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE;if(hints!==null){if(undefined!==hints.get(EncodeHintType$1.ERROR_CORRECTION)){errorCorrectionLevel=ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}
if(undefined!==hints.get(EncodeHintType$1.MARGIN)){quietZone=Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(),10);}}
const code=Encoder.encode(contents,errorCorrectionLevel,hints);return this.renderResult(code,width,height,quietZone);}
writeToDom(containerElement,contents,width,height,hints=null){if(typeof containerElement==='string'){containerElement=document.querySelector(containerElement);}
const svgElement=this.write(contents,width,height,hints);if(containerElement)
containerElement.appendChild(svgElement);}
renderResult(code,width,height,quietZone){const input=code.getMatrix();if(input===null){throw new IllegalStateException();}
const inputWidth=input.getWidth();const inputHeight=input.getHeight();const qrWidth=inputWidth+(quietZone*2);const qrHeight=inputHeight+(quietZone*2);const outputWidth=Math.max(width,qrWidth);const outputHeight=Math.max(height,qrHeight);const multiple=Math.min(Math.floor(outputWidth/qrWidth),Math.floor(outputHeight/qrHeight));const leftPadding=Math.floor((outputWidth-(inputWidth*multiple))/2);const topPadding=Math.floor((outputHeight-(inputHeight*multiple))/2);const svgElement=this.createSVGElement(outputWidth,outputHeight);for(let inputY=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){for(let inputX=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)===1){const svgRectElement=this.createSvgRectElement(outputX,outputY,multiple,multiple);svgElement.appendChild(svgRectElement);}}}
return svgElement;}
createSVGElement(w,h){const svgElement=document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS,'svg');svgElement.setAttributeNS(null,'height',w.toString());svgElement.setAttributeNS(null,'width',h.toString());return svgElement;}
createSvgRectElement(x,y,w,h){const rect=document.createElementNS(BrowserQRCodeSvgWriter.SVG_NS,'rect');rect.setAttributeNS(null,'x',x.toString());rect.setAttributeNS(null,'y',y.toString());rect.setAttributeNS(null,'height',w.toString());rect.setAttributeNS(null,'width',h.toString());rect.setAttributeNS(null,'fill','#000000');return rect;}}
BrowserQRCodeSvgWriter.QUIET_ZONE_SIZE=4;BrowserQRCodeSvgWriter.SVG_NS='http://www.w3.org/2000/svg';class QRCodeWriter{encode(contents,format,width,height,hints){if(contents.length===0){throw new IllegalArgumentException('Found empty contents');}
if(format!==BarcodeFormat$1.QR_CODE){throw new IllegalArgumentException('Can only encode QR_CODE, but got '+format);}
if(width<0||height<0){throw new IllegalArgumentException(`Requested dimensions are too small: ${width}x${height}`);}
let errorCorrectionLevel=ErrorCorrectionLevel.L;let quietZone=QRCodeWriter.QUIET_ZONE_SIZE;if(hints!==null){if(undefined!==hints.get(EncodeHintType$1.ERROR_CORRECTION)){errorCorrectionLevel=ErrorCorrectionLevel.fromString(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}
if(undefined!==hints.get(EncodeHintType$1.MARGIN)){quietZone=Number.parseInt(hints.get(EncodeHintType$1.MARGIN).toString(),10);}}
const code=Encoder.encode(contents,errorCorrectionLevel,hints);return QRCodeWriter.renderResult(code,width,height,quietZone);}
static renderResult(code,width,height,quietZone){const input=code.getMatrix();if(input===null){throw new IllegalStateException();}
const inputWidth=input.getWidth();const inputHeight=input.getHeight();const qrWidth=inputWidth+(quietZone*2);const qrHeight=inputHeight+(quietZone*2);const outputWidth=Math.max(width,qrWidth);const outputHeight=Math.max(height,qrHeight);const multiple=Math.min(Math.floor(outputWidth/qrWidth),Math.floor(outputHeight/qrHeight));const leftPadding=Math.floor((outputWidth-(inputWidth*multiple))/2);const topPadding=Math.floor((outputHeight-(inputHeight*multiple))/2);const output=new BitMatrix(outputWidth,outputHeight);for(let inputY=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){for(let inputX=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)===1){output.setRegion(outputX,outputY,multiple,multiple);}}}
return output;}}
QRCodeWriter.QUIET_ZONE_SIZE=4;class MultiFormatWriter{encode(contents,format,width,height,hints){let writer;switch(format){case BarcodeFormat$1.QR_CODE:writer=new QRCodeWriter();break;default:throw new IllegalArgumentException('No encoder available for format '+format);}
return writer.encode(contents,format,width,height,hints);}}
class PlanarYUVLuminanceSource extends LuminanceSource{constructor(yuvData,dataWidth,dataHeight,left,top,width,height,reverseHorizontal){super(width,height);this.yuvData=yuvData;this.dataWidth=dataWidth;this.dataHeight=dataHeight;this.left=left;this.top=top;if(left+width>dataWidth||top+height>dataHeight){throw new IllegalArgumentException('Crop rectangle does not fit within image data.');}
if(reverseHorizontal){this.reverseHorizontal(width,height);}}
getRow(y,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}
const width=this.getWidth();if(row===null||row===undefined||row.length<width){row=new Uint8ClampedArray(width);}
const offset=(y+this.top)*this.dataWidth+this.left;System.arraycopy(this.yuvData,offset,row,0,width);return row;}
getMatrix(){const width=this.getWidth();const height=this.getHeight();if(width===this.dataWidth&&height===this.dataHeight){return this.yuvData;}
const area=width*height;const matrix=new Uint8ClampedArray(area);let inputOffset=this.top*this.dataWidth+this.left;if(width===this.dataWidth){System.arraycopy(this.yuvData,inputOffset,matrix,0,area);return matrix;}
for(let y=0;y<height;y++){const outputOffset=y*width;System.arraycopy(this.yuvData,inputOffset,matrix,outputOffset,width);inputOffset+=this.dataWidth;}
return matrix;}
isCropSupported(){return true;}
crop(left,top,width,height){return new PlanarYUVLuminanceSource(this.yuvData,this.dataWidth,this.dataHeight,this.left+left,this.top+top,width,height,false);}
renderThumbnail(){const width=this.getWidth()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;const height=this.getHeight()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;const pixels=new Int32Array(width*height);const yuv=this.yuvData;let inputOffset=this.top*this.dataWidth+this.left;for(let y=0;y<height;y++){const outputOffset=y*width;for(let x=0;x<width;x++){const grey=yuv[inputOffset+x*PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR]&0xff;pixels[outputOffset+x]=0xFF000000|(grey*0x00010101);}
inputOffset+=this.dataWidth*PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}
return pixels;}
getThumbnailWidth(){return this.getWidth()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}
getThumbnailHeight(){return this.getHeight()/PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR;}
reverseHorizontal(width,height){const yuvData=this.yuvData;for(let y=0,rowStart=this.top*this.dataWidth+this.left;y<height;y++,rowStart+=this.dataWidth){const middle=rowStart+width/2;for(let x1=rowStart,x2=rowStart+width-1;x1<middle;x1++,x2--){const temp=yuvData[x1];yuvData[x1]=yuvData[x2];yuvData[x2]=temp;}}}
invert(){return new InvertedLuminanceSource(this);}}
PlanarYUVLuminanceSource.THUMBNAIL_SCALE_FACTOR=2;class RGBLuminanceSource extends LuminanceSource{constructor(luminances,width,height,dataWidth,dataHeight,left,top){super(width,height);this.dataWidth=dataWidth;this.dataHeight=dataHeight;this.left=left;this.top=top;if(luminances.BYTES_PER_ELEMENT===4){const size=width*height;const luminancesUint8Array=new Uint8ClampedArray(size);for(let offset=0;offset<size;offset++){const pixel=luminances[offset];const r=(pixel>>16)&0xff;const g2=(pixel>>7)&0x1fe;const b=pixel&0xff;luminancesUint8Array[offset]=((r+g2+b)/4)&0xFF;}
this.luminances=luminancesUint8Array;}
else{this.luminances=luminances;}
if(undefined===dataWidth){this.dataWidth=width;}
if(undefined===dataHeight){this.dataHeight=height;}
if(undefined===left){this.left=0;}
if(undefined===top){this.top=0;}
if(this.left+width>this.dataWidth||this.top+height>this.dataHeight){throw new IllegalArgumentException('Crop rectangle does not fit within image data.');}}
getRow(y,row){if(y<0||y>=this.getHeight()){throw new IllegalArgumentException('Requested row is outside the image: '+y);}
const width=this.getWidth();if(row===null||row===undefined||row.length<width){row=new Uint8ClampedArray(width);}
const offset=(y+this.top)*this.dataWidth+this.left;System.arraycopy(this.luminances,offset,row,0,width);return row;}
getMatrix(){const width=this.getWidth();const height=this.getHeight();if(width===this.dataWidth&&height===this.dataHeight){return this.luminances;}
const area=width*height;const matrix=new Uint8ClampedArray(area);let inputOffset=this.top*this.dataWidth+this.left;if(width===this.dataWidth){System.arraycopy(this.luminances,inputOffset,matrix,0,area);return matrix;}
for(let y=0;y<height;y++){const outputOffset=y*width;System.arraycopy(this.luminances,inputOffset,matrix,outputOffset,width);inputOffset+=this.dataWidth;}
return matrix;}
isCropSupported(){return true;}
crop(left,top,width,height){return new RGBLuminanceSource(this.luminances,width,height,this.dataWidth,this.dataHeight,this.left+left,this.top+top);}
invert(){return new InvertedLuminanceSource(this);}}
class Charset extends CharacterSetECI{static forName(name){return this.getCharacterSetECIByName(name);}}
class StandardCharsets{}
StandardCharsets.ISO_8859_1=CharacterSetECI.ISO8859_1;class DefaultPlacement{constructor(codewords,numcols,numrows){this.codewords=codewords;this.numcols=numcols;this.numrows=numrows;this.bits=new Uint8Array(numcols*numrows);Arrays.fill(this.bits,2);}
getNumrows(){return this.numrows;}
getNumcols(){return this.numcols;}
getBits(){return this.bits;}
getBit(col,row){return this.bits[row*this.numcols+col]===1;}
setBit(col,row,bit){this.bits[row*this.numcols+col]=bit?1:0;}
noBit(col,row){return this.bits[row*this.numcols+col]===2;}
place(){let pos=0;let row=4;let col=0;do{if(row===this.numrows&&col===0){this.corner1(pos++);}
if(row===this.numrows-2&&col===0&&this.numcols%4!==0){this.corner2(pos++);}
if(row===this.numrows-2&&col===0&&this.numcols%8===4){this.corner3(pos++);}
if(row===this.numrows+4&&col===2&&this.numcols%8===0){this.corner4(pos++);}
do{if(row<this.numrows&&col>=0&&this.noBit(col,row)){this.utah(row,col,pos++);}
row-=2;col+=2;}while(row>=0&&col<this.numcols);row++;col+=3;do{if(row>=0&&col<this.numcols&&this.noBit(col,row)){this.utah(row,col,pos++);}
row+=2;col-=2;}while(row<this.numrows&&col>=0);row+=3;col++;}while(row<this.numrows||col<this.numcols);if(this.noBit(this.numcols-1,this.numrows-1)){this.setBit(this.numcols-1,this.numrows-1,true);this.setBit(this.numcols-2,this.numrows-2,true);}}
module(row,col,pos,bit){if(row<0){row+=this.numrows;col+=4-((this.numrows+4)%8);}
if(col<0){col+=this.numcols;row+=4-((this.numcols+4)%8);}
let v=this.codewords.charCodeAt(pos);v&=1<<(8-bit);this.setBit(col,row,v!==0);}
utah(row,col,pos){this.module(row-2,col-2,pos,1);this.module(row-2,col-1,pos,2);this.module(row-1,col-2,pos,3);this.module(row-1,col-1,pos,4);this.module(row-1,col,pos,5);this.module(row,col-2,pos,6);this.module(row,col-1,pos,7);this.module(row,col,pos,8);}
corner1(pos){this.module(this.numrows-1,0,pos,1);this.module(this.numrows-1,1,pos,2);this.module(this.numrows-1,2,pos,3);this.module(0,this.numcols-2,pos,4);this.module(0,this.numcols-1,pos,5);this.module(1,this.numcols-1,pos,6);this.module(2,this.numcols-1,pos,7);this.module(3,this.numcols-1,pos,8);}
corner2(pos){this.module(this.numrows-3,0,pos,1);this.module(this.numrows-2,0,pos,2);this.module(this.numrows-1,0,pos,3);this.module(0,this.numcols-4,pos,4);this.module(0,this.numcols-3,pos,5);this.module(0,this.numcols-2,pos,6);this.module(0,this.numcols-1,pos,7);this.module(1,this.numcols-1,pos,8);}
corner3(pos){this.module(this.numrows-3,0,pos,1);this.module(this.numrows-2,0,pos,2);this.module(this.numrows-1,0,pos,3);this.module(0,this.numcols-2,pos,4);this.module(0,this.numcols-1,pos,5);this.module(1,this.numcols-1,pos,6);this.module(2,this.numcols-1,pos,7);this.module(3,this.numcols-1,pos,8);}
corner4(pos){this.module(this.numrows-1,0,pos,1);this.module(this.numrows-1,this.numcols-1,pos,2);this.module(0,this.numcols-3,pos,3);this.module(0,this.numcols-2,pos,4);this.module(0,this.numcols-1,pos,5);this.module(1,this.numcols-3,pos,6);this.module(1,this.numcols-2,pos,7);this.module(1,this.numcols-1,pos,8);}}
const FACTOR_SETS=[5,7,10,11,12,14,18,20,24,28,36,42,48,56,62,68,];const FACTORS=[[228,48,15,111,62],[23,68,144,134,240,92,254],[28,24,185,166,223,248,116,255,110,61],[175,138,205,12,194,168,39,245,60,97,120],[41,153,158,91,61,42,142,213,97,178,100,242],[156,97,192,252,95,9,157,119,138,45,18,186,83,185],[83,195,100,39,188,75,66,61,241,213,109,129,94,254,225,48,90,188,],[15,195,244,9,233,71,168,2,188,160,153,145,253,79,108,82,27,174,186,172,],[52,190,88,205,109,39,176,21,155,197,251,223,155,21,5,172,254,124,12,181,184,96,50,193,],[211,231,43,97,71,96,103,174,37,151,170,53,75,34,249,121,17,138,110,213,141,136,120,151,233,168,93,255,],[245,127,242,218,130,250,162,181,102,120,84,179,220,251,80,182,229,18,2,4,68,33,101,137,95,119,115,44,175,184,59,25,225,98,81,112,],[77,193,137,31,19,38,22,153,247,105,122,2,245,133,242,8,175,95,100,9,167,105,214,111,57,121,21,1,253,57,54,101,248,202,69,50,150,177,226,5,9,5,],[245,132,172,223,96,32,117,22,238,133,238,231,205,188,237,87,191,106,16,147,118,23,37,90,170,205,131,88,120,100,66,138,186,240,82,44,176,87,187,147,160,175,69,213,92,253,225,19,],[175,9,223,238,12,17,220,208,100,29,175,170,230,192,215,235,150,159,36,223,38,200,132,54,228,146,218,234,117,203,29,232,144,238,22,150,201,117,62,207,164,13,137,245,127,67,247,28,155,43,203,107,233,53,143,46,],[242,93,169,50,144,210,39,118,202,188,201,189,143,108,196,37,185,112,134,230,245,63,197,190,250,106,185,221,175,64,114,71,161,44,147,6,27,218,51,63,87,10,40,130,188,17,163,31,176,170,4,107,232,7,94,166,224,124,86,47,11,204,],[220,228,173,89,251,149,159,56,89,33,147,244,154,36,73,127,213,136,248,180,234,197,158,177,68,122,93,213,15,160,227,236,66,139,153,185,202,167,179,25,220,232,96,210,231,136,223,239,181,241,59,52,172,25,49,232,211,189,64,54,108,153,132,63,96,103,82,186,],];const MODULO_VALUE=0x12d;const static_LOG=(LOG,ALOG)=>{let p=1;for(let i=0;i<255;i++){ALOG[i]=p;LOG[p]=i;p*=2;if(p>=256){p^=MODULO_VALUE;}}
return{LOG,ALOG,};};const{LOG,ALOG}=static_LOG([],[]);(function(SymbolShapeHint){SymbolShapeHint[SymbolShapeHint["FORCE_NONE"]=0]="FORCE_NONE";SymbolShapeHint[SymbolShapeHint["FORCE_SQUARE"]=1]="FORCE_SQUARE";SymbolShapeHint[SymbolShapeHint["FORCE_RECTANGLE"]=2]="FORCE_RECTANGLE";})(exports.DataMatrixSymbolShapeHint||(exports.DataMatrixSymbolShapeHint={}));const PAD=129;const LATCH_TO_C40=230;const LATCH_TO_BASE256=231;const UPPER_SHIFT=235;const MACRO_05=236;const MACRO_06=237;const LATCH_TO_ANSIX12=238;const LATCH_TO_TEXT=239;const LATCH_TO_EDIFACT=240;const C40_UNLATCH=254;const X12_UNLATCH=254;const MACRO_05_HEADER='[)>\u001E05\u001D';const MACRO_06_HEADER='[)>\u001E06\u001D';const MACRO_TRAILER='\u001E\u0004';const ASCII_ENCODATION=0;const C40_ENCODATION=1;const TEXT_ENCODATION=2;const X12_ENCODATION=3;const EDIFACT_ENCODATION=4;const BASE256_ENCODATION=5;class ErrorCorrection$1{static encodeECC200(codewords,symbolInfo){if(codewords.length!==symbolInfo.getDataCapacity()){throw new Error('The number of codewords does not match the selected symbol');}
const sb=new StringBuilder();sb.append(codewords);const blockCount=symbolInfo.getInterleavedBlockCount();if(blockCount===1){const ecc=this.createECCBlock(codewords,symbolInfo.getErrorCodewords());sb.append(ecc);}
else{const dataSizes=[];const errorSizes=[];for(let i=0;i<blockCount;i++){dataSizes[i]=symbolInfo.getDataLengthForInterleavedBlock(i+1);errorSizes[i]=symbolInfo.getErrorLengthForInterleavedBlock(i+1);}
for(let block=0;block<blockCount;block++){const temp=new StringBuilder();for(let d=block;d<symbolInfo.getDataCapacity();d+=blockCount){temp.append(codewords.charAt(d));}
const ecc=this.createECCBlock(temp.toString(),errorSizes[block]);let pos=0;for(let e=block;e<errorSizes[block]*blockCount;e+=blockCount){sb.setCharAt(symbolInfo.getDataCapacity()+e,ecc.charAt(pos++));}}}
return sb.toString();}
static createECCBlock(codewords,numECWords){let table=-1;for(let i=0;i<FACTOR_SETS.length;i++){if(FACTOR_SETS[i]===numECWords){table=i;break;}}
if(table<0){throw new Error('Illegal number of error correction codewords specified: '+numECWords);}
const poly=FACTORS[table];const ecc=[];for(let i=0;i<numECWords;i++){ecc[i]=0;}
for(let i=0;i<codewords.length;i++){let m=ecc[numECWords-1]^codewords.charAt(i).charCodeAt(0);for(let k=numECWords-1;k>0;k--){if(m!==0&&poly[k]!==0){ecc[k]=ecc[k-1]^ALOG[(LOG[m]+LOG[poly[k]])%255];}
else{ecc[k]=ecc[k-1];}}
if(m!==0&&poly[0]!==0){ecc[0]=ALOG[(LOG[m]+LOG[poly[0]])%255];}
else{ecc[0]=0;}}
const eccReversed=[];for(let i=0;i<numECWords;i++){eccReversed[i]=ecc[numECWords-i-1];}
return eccReversed.map(c=>String.fromCharCode(c)).join('');}}
class ASCIIEncoder{getEncodingMode(){return ASCII_ENCODATION;}
encode(context){const n=HighLevelEncoder.determineConsecutiveDigitCount(context.getMessage(),context.pos);if(n>=2){context.writeCodeword(this.encodeASCIIDigits(context.getMessage().charCodeAt(context.pos),context.getMessage().charCodeAt(context.pos+1)));context.pos+=2;}
else{const c=context.getCurrentChar();const newMode=HighLevelEncoder.lookAheadTest(context.getMessage(),context.pos,this.getEncodingMode());if(newMode!==this.getEncodingMode()){switch(newMode){case BASE256_ENCODATION:context.writeCodeword(LATCH_TO_BASE256);context.signalEncoderChange(BASE256_ENCODATION);return;case C40_ENCODATION:context.writeCodeword(LATCH_TO_C40);context.signalEncoderChange(C40_ENCODATION);return;case X12_ENCODATION:context.writeCodeword(LATCH_TO_ANSIX12);context.signalEncoderChange(X12_ENCODATION);break;case TEXT_ENCODATION:context.writeCodeword(LATCH_TO_TEXT);context.signalEncoderChange(TEXT_ENCODATION);break;case EDIFACT_ENCODATION:context.writeCodeword(LATCH_TO_EDIFACT);context.signalEncoderChange(EDIFACT_ENCODATION);break;default:throw new Error('Illegal mode: '+newMode);}}
else if(HighLevelEncoder.isExtendedASCII(c)){context.writeCodeword(UPPER_SHIFT);context.writeCodeword(c-128+1);context.pos++;}
else{context.writeCodeword(c+1);context.pos++;}}}
encodeASCIIDigits(digit1,digit2){if(HighLevelEncoder.isDigit(digit1)&&HighLevelEncoder.isDigit(digit2)){const num=(digit1-48)*10+(digit2-48);return num+130;}
throw new Error('not digits: '+digit1+digit2);}}
class Base256Encoder{getEncodingMode(){return BASE256_ENCODATION;}
encode(context){const buffer=new StringBuilder();buffer.append(0o0);while(context.hasMoreCharacters()){const c=context.getCurrentChar();buffer.append(c);context.pos++;const newMode=HighLevelEncoder.lookAheadTest(context.getMessage(),context.pos,this.getEncodingMode());if(newMode!==this.getEncodingMode()){context.signalEncoderChange(ASCII_ENCODATION);break;}}
const dataCount=buffer.length()-1;const lengthFieldSize=1;const currentSize=context.getCodewordCount()+dataCount+lengthFieldSize;context.updateSymbolInfo(currentSize);const mustPad=context.getSymbolInfo().getDataCapacity()-currentSize>0;if(context.hasMoreCharacters()||mustPad){if(dataCount<=249){buffer.setCharAt(0,StringUtils.getCharAt(dataCount));}
else if(dataCount<=1555){buffer.setCharAt(0,StringUtils.getCharAt(Math.floor(dataCount/250)+249));buffer.insert(1,StringUtils.getCharAt(dataCount%250));}
else{throw new Error('Message length not in valid ranges: '+dataCount);}}
for(let i=0,c=buffer.length();i<c;i++){context.writeCodeword(this.randomize255State(buffer.charAt(i).charCodeAt(0),context.getCodewordCount()+1));}}
randomize255State(ch,codewordPosition){const pseudoRandom=((149*codewordPosition)%255)+1;const tempVariable=ch+pseudoRandom;if(tempVariable<=255){return tempVariable;}
else{return tempVariable-256;}}}
class C40Encoder{getEncodingMode(){return C40_ENCODATION;}
encodeMaximal(context){const buffer=new StringBuilder();let lastCharSize=0;let backtrackStartPosition=context.pos;let backtrackBufferLength=0;while(context.hasMoreCharacters()){const c=context.getCurrentChar();context.pos++;lastCharSize=this.encodeChar(c,buffer);if(buffer.length()%3===0){backtrackStartPosition=context.pos;backtrackBufferLength=buffer.length();}}
if(backtrackBufferLength!==buffer.length()){const unwritten=Math.floor((buffer.length()/3)*2);const curCodewordCount=Math.floor(context.getCodewordCount()+unwritten+1);context.updateSymbolInfo(curCodewordCount);const available=context.getSymbolInfo().getDataCapacity()-curCodewordCount;const rest=Math.floor(buffer.length()%3);if((rest===2&&available!==2)||(rest===1&&(lastCharSize>3||available!==1))){context.pos=backtrackStartPosition;}}
if(buffer.length()>0){context.writeCodeword(LATCH_TO_C40);}
this.handleEOD(context,buffer);}
encode(context){const buffer=new StringBuilder();while(context.hasMoreCharacters()){const c=context.getCurrentChar();context.pos++;let lastCharSize=this.encodeChar(c,buffer);const unwritten=Math.floor(buffer.length()/3)*2;const curCodewordCount=context.getCodewordCount()+unwritten;context.updateSymbolInfo(curCodewordCount);const available=context.getSymbolInfo().getDataCapacity()-curCodewordCount;if(!context.hasMoreCharacters()){const removed=new StringBuilder();if(buffer.length()%3===2&&available!==2){lastCharSize=this.backtrackOneCharacter(context,buffer,removed,lastCharSize);}
while(buffer.length()%3===1&&(lastCharSize>3||available!==1)){lastCharSize=this.backtrackOneCharacter(context,buffer,removed,lastCharSize);}
break;}
const count=buffer.length();if(count%3===0){const newMode=HighLevelEncoder.lookAheadTest(context.getMessage(),context.pos,this.getEncodingMode());if(newMode!==this.getEncodingMode()){context.signalEncoderChange(ASCII_ENCODATION);break;}}}
this.handleEOD(context,buffer);}
backtrackOneCharacter(context,buffer,removed,lastCharSize){const count=buffer.length();const test=buffer.toString().substring(0,count-lastCharSize);buffer.setLengthToZero();buffer.append(test);context.pos--;const c=context.getCurrentChar();lastCharSize=this.encodeChar(c,removed);context.resetSymbolInfo();return lastCharSize;}
writeNextTriplet(context,buffer){context.writeCodewords(this.encodeToCodewords(buffer.toString()));const test=buffer.toString().substring(3);buffer.setLengthToZero();buffer.append(test);}
handleEOD(context,buffer){const unwritten=Math.floor((buffer.length()/3)*2);const rest=buffer.length()%3;const curCodewordCount=context.getCodewordCount()+unwritten;context.updateSymbolInfo(curCodewordCount);const available=context.getSymbolInfo().getDataCapacity()-curCodewordCount;if(rest===2){buffer.append('\0');while(buffer.length()>=3){this.writeNextTriplet(context,buffer);}
if(context.hasMoreCharacters()){context.writeCodeword(C40_UNLATCH);}}
else if(available===1&&rest===1){while(buffer.length()>=3){this.writeNextTriplet(context,buffer);}
if(context.hasMoreCharacters()){context.writeCodeword(C40_UNLATCH);}
context.pos--;}
else if(rest===0){while(buffer.length()>=3){this.writeNextTriplet(context,buffer);}
if(available>0||context.hasMoreCharacters()){context.writeCodeword(C40_UNLATCH);}}
else{throw new Error('Unexpected case. Please report!');}
context.signalEncoderChange(ASCII_ENCODATION);}
encodeChar(c,sb){if(c===' '.charCodeAt(0)){sb.append(0o3);return 1;}
if(c>='0'.charCodeAt(0)&&c<='9'.charCodeAt(0)){sb.append(c-48+4);return 1;}
if(c>='A'.charCodeAt(0)&&c<='Z'.charCodeAt(0)){sb.append(c-65+14);return 1;}
if(c<' '.charCodeAt(0)){sb.append(0o0);sb.append(c);return 2;}
if(c<='/'.charCodeAt(0)){sb.append(0o1);sb.append(c-33);return 2;}
if(c<='@'.charCodeAt(0)){sb.append(0o1);sb.append(c-58+15);return 2;}
if(c<='_'.charCodeAt(0)){sb.append(0o1);sb.append(c-91+22);return 2;}
if(c<=127){sb.append(0o2);sb.append(c-96);return 2;}
sb.append(`${0o1}\u001e`);let len=2;len+=this.encodeChar(c-128,sb);return len;}
encodeToCodewords(sb){const v=1600*sb.charCodeAt(0)+40*sb.charCodeAt(1)+sb.charCodeAt(2)+1;const cw1=v/256;const cw2=v%256;const result=new StringBuilder();result.append(cw1);result.append(cw2);return result.toString();}}
class EdifactEncoder{getEncodingMode(){return EDIFACT_ENCODATION;}
encode(context){const buffer=new StringBuilder();while(context.hasMoreCharacters()){const c=context.getCurrentChar();this.encodeChar(c,buffer);context.pos++;const count=buffer.length();if(count>=4){context.writeCodewords(this.encodeToCodewords(buffer.toString()));const test=buffer.toString().substring(4);buffer.setLengthToZero();buffer.append(test);const newMode=HighLevelEncoder.lookAheadTest(context.getMessage(),context.pos,this.getEncodingMode());if(newMode!==this.getEncodingMode()){context.signalEncoderChange(ASCII_ENCODATION);break;}}}
buffer.append(StringUtils.getCharAt(31));this.handleEOD(context,buffer);}
handleEOD(context,buffer){try{const count=buffer.length();if(count===0){return;}
if(count===1){context.updateSymbolInfo();let available=context.getSymbolInfo().getDataCapacity()-
context.getCodewordCount();const remaining=context.getRemainingCharacters();if(remaining>available){context.updateSymbolInfo(context.getCodewordCount()+1);available=context.getSymbolInfo().getDataCapacity()-
context.getCodewordCount();}
if(remaining<=available&&available<=2){return;}}
if(count>4){throw new Error('Count must not exceed 4');}
const restChars=count-1;const encoded=this.encodeToCodewords(buffer.toString());const endOfSymbolReached=!context.hasMoreCharacters();let restInAscii=endOfSymbolReached&&restChars<=2;if(restChars<=2){context.updateSymbolInfo(context.getCodewordCount()+restChars);const available=context.getSymbolInfo().getDataCapacity()-
context.getCodewordCount();if(available>=3){restInAscii=false;context.updateSymbolInfo(context.getCodewordCount()+encoded.length);}}
if(restInAscii){context.resetSymbolInfo();context.pos-=restChars;}
else{context.writeCodewords(encoded);}}
finally{context.signalEncoderChange(ASCII_ENCODATION);}}
encodeChar(c,sb){if(c>=' '.charCodeAt(0)&&c<='?'.charCodeAt(0)){sb.append(c);}
else if(c>='@'.charCodeAt(0)&&c<='^'.charCodeAt(0)){sb.append(StringUtils.getCharAt(c-64));}
else{HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));}}
encodeToCodewords(sb){const len=sb.length;if(len===0){throw new Error('StringBuilder must not be empty');}
const c1=sb.charAt(0).charCodeAt(0);const c2=len>=2?sb.charAt(1).charCodeAt(0):0;const c3=len>=3?sb.charAt(2).charCodeAt(0):0;const c4=len>=4?sb.charAt(3).charCodeAt(0):0;const v=(c1<<18)+(c2<<12)+(c3<<6)+c4;const cw1=(v>>16)&255;const cw2=(v>>8)&255;const cw3=v&255;const res=new StringBuilder();res.append(cw1);if(len>=2){res.append(cw2);}
if(len>=3){res.append(cw3);}
return res.toString();}}
class SymbolInfo{constructor(rectangular,dataCapacity,errorCodewords,matrixWidth,matrixHeight,dataRegions,rsBlockData=0,rsBlockError=0){this.rectangular=rectangular;this.dataCapacity=dataCapacity;this.errorCodewords=errorCodewords;this.matrixWidth=matrixWidth;this.matrixHeight=matrixHeight;this.dataRegions=dataRegions;this.rsBlockData=rsBlockData;this.rsBlockError=rsBlockError;}
static lookup(dataCodewords,shape=0,minSize=null,maxSize=null,fail=true){for(const symbol of PROD_SYMBOLS){if(shape===1&&symbol.rectangular){continue;}
if(shape===2&&!symbol.rectangular){continue;}
if(minSize!=null&&(symbol.getSymbolWidth()<minSize.getWidth()||symbol.getSymbolHeight()<minSize.getHeight())){continue;}
if(maxSize!=null&&(symbol.getSymbolWidth()>maxSize.getWidth()||symbol.getSymbolHeight()>maxSize.getHeight())){continue;}
if(dataCodewords<=symbol.dataCapacity){return symbol;}}
if(fail){throw new Error("Can't find a symbol arrangement that matches the message. Data codewords: "+
dataCodewords);}
return null;}
getHorizontalDataRegions(){switch(this.dataRegions){case 1:return 1;case 2:case 4:return 2;case 16:return 4;case 36:return 6;default:throw new Error('Cannot handle this number of data regions');}}
getVerticalDataRegions(){switch(this.dataRegions){case 1:case 2:return 1;case 4:return 2;case 16:return 4;case 36:return 6;default:throw new Error('Cannot handle this number of data regions');}}
getSymbolDataWidth(){return this.getHorizontalDataRegions()*this.matrixWidth;}
getSymbolDataHeight(){return this.getVerticalDataRegions()*this.matrixHeight;}
getSymbolWidth(){return this.getSymbolDataWidth()+this.getHorizontalDataRegions()*2;}
getSymbolHeight(){return this.getSymbolDataHeight()+this.getVerticalDataRegions()*2;}
getCodewordCount(){return this.dataCapacity+this.errorCodewords;}
getInterleavedBlockCount(){if(!this.rsBlockData)
return 1;return this.dataCapacity/this.rsBlockData;}
getDataCapacity(){return this.dataCapacity;}
getErrorCodewords(){return this.errorCodewords;}
getDataLengthForInterleavedBlock(index){return this.rsBlockData;}
getErrorLengthForInterleavedBlock(index){return this.rsBlockError;}}
class DataMatrixSymbolInfo144 extends SymbolInfo{constructor(){super(false,1558,620,22,22,36,-1,62);}
getInterleavedBlockCount(){return 10;}
getDataLengthForInterleavedBlock(index){return index<=8?156:155;}}
const PROD_SYMBOLS=[new SymbolInfo(false,3,5,8,8,1),new SymbolInfo(false,5,7,10,10,1),new SymbolInfo(true,5,7,16,6,1),new SymbolInfo(false,8,10,12,12,1),new SymbolInfo(true,10,11,14,6,2),new SymbolInfo(false,12,12,14,14,1),new SymbolInfo(true,16,14,24,10,1),new SymbolInfo(false,18,14,16,16,1),new SymbolInfo(false,22,18,18,18,1),new SymbolInfo(true,22,18,16,10,2),new SymbolInfo(false,30,20,20,20,1),new SymbolInfo(true,32,24,16,14,2),new SymbolInfo(false,36,24,22,22,1),new SymbolInfo(false,44,28,24,24,1),new SymbolInfo(true,49,28,22,14,2),new SymbolInfo(false,62,36,14,14,4),new SymbolInfo(false,86,42,16,16,4),new SymbolInfo(false,114,48,18,18,4),new SymbolInfo(false,144,56,20,20,4),new SymbolInfo(false,174,68,22,22,4),new SymbolInfo(false,204,84,24,24,4,102,42),new SymbolInfo(false,280,112,14,14,16,140,56),new SymbolInfo(false,368,144,16,16,16,92,36),new SymbolInfo(false,456,192,18,18,16,114,48),new SymbolInfo(false,576,224,20,20,16,144,56),new SymbolInfo(false,696,272,22,22,16,174,68),new SymbolInfo(false,816,336,24,24,16,136,56),new SymbolInfo(false,1050,408,18,18,36,175,68),new SymbolInfo(false,1304,496,20,20,36,163,62),new DataMatrixSymbolInfo144(),];class EncoderContext{constructor(msg){this.msg=msg;this.pos=0;this.skipAtEnd=0;const msgBinary=msg.split('').map(c=>c.charCodeAt(0));const sb=new StringBuilder();for(let i=0,c=msgBinary.length;i<c;i++){const ch=String.fromCharCode(msgBinary[i]&0xff);if(ch==='?'&&msg.charAt(i)!=='?'){throw new Error('Message contains characters outside ISO-8859-1 encoding.');}
sb.append(ch);}
this.msg=sb.toString();this.shape=0;this.codewords=new StringBuilder();this.newEncoding=-1;}
setSymbolShape(shape){this.shape=shape;}
setSizeConstraints(minSize,maxSize){this.minSize=minSize;this.maxSize=maxSize;}
getMessage(){return this.msg;}
setSkipAtEnd(count){this.skipAtEnd=count;}
getCurrentChar(){return this.msg.charCodeAt(this.pos);}
getCurrent(){return this.msg.charCodeAt(this.pos);}
getCodewords(){return this.codewords;}
writeCodewords(codewords){this.codewords.append(codewords);}
writeCodeword(codeword){this.codewords.append(codeword);}
getCodewordCount(){return this.codewords.length();}
getNewEncoding(){return this.newEncoding;}
signalEncoderChange(encoding){this.newEncoding=encoding;}
resetEncoderSignal(){this.newEncoding=-1;}
hasMoreCharacters(){return this.pos<this.getTotalMessageCharCount();}
getTotalMessageCharCount(){return this.msg.length-this.skipAtEnd;}
getRemainingCharacters(){return this.getTotalMessageCharCount()-this.pos;}
getSymbolInfo(){return this.symbolInfo;}
updateSymbolInfo(len=this.getCodewordCount()){if(this.symbolInfo==null||len>this.symbolInfo.getDataCapacity()){this.symbolInfo=SymbolInfo.lookup(len,this.shape,this.minSize,this.maxSize,true);}}
resetSymbolInfo(){this.symbolInfo=null;}}
class X12Encoder extends C40Encoder{getEncodingMode(){return X12_ENCODATION;}
encode(context){const buffer=new StringBuilder();while(context.hasMoreCharacters()){const c=context.getCurrentChar();context.pos++;this.encodeChar(c,buffer);const count=buffer.length();if(count%3===0){this.writeNextTriplet(context,buffer);const newMode=HighLevelEncoder.lookAheadTest(context.getMessage(),context.pos,this.getEncodingMode());if(newMode!==this.getEncodingMode()){context.signalEncoderChange(ASCII_ENCODATION);break;}}}
this.handleEOD(context,buffer);}
encodeChar(c,sb){switch(c){case 13:sb.append(0o0);break;case'*'.charCodeAt(0):sb.append(0o1);break;case'>'.charCodeAt(0):sb.append(0o2);break;case' '.charCodeAt(0):sb.append(0o3);break;default:if(c>='0'.charCodeAt(0)&&c<='9'.charCodeAt(0)){sb.append(c-48+4);}
else if(c>='A'.charCodeAt(0)&&c<='Z'.charCodeAt(0)){sb.append(c-65+14);}
else{HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));}
break;}
return 1;}
handleEOD(context,buffer){context.updateSymbolInfo();const available=context.getSymbolInfo().getDataCapacity()-context.getCodewordCount();const count=buffer.length();context.pos-=count;if(context.getRemainingCharacters()>1||available>1||context.getRemainingCharacters()!==available){context.writeCodeword(X12_UNLATCH);}
if(context.getNewEncoding()<0){context.signalEncoderChange(ASCII_ENCODATION);}}}
class TextEncoder$1 extends C40Encoder{getEncodingMode(){return TEXT_ENCODATION;}
encodeChar(c,sb){if(c===' '.charCodeAt(0)){sb.append(0o3);return 1;}
if(c>='0'.charCodeAt(0)&&c<='9'.charCodeAt(0)){sb.append(c-48+4);return 1;}
if(c>='a'.charCodeAt(0)&&c<='z'.charCodeAt(0)){sb.append(c-97+14);return 1;}
if(c<' '.charCodeAt(0)){sb.append(0o0);sb.append(c);return 2;}
if(c<='/'.charCodeAt(0)){sb.append(0o1);sb.append(c-33);return 2;}
if(c<='@'.charCodeAt(0)){sb.append(0o1);sb.append(c-58+15);return 2;}
if(c>='['.charCodeAt(0)&&c<='_'.charCodeAt(0)){sb.append(0o1);sb.append(c-91+22);return 2;}
if(c==='`'.charCodeAt(0)){sb.append(0o2);sb.append(0);return 2;}
if(c<='Z'.charCodeAt(0)){sb.append(0o2);sb.append(c-65+1);return 2;}
if(c<=127){sb.append(0o2);sb.append(c-123+27);return 2;}
sb.append(`${0o1}\u001e`);let len=2;len+=this.encodeChar(c-128,sb);return len;}}
class HighLevelEncoder{static randomize253State(codewordPosition){const pseudoRandom=((149*codewordPosition)%253)+1;const tempVariable=PAD+pseudoRandom;return tempVariable<=254?tempVariable:tempVariable-254;}
static encodeHighLevel(msg,shape=0,minSize=null,maxSize=null,forceC40=false){const c40Encoder=new C40Encoder();const encoders=[new ASCIIEncoder(),c40Encoder,new TextEncoder$1(),new X12Encoder(),new EdifactEncoder(),new Base256Encoder(),];const context=new EncoderContext(msg);context.setSymbolShape(shape);context.setSizeConstraints(minSize,maxSize);if(msg.startsWith(MACRO_05_HEADER)&&msg.endsWith(MACRO_TRAILER)){context.writeCodeword(MACRO_05);context.setSkipAtEnd(2);context.pos+=MACRO_05_HEADER.length;}
else if(msg.startsWith(MACRO_06_HEADER)&&msg.endsWith(MACRO_TRAILER)){context.writeCodeword(MACRO_06);context.setSkipAtEnd(2);context.pos+=MACRO_06_HEADER.length;}
let encodingMode=ASCII_ENCODATION;if(forceC40){c40Encoder.encodeMaximal(context);encodingMode=context.getNewEncoding();context.resetEncoderSignal();}
while(context.hasMoreCharacters()){encoders[encodingMode].encode(context);if(context.getNewEncoding()>=0){encodingMode=context.getNewEncoding();context.resetEncoderSignal();}}
const len=context.getCodewordCount();context.updateSymbolInfo();const capacity=context.getSymbolInfo().getDataCapacity();if(len<capacity&&encodingMode!==ASCII_ENCODATION&&encodingMode!==BASE256_ENCODATION&&encodingMode!==EDIFACT_ENCODATION){context.writeCodeword('\u00fe');}
const codewords=context.getCodewords();if(codewords.length()<capacity){codewords.append(PAD);}
while(codewords.length()<capacity){codewords.append(this.randomize253State(codewords.length()+1));}
return context.getCodewords().toString();}
static lookAheadTest(msg,startpos,currentMode){const newMode=this.lookAheadTestIntern(msg,startpos,currentMode);if(currentMode===X12_ENCODATION&&newMode===X12_ENCODATION){const endpos=Math.min(startpos+3,msg.length);for(let i=startpos;i<endpos;i++){if(!this.isNativeX12(msg.charCodeAt(i))){return ASCII_ENCODATION;}}}
else if(currentMode===EDIFACT_ENCODATION&&newMode===EDIFACT_ENCODATION){const endpos=Math.min(startpos+4,msg.length);for(let i=startpos;i<endpos;i++){if(!this.isNativeEDIFACT(msg.charCodeAt(i))){return ASCII_ENCODATION;}}}
return newMode;}
static lookAheadTestIntern(msg,startpos,currentMode){if(startpos>=msg.length){return currentMode;}
let charCounts;if(currentMode===ASCII_ENCODATION){charCounts=[0,1,1,1,1,1.25];}
else{charCounts=[1,2,2,2,2,2.25];charCounts[currentMode]=0;}
let charsProcessed=0;const mins=new Uint8Array(6);const intCharCounts=[];while(true){if(startpos+charsProcessed===msg.length){Arrays.fill(mins,0);Arrays.fill(intCharCounts,0);const min=this.findMinimums(charCounts,intCharCounts,Integer.MAX_VALUE,mins);const minCount=this.getMinimumCount(mins);if(intCharCounts[ASCII_ENCODATION]===min){return ASCII_ENCODATION;}
if(minCount===1){if(mins[BASE256_ENCODATION]>0){return BASE256_ENCODATION;}
if(mins[EDIFACT_ENCODATION]>0){return EDIFACT_ENCODATION;}
if(mins[TEXT_ENCODATION]>0){return TEXT_ENCODATION;}
if(mins[X12_ENCODATION]>0){return X12_ENCODATION;}}
return C40_ENCODATION;}
const c=msg.charCodeAt(startpos+charsProcessed);charsProcessed++;if(this.isDigit(c)){charCounts[ASCII_ENCODATION]+=0.5;}
else if(this.isExtendedASCII(c)){charCounts[ASCII_ENCODATION]=Math.ceil(charCounts[ASCII_ENCODATION]);charCounts[ASCII_ENCODATION]+=2.0;}
else{charCounts[ASCII_ENCODATION]=Math.ceil(charCounts[ASCII_ENCODATION]);charCounts[ASCII_ENCODATION]++;}
if(this.isNativeC40(c)){charCounts[C40_ENCODATION]+=2.0/3.0;}
else if(this.isExtendedASCII(c)){charCounts[C40_ENCODATION]+=8.0/3.0;}
else{charCounts[C40_ENCODATION]+=4.0/3.0;}
if(this.isNativeText(c)){charCounts[TEXT_ENCODATION]+=2.0/3.0;}
else if(this.isExtendedASCII(c)){charCounts[TEXT_ENCODATION]+=8.0/3.0;}
else{charCounts[TEXT_ENCODATION]+=4.0/3.0;}
if(this.isNativeX12(c)){charCounts[X12_ENCODATION]+=2.0/3.0;}
else if(this.isExtendedASCII(c)){charCounts[X12_ENCODATION]+=13.0/3.0;}
else{charCounts[X12_ENCODATION]+=10.0/3.0;}
if(this.isNativeEDIFACT(c)){charCounts[EDIFACT_ENCODATION]+=3.0/4.0;}
else if(this.isExtendedASCII(c)){charCounts[EDIFACT_ENCODATION]+=17.0/4.0;}
else{charCounts[EDIFACT_ENCODATION]+=13.0/4.0;}
if(this.isSpecialB256(c)){charCounts[BASE256_ENCODATION]+=4.0;}
else{charCounts[BASE256_ENCODATION]++;}
if(charsProcessed>=4){Arrays.fill(mins,0);Arrays.fill(intCharCounts,0);this.findMinimums(charCounts,intCharCounts,Integer.MAX_VALUE,mins);if(intCharCounts[ASCII_ENCODATION]<this.min(intCharCounts[BASE256_ENCODATION],intCharCounts[C40_ENCODATION],intCharCounts[TEXT_ENCODATION],intCharCounts[X12_ENCODATION],intCharCounts[EDIFACT_ENCODATION])){return ASCII_ENCODATION;}
if(intCharCounts[BASE256_ENCODATION]<intCharCounts[ASCII_ENCODATION]||intCharCounts[BASE256_ENCODATION]+1<this.min(intCharCounts[C40_ENCODATION],intCharCounts[TEXT_ENCODATION],intCharCounts[X12_ENCODATION],intCharCounts[EDIFACT_ENCODATION])){return BASE256_ENCODATION;}
if(intCharCounts[EDIFACT_ENCODATION]+1<this.min(intCharCounts[BASE256_ENCODATION],intCharCounts[C40_ENCODATION],intCharCounts[TEXT_ENCODATION],intCharCounts[X12_ENCODATION],intCharCounts[ASCII_ENCODATION])){return EDIFACT_ENCODATION;}
if(intCharCounts[TEXT_ENCODATION]+1<this.min(intCharCounts[BASE256_ENCODATION],intCharCounts[C40_ENCODATION],intCharCounts[EDIFACT_ENCODATION],intCharCounts[X12_ENCODATION],intCharCounts[ASCII_ENCODATION])){return TEXT_ENCODATION;}
if(intCharCounts[X12_ENCODATION]+1<this.min(intCharCounts[BASE256_ENCODATION],intCharCounts[C40_ENCODATION],intCharCounts[EDIFACT_ENCODATION],intCharCounts[TEXT_ENCODATION],intCharCounts[ASCII_ENCODATION])){return X12_ENCODATION;}
if(intCharCounts[C40_ENCODATION]+1<this.min(intCharCounts[ASCII_ENCODATION],intCharCounts[BASE256_ENCODATION],intCharCounts[EDIFACT_ENCODATION],intCharCounts[TEXT_ENCODATION])){if(intCharCounts[C40_ENCODATION]<intCharCounts[X12_ENCODATION]){return C40_ENCODATION;}
if(intCharCounts[C40_ENCODATION]===intCharCounts[X12_ENCODATION]){let p=startpos+charsProcessed+1;while(p<msg.length){const tc=msg.charCodeAt(p);if(this.isX12TermSep(tc)){return X12_ENCODATION;}
if(!this.isNativeX12(tc)){break;}
p++;}
return C40_ENCODATION;}}}}}
static min(f1,f2,f3,f4,f5){const val=Math.min(f1,Math.min(f2,Math.min(f3,f4)));if(f5===undefined){return val;}
else{return Math.min(val,f5);}}
static findMinimums(charCounts,intCharCounts,min,mins){for(let i=0;i<6;i++){const current=(intCharCounts[i]=Math.ceil(charCounts[i]));if(min>current){min=current;Arrays.fill(mins,0);}
if(min===current){mins[i]=mins[i]+1;}}
return min;}
static getMinimumCount(mins){let minCount=0;for(let i=0;i<6;i++){minCount+=mins[i];}
return minCount||0;}
static isDigit(ch){return ch>='0'.charCodeAt(0)&&ch<='9'.charCodeAt(0);}
static isExtendedASCII(ch){return ch>=128&&ch<=255;}
static isNativeC40(ch){return(ch===' '.charCodeAt(0)||(ch>='0'.charCodeAt(0)&&ch<='9'.charCodeAt(0))||(ch>='A'.charCodeAt(0)&&ch<='Z'.charCodeAt(0)));}
static isNativeText(ch){return(ch===' '.charCodeAt(0)||(ch>='0'.charCodeAt(0)&&ch<='9'.charCodeAt(0))||(ch>='a'.charCodeAt(0)&&ch<='z'.charCodeAt(0)));}
static isNativeX12(ch){return(this.isX12TermSep(ch)||ch===' '.charCodeAt(0)||(ch>='0'.charCodeAt(0)&&ch<='9'.charCodeAt(0))||(ch>='A'.charCodeAt(0)&&ch<='Z'.charCodeAt(0)));}
static isX12TermSep(ch){return(ch===13||ch==='*'.charCodeAt(0)||ch==='>'.charCodeAt(0));}
static isNativeEDIFACT(ch){return ch>=' '.charCodeAt(0)&&ch<='^'.charCodeAt(0);}
static isSpecialB256(ch){return false;}
static determineConsecutiveDigitCount(msg,startpos=0){const len=msg.length;let idx=startpos;while(idx<len&&this.isDigit(msg.charCodeAt(idx))){idx++;}
return idx-startpos;}
static illegalCharacter(singleCharacter){let hex=Integer.toHexString(singleCharacter.charCodeAt(0));hex='0000'.substring(0,4-hex.length)+hex;throw new Error('Illegal character: '+singleCharacter+' (0x'+hex+')');}}
class CharsetEncoder{constructor(charset){this.charset=charset;this.name=charset.name;}
canEncode(c){try{return StringEncoding.encode(c,this.charset)!=null;}
catch(ex){return false;}}}
class ECIEncoderSet{constructor(stringToEncode,priorityCharset,fnc1){this.ENCODERS=['IBM437','ISO-8859-2','ISO-8859-3','ISO-8859-4','ISO-8859-5','ISO-8859-6','ISO-8859-7','ISO-8859-8','ISO-8859-9','ISO-8859-10','ISO-8859-11','ISO-8859-13','ISO-8859-14','ISO-8859-15','ISO-8859-16','windows-1250','windows-1251','windows-1252','windows-1256','Shift_JIS',].map(name=>new CharsetEncoder(Charset.forName(name)));this.encoders=[];const neededEncoders=[];neededEncoders.push(new CharsetEncoder(StandardCharsets.ISO_8859_1));let needUnicodeEncoder=priorityCharset!=null&&priorityCharset.name.startsWith('UTF');for(let i=0;i<stringToEncode.length;i++){let canEncode=false;for(const encoder of neededEncoders){const singleCharacter=stringToEncode.charAt(i);const c=singleCharacter.charCodeAt(0);if(c===fnc1||encoder.canEncode(singleCharacter)){canEncode=true;break;}}
if(!canEncode){for(const encoder of this.ENCODERS){if(encoder.canEncode(stringToEncode.charAt(i))){neededEncoders.push(encoder);canEncode=true;break;}}}
if(!canEncode){needUnicodeEncoder=true;}}
if(neededEncoders.length===1&&!needUnicodeEncoder){this.encoders=[neededEncoders[0]];}
else{this.encoders=[];let index=0;for(const encoder of neededEncoders){this.encoders[index++]=encoder;}}
let priorityEncoderIndexValue=-1;if(priorityCharset!=null){for(let i=0;i<this.encoders.length;i++){if(this.encoders[i]!=null&&priorityCharset.name===this.encoders[i].name){priorityEncoderIndexValue=i;break;}}}
this.priorityEncoderIndex=priorityEncoderIndexValue;}
length(){return this.encoders.length;}
getCharsetName(index){if(!(index<this.length())){throw new Error('index must be less than length');}
return this.encoders[index].name;}
getCharset(index){if(!(index<this.length())){throw new Error('index must be less than length');}
return this.encoders[index].charset;}
getECIValue(encoderIndex){return this.encoders[encoderIndex].charset.getValueIdentifier();}
getPriorityEncoderIndex(){return this.priorityEncoderIndex;}
canEncode(c,encoderIndex){if(!(encoderIndex<this.length())){throw new Error('index must be less than length');}
return true;}
encode(c,encoderIndex){if(!(encoderIndex<this.length())){throw new Error('index must be less than length');}
return StringEncoding.encode(StringUtils.getCharAt(c),this.encoders[encoderIndex].name);}}
const COST_PER_ECI=3;class MinimalECIInput{constructor(stringToEncode,priorityCharset,fnc1){this.fnc1=fnc1;const encoderSet=new ECIEncoderSet(stringToEncode,priorityCharset,fnc1);if(encoderSet.length()===1){for(let i=0;i<this.bytes.length;i++){const c=stringToEncode.charAt(i).charCodeAt(0);this.bytes[i]=c===fnc1?1000:c;}}
else{this.bytes=this.encodeMinimally(stringToEncode,encoderSet,fnc1);}}
getFNC1Character(){return this.fnc1;}
length(){return this.bytes.length;}
haveNCharacters(index,n){if(index+n-1>=this.bytes.length){return false;}
for(let i=0;i<n;i++){if(this.isECI(index+i)){return false;}}
return true;}
charAt(index){if(index<0||index>=this.length()){throw new Error(''+index);}
if(this.isECI(index)){throw new Error('value at '+index+' is not a character but an ECI');}
return this.isFNC1(index)?this.fnc1:this.bytes[index];}
subSequence(start,end){if(start<0||start>end||end>this.length()){throw new Error(''+start);}
const result=new StringBuilder();for(let i=start;i<end;i++){if(this.isECI(i)){throw new Error('value at '+i+' is not a character but an ECI');}
result.append(this.charAt(i));}
return result.toString();}
isECI(index){if(index<0||index>=this.length()){throw new Error(''+index);}
return this.bytes[index]>255&&this.bytes[index]<=999;}
isFNC1(index){if(index<0||index>=this.length()){throw new Error(''+index);}
return this.bytes[index]===1000;}
getECIValue(index){if(index<0||index>=this.length()){throw new Error(''+index);}
if(!this.isECI(index)){throw new Error('value at '+index+' is not an ECI but a character');}
return this.bytes[index]-256;}
addEdge(edges,to,edge){if(edges[to][edge.encoderIndex]==null||edges[to][edge.encoderIndex].cachedTotalSize>edge.cachedTotalSize){edges[to][edge.encoderIndex]=edge;}}
addEdges(stringToEncode,encoderSet,edges,from,previous,fnc1){const ch=stringToEncode.charAt(from).charCodeAt(0);let start=0;let end=encoderSet.length();if(encoderSet.getPriorityEncoderIndex()>=0&&(ch===fnc1||encoderSet.canEncode(ch,encoderSet.getPriorityEncoderIndex()))){start=encoderSet.getPriorityEncoderIndex();end=start+1;}
for(let i=start;i<end;i++){if(ch===fnc1||encoderSet.canEncode(ch,i)){this.addEdge(edges,from+1,new InputEdge(ch,encoderSet,i,previous,fnc1));}}}
encodeMinimally(stringToEncode,encoderSet,fnc1){const inputLength=stringToEncode.length;const edges=new InputEdge[inputLength+1][encoderSet.length()]();this.addEdges(stringToEncode,encoderSet,edges,0,null,fnc1);for(let i=1;i<=inputLength;i++){for(let j=0;j<encoderSet.length();j++){if(edges[i][j]!=null&&i<inputLength){this.addEdges(stringToEncode,encoderSet,edges,i,edges[i][j],fnc1);}}
for(let j=0;j<encoderSet.length();j++){edges[i-1][j]=null;}}
let minimalJ=-1;let minimalSize=Integer.MAX_VALUE;for(let j=0;j<encoderSet.length();j++){if(edges[inputLength][j]!=null){const edge=edges[inputLength][j];if(edge.cachedTotalSize<minimalSize){minimalSize=edge.cachedTotalSize;minimalJ=j;}}}
if(minimalJ<0){throw new Error('Failed to encode "'+stringToEncode+'"');}
const intsAL=[];let current=edges[inputLength][minimalJ];while(current!=null){if(current.isFNC1()){intsAL.unshift(1000);}
else{const bytes=encoderSet.encode(current.c,current.encoderIndex);for(let i=bytes.length-1;i>=0;i--){intsAL.unshift(bytes[i]&0xff);}}
const previousEncoderIndex=current.previous===null?0:current.previous.encoderIndex;if(previousEncoderIndex!==current.encoderIndex){intsAL.unshift(256+encoderSet.getECIValue(current.encoderIndex));}
current=current.previous;}
const ints=[];for(let i=0;i<ints.length;i++){ints[i]=intsAL[i];}
return ints;}}
class InputEdge{constructor(c,encoderSet,encoderIndex,previous,fnc1){this.c=c;this.encoderSet=encoderSet;this.encoderIndex=encoderIndex;this.previous=previous;this.fnc1=fnc1;this.c=c===fnc1?1000:c;let size=this.isFNC1()?1:encoderSet.encode(c,encoderIndex).length;const previousEncoderIndex=previous===null?0:previous.encoderIndex;if(previousEncoderIndex!==encoderIndex){size+=COST_PER_ECI;}
if(previous!=null){size+=previous.cachedTotalSize;}
this.cachedTotalSize=size;}
isFNC1(){return this.c===1000;}}
var Mode$3;(function(Mode){Mode[Mode["ASCII"]=0]="ASCII";Mode[Mode["C40"]=1]="C40";Mode[Mode["TEXT"]=2]="TEXT";Mode[Mode["X12"]=3]="X12";Mode[Mode["EDF"]=4]="EDF";Mode[Mode["B256"]=5]="B256";})(Mode$3||(Mode$3={}));const C40_SHIFT2_CHARS=['!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/',':',';','<','=','>','?','@','[','\\',']','^','_',];class MinimalEncoder{static isExtendedASCII(ch,fnc1){return ch!==fnc1&&ch>=128&&ch<=255;}
static isInC40Shift1Set(ch){return ch<=31;}
static isInC40Shift2Set(ch,fnc1){for(const c40Shift2Char of C40_SHIFT2_CHARS){if(c40Shift2Char.charCodeAt(0)===ch){return true;}}
return ch===fnc1;}
static isInTextShift1Set(ch){return this.isInC40Shift1Set(ch);}
static isInTextShift2Set(ch,fnc1){return this.isInC40Shift2Set(ch,fnc1);}
static encodeHighLevel(msg,priorityCharset=null,fnc1=-1,shape=0){let macroId=0;if(msg.startsWith(MACRO_05_HEADER)&&msg.endsWith(MACRO_TRAILER)){macroId=5;msg=msg.substring(MACRO_05_HEADER.length,msg.length-2);}
else if(msg.startsWith(MACRO_06_HEADER)&&msg.endsWith(MACRO_TRAILER)){macroId=6;msg=msg.substring(MACRO_06_HEADER.length,msg.length-2);}
return decodeURIComponent(escape(String.fromCharCode(...this.encode(msg,priorityCharset,fnc1,shape,macroId))));}
static encode(input,priorityCharset,fnc1,shape,macroId){return this.encodeMinimally(new Input(input,priorityCharset,fnc1,shape,macroId)).getBytes();}
static addEdge(edges,edge){const vertexIndex=edge.fromPosition+edge.characterLength;if(edges[vertexIndex][edge.getEndMode()]===null||edges[vertexIndex][edge.getEndMode()].cachedTotalSize>edge.cachedTotalSize){edges[vertexIndex][edge.getEndMode()]=edge;}}
static getNumberOfC40Words(input,from,c40,characterLength){let thirdsCount=0;for(let i=from;i<input.length();i++){if(input.isECI(i)){characterLength[0]=0;return 0;}
const ci=input.charAt(i);if((c40&&HighLevelEncoder.isNativeC40(ci))||(!c40&&HighLevelEncoder.isNativeText(ci))){thirdsCount++;}
else if(!MinimalEncoder.isExtendedASCII(ci,input.getFNC1Character())){thirdsCount+=2;}
else{const asciiValue=ci&0xff;if(asciiValue>=128&&((c40&&HighLevelEncoder.isNativeC40(asciiValue-128))||(!c40&&HighLevelEncoder.isNativeText(asciiValue-128)))){thirdsCount+=3;}
else{thirdsCount+=4;}}
if(thirdsCount%3===0||((thirdsCount-2)%3===0&&i+1===input.length())){characterLength[0]=i-from+1;return Math.ceil(thirdsCount/3.0);}}
characterLength[0]=0;return 0;}
static addEdges(input,edges,from,previous){if(input.isECI(from)){this.addEdge(edges,new Edge(input,Mode$3.ASCII,from,1,previous));return;}
const ch=input.charAt(from);if(previous===null||previous.getEndMode()!==Mode$3.EDF){if(HighLevelEncoder.isDigit(ch)&&input.haveNCharacters(from,2)&&HighLevelEncoder.isDigit(input.charAt(from+1))){this.addEdge(edges,new Edge(input,Mode$3.ASCII,from,2,previous));}
else{this.addEdge(edges,new Edge(input,Mode$3.ASCII,from,1,previous));}
const modes=[Mode$3.C40,Mode$3.TEXT];for(const mode of modes){const characterLength=[];if(MinimalEncoder.getNumberOfC40Words(input,from,mode===Mode$3.C40,characterLength)>0){this.addEdge(edges,new Edge(input,mode,from,characterLength[0],previous));}}
if(input.haveNCharacters(from,3)&&HighLevelEncoder.isNativeX12(input.charAt(from))&&HighLevelEncoder.isNativeX12(input.charAt(from+1))&&HighLevelEncoder.isNativeX12(input.charAt(from+2))){this.addEdge(edges,new Edge(input,Mode$3.X12,from,3,previous));}
this.addEdge(edges,new Edge(input,Mode$3.B256,from,1,previous));}
let i;for(i=0;i<3;i++){const pos=from+i;if(input.haveNCharacters(pos,1)&&HighLevelEncoder.isNativeEDIFACT(input.charAt(pos))){this.addEdge(edges,new Edge(input,Mode$3.EDF,from,i+1,previous));}
else{break;}}
if(i===3&&input.haveNCharacters(from,4)&&HighLevelEncoder.isNativeEDIFACT(input.charAt(from+3))){this.addEdge(edges,new Edge(input,Mode$3.EDF,from,4,previous));}}
static encodeMinimally(input){const inputLength=input.length();const edges=Array(inputLength+1).fill(null).map(()=>Array(6).fill(0));this.addEdges(input,edges,0,null);for(let i=1;i<=inputLength;i++){for(let j=0;j<6;j++){if(edges[i][j]!==null&&i<inputLength){this.addEdges(input,edges,i,edges[i][j]);}}
for(let j=0;j<6;j++){edges[i-1][j]=null;}}
let minimalJ=-1;let minimalSize=Integer.MAX_VALUE;for(let j=0;j<6;j++){if(edges[inputLength][j]!==null){const edge=edges[inputLength][j];const size=j>=1&&j<=3?edge.cachedTotalSize+1:edge.cachedTotalSize;if(size<minimalSize){minimalSize=size;minimalJ=j;}}}
if(minimalJ<0){throw new Error('Failed to encode "'+input+'"');}
return new Result$1(edges[inputLength][minimalJ]);}}
class Result$1{constructor(solution){const input=solution.input;let size=0;let bytesAL=[];const randomizePostfixLength=[];const randomizeLengths=[];if((solution.mode===Mode$3.C40||solution.mode===Mode$3.TEXT||solution.mode===Mode$3.X12)&&solution.getEndMode()!==Mode$3.ASCII){size+=this.prepend(Edge.getBytes(254),bytesAL);}
let current=solution;while(current!==null){size+=this.prepend(current.getDataBytes(),bytesAL);if(current.previous===null||current.getPreviousStartMode()!==current.getMode()){if(current.getMode()===Mode$3.B256){if(size<=249){bytesAL.unshift(size);size++;}
else{bytesAL.unshift(size%250);bytesAL.unshift(size/250+249);size+=2;}
randomizePostfixLength.push(bytesAL.length);randomizeLengths.push(size);}
this.prepend(current.getLatchBytes(),bytesAL);size=0;}
current=current.previous;}
if(input.getMacroId()===5){size+=this.prepend(Edge.getBytes(236),bytesAL);}
else if(input.getMacroId()===6){size+=this.prepend(Edge.getBytes(237),bytesAL);}
if(input.getFNC1Character()>0){size+=this.prepend(Edge.getBytes(232),bytesAL);}
for(let i=0;i<randomizePostfixLength.length;i++){this.applyRandomPattern(bytesAL,bytesAL.length-randomizePostfixLength[i],randomizeLengths[i]);}
const capacity=solution.getMinSymbolSize(bytesAL.length);if(bytesAL.length<capacity){bytesAL.push(129);}
while(bytesAL.length<capacity){bytesAL.push(this.randomize253State(bytesAL.length+1));}
this.bytes=new Uint8Array(bytesAL.length);for(let i=0;i<this.bytes.length;i++){this.bytes[i]=bytesAL[i];}}
prepend(bytes,into){for(let i=bytes.length-1;i>=0;i--){into.unshift(bytes[i]);}
return bytes.length;}
randomize253State(codewordPosition){const pseudoRandom=((149*codewordPosition)%253)+1;const tempVariable=129+pseudoRandom;return tempVariable<=254?tempVariable:tempVariable-254;}
applyRandomPattern(bytesAL,startPosition,length){for(let i=0;i<length;i++){const Pad_codeword_position=startPosition+i;const Pad_codeword_value=bytesAL[Pad_codeword_position]&0xff;const pseudo_random_number=((149*(Pad_codeword_position+1))%255)+1;const temp_variable=Pad_codeword_value+pseudo_random_number;bytesAL[Pad_codeword_position]=temp_variable<=255?temp_variable:temp_variable-256;}}
getBytes(){return this.bytes;}}
class Edge{constructor(input,mode,fromPosition,characterLength,previous){this.input=input;this.mode=mode;this.fromPosition=fromPosition;this.characterLength=characterLength;this.previous=previous;this.allCodewordCapacities=[3,5,8,10,12,16,18,22,30,32,36,44,49,62,86,114,144,174,204,280,368,456,576,696,816,1050,1304,1558,];this.squareCodewordCapacities=[3,5,8,12,18,22,30,36,44,62,86,114,144,174,204,280,368,456,576,696,816,1050,1304,1558,];this.rectangularCodewordCapacities=[5,10,16,33,32,49];if(!(fromPosition+characterLength<=input.length())){throw new Error('Invalid edge');}
let size=previous!==null?previous.cachedTotalSize:0;const previousMode=this.getPreviousMode();switch(mode){case Mode$3.ASCII:size++;if(input.isECI(fromPosition)||MinimalEncoder.isExtendedASCII(input.charAt(fromPosition),input.getFNC1Character())){size++;}
if(previousMode===Mode$3.C40||previousMode===Mode$3.TEXT||previousMode===Mode$3.X12){size++;}
break;case Mode$3.B256:size++;if(previousMode!==Mode$3.B256){size++;}
else if(this.getB256Size()===250){size++;}
if(previousMode===Mode$3.ASCII){size++;}
else if(previousMode===Mode$3.C40||previousMode===Mode$3.TEXT||previousMode===Mode$3.X12){size+=2;}
break;case Mode$3.C40:case Mode$3.TEXT:case Mode$3.X12:if(mode===Mode$3.X12){size+=2;}
else{let charLen=[];size+=MinimalEncoder.getNumberOfC40Words(input,fromPosition,mode===Mode$3.C40,charLen)*2;}
if(previousMode===Mode$3.ASCII||previousMode===Mode$3.B256){size++;}
else if(previousMode!==mode&&(previousMode===Mode$3.C40||previousMode===Mode$3.TEXT||previousMode===Mode$3.X12)){size+=2;}
break;case Mode$3.EDF:size+=3;if(previousMode===Mode$3.ASCII||previousMode===Mode$3.B256){size++;}
else if(previousMode===Mode$3.C40||previousMode===Mode$3.TEXT||previousMode===Mode$3.X12){size+=2;}
break;}
this.cachedTotalSize=size;}
getB256Size(){let cnt=0;let current=this;while(current!==null&&current.mode===Mode$3.B256&&cnt<=250){cnt++;current=current.previous;}
return cnt;}
getPreviousStartMode(){return this.previous===null?Mode$3.ASCII:this.previous.mode;}
getPreviousMode(){return this.previous===null?Mode$3.ASCII:this.previous.getEndMode();}
getEndMode(){if(this.mode===Mode$3.EDF){if(this.characterLength<4){return Mode$3.ASCII;}
const lastASCII=this.getLastASCII();if(lastASCII>0&&this.getCodewordsRemaining(this.cachedTotalSize+lastASCII)<=2-lastASCII){return Mode$3.ASCII;}}
if(this.mode===Mode$3.C40||this.mode===Mode$3.TEXT||this.mode===Mode$3.X12){if(this.fromPosition+this.characterLength>=this.input.length()&&this.getCodewordsRemaining(this.cachedTotalSize)===0){return Mode$3.ASCII;}
const lastASCII=this.getLastASCII();if(lastASCII===1&&this.getCodewordsRemaining(this.cachedTotalSize+1)===0){return Mode$3.ASCII;}}
return this.mode;}
getMode(){return this.mode;}
getLastASCII(){const length=this.input.length();const from=this.fromPosition+this.characterLength;if(length-from>4||from>=length){return 0;}
if(length-from===1){if(MinimalEncoder.isExtendedASCII(this.input.charAt(from),this.input.getFNC1Character())){return 0;}
return 1;}
if(length-from===2){if(MinimalEncoder.isExtendedASCII(this.input.charAt(from),this.input.getFNC1Character())||MinimalEncoder.isExtendedASCII(this.input.charAt(from+1),this.input.getFNC1Character())){return 0;}
if(HighLevelEncoder.isDigit(this.input.charAt(from))&&HighLevelEncoder.isDigit(this.input.charAt(from+1))){return 1;}
return 2;}
if(length-from===3){if(HighLevelEncoder.isDigit(this.input.charAt(from))&&HighLevelEncoder.isDigit(this.input.charAt(from+1))&&!MinimalEncoder.isExtendedASCII(this.input.charAt(from+2),this.input.getFNC1Character())){return 2;}
if(HighLevelEncoder.isDigit(this.input.charAt(from+1))&&HighLevelEncoder.isDigit(this.input.charAt(from+2))&&!MinimalEncoder.isExtendedASCII(this.input.charAt(from),this.input.getFNC1Character())){return 2;}
return 0;}
if(HighLevelEncoder.isDigit(this.input.charAt(from))&&HighLevelEncoder.isDigit(this.input.charAt(from+1))&&HighLevelEncoder.isDigit(this.input.charAt(from+2))&&HighLevelEncoder.isDigit(this.input.charAt(from+3))){return 2;}
return 0;}
getMinSymbolSize(minimum){switch(this.input.getShapeHint()){case 1:for(const capacity of this.squareCodewordCapacities){if(capacity>=minimum){return capacity;}}
break;case 2:for(const capacity of this.rectangularCodewordCapacities){if(capacity>=minimum){return capacity;}}
break;}
for(const capacity of this.allCodewordCapacities){if(capacity>=minimum){return capacity;}}
return this.allCodewordCapacities[this.allCodewordCapacities.length-1];}
getCodewordsRemaining(minimum){return this.getMinSymbolSize(minimum)-minimum;}
static getBytes(c1,c2){const result=new Uint8Array(c2?2:1);result[0]=c1;if(c2){result[1]=c2;}
return result;}
setC40Word(bytes,offset,c1,c2,c3){const val16=1600*(c1&0xff)+40*(c2&0xff)+(c3&0xff)+1;bytes[offset]=val16/256;bytes[offset+1]=val16%256;}
getX12Value(c){return c===13?0:c===42?1:c===62?2:c===32?3:c>=48&&c<=57?c-44:c>=65&&c<=90?c-51:c;}
getX12Words(){if(!(this.characterLength%3===0)){throw new Error('X12 words must be a multiple of 3');}
const result=new Uint8Array((this.characterLength/3)*2);for(let i=0;i<result.length;i+=2){this.setC40Word(result,i,this.getX12Value(this.input.charAt(this.fromPosition+(i/2)*3)),this.getX12Value(this.input.charAt(this.fromPosition+(i/2)*3+1)),this.getX12Value(this.input.charAt(this.fromPosition+(i/2)*3+2)));}
return result;}
getShiftValue(c,c40,fnc1){return(c40&&MinimalEncoder.isInC40Shift1Set(c))||(!c40&&MinimalEncoder.isInTextShift1Set(c))?0:(c40&&MinimalEncoder.isInC40Shift2Set(c,fnc1))||(!c40&&MinimalEncoder.isInTextShift2Set(c,fnc1))?1:2;}
getC40Value(c40,setIndex,c,fnc1){if(c===fnc1){if(!(setIndex===2)){throw new Error('FNC1 cannot be used in C40 shift 2');}
return 27;}
if(c40){return c<=31?c:c===32?3:c<=47?c-33:c<=57?c-44:c<=64?c-43:c<=90?c-51:c<=95?c-69:c<=127?c-96:c;}
else{return c===0?0:setIndex===0&&c<=3?c-1:setIndex===1&&c<=31?c:c===32?3:c>=33&&c<=47?c-33:c>=48&&c<=57?c-44:c>=58&&c<=64?c-43:c>=65&&c<=90?c-64:c>=91&&c<=95?c-69:c===96?0:c>=97&&c<=122?c-83:c>=123&&c<=127?c-96:c;}}
getC40Words(c40,fnc1){const c40Values=[];for(let i=0;i<this.characterLength;i++){const ci=this.input.charAt(this.fromPosition+i);if((c40&&HighLevelEncoder.isNativeC40(ci))||(!c40&&HighLevelEncoder.isNativeText(ci))){c40Values.push(this.getC40Value(c40,0,ci,fnc1));}
else if(!MinimalEncoder.isExtendedASCII(ci,fnc1)){const shiftValue=this.getShiftValue(ci,c40,fnc1);c40Values.push(shiftValue);c40Values.push(this.getC40Value(c40,shiftValue,ci,fnc1));}
else{const asciiValue=(ci&0xff)-128;if((c40&&HighLevelEncoder.isNativeC40(asciiValue))||(!c40&&HighLevelEncoder.isNativeText(asciiValue))){c40Values.push(1);c40Values.push(30);c40Values.push(this.getC40Value(c40,0,asciiValue,fnc1));}
else{c40Values.push(1);c40Values.push(30);const shiftValue=this.getShiftValue(asciiValue,c40,fnc1);c40Values.push(shiftValue);c40Values.push(this.getC40Value(c40,shiftValue,asciiValue,fnc1));}}}
if(c40Values.length%3!==0){if(!((c40Values.length-2)%3===0&&this.fromPosition+this.characterLength===this.input.length())){throw new Error('C40 words must be a multiple of 3');}
c40Values.push(0);}
const result=new Uint8Array((c40Values.length/3)*2);let byteIndex=0;for(let i=0;i<c40Values.length;i+=3){this.setC40Word(result,byteIndex,c40Values[i]&0xff,c40Values[i+1]&0xff,c40Values[i+2]&0xff);byteIndex+=2;}
return result;}
getEDFBytes(){const numberOfThirds=Math.ceil(this.characterLength/4.0);const result=new Uint8Array(numberOfThirds*3);let pos=this.fromPosition;const endPos=Math.min(this.fromPosition+this.characterLength-1,this.input.length()-1);for(let i=0;i<numberOfThirds;i+=3){const edfValues=[];for(let j=0;j<4;j++){if(pos<=endPos){edfValues[j]=this.input.charAt(pos++)&0x3f;}
else{edfValues[j]=pos===endPos+1?0x1f:0;}}
let val24=edfValues[0]<<18;val24|=edfValues[1]<<12;val24|=edfValues[2]<<6;val24|=edfValues[3];result[i]=(val24>>16)&0xff;result[i+1]=(val24>>8)&0xff;result[i+2]=val24&0xff;}
return result;}
getLatchBytes(){switch(this.getPreviousMode()){case Mode$3.ASCII:case Mode$3.B256:switch(this.mode){case Mode$3.B256:return Edge.getBytes(231);case Mode$3.C40:return Edge.getBytes(230);case Mode$3.TEXT:return Edge.getBytes(239);case Mode$3.X12:return Edge.getBytes(238);case Mode$3.EDF:return Edge.getBytes(240);}
break;case Mode$3.C40:case Mode$3.TEXT:case Mode$3.X12:if(this.mode!==this.getPreviousMode()){switch(this.mode){case Mode$3.ASCII:return Edge.getBytes(254);case Mode$3.B256:return Edge.getBytes(254,231);case Mode$3.C40:return Edge.getBytes(254,230);case Mode$3.TEXT:return Edge.getBytes(254,239);case Mode$3.X12:return Edge.getBytes(254,238);case Mode$3.EDF:return Edge.getBytes(254,240);}}
break;case Mode$3.EDF:if(this.mode!==Mode$3.EDF){throw new Error('Cannot switch from EDF to '+this.mode);}
break;}
return new Uint8Array(0);}
getDataBytes(){switch(this.mode){case Mode$3.ASCII:if(this.input.isECI(this.fromPosition)){return Edge.getBytes(241,this.input.getECIValue(this.fromPosition)+1);}
else if(MinimalEncoder.isExtendedASCII(this.input.charAt(this.fromPosition),this.input.getFNC1Character())){return Edge.getBytes(235,this.input.charAt(this.fromPosition)-127);}
else if(this.characterLength===2){return Edge.getBytes(this.input.charAt(this.fromPosition)*10+
this.input.charAt(this.fromPosition+1)+
130);}
else if(this.input.isFNC1(this.fromPosition)){return Edge.getBytes(232);}
else{return Edge.getBytes(this.input.charAt(this.fromPosition)+1);}
case Mode$3.B256:return Edge.getBytes(this.input.charAt(this.fromPosition));case Mode$3.C40:return this.getC40Words(true,this.input.getFNC1Character());case Mode$3.TEXT:return this.getC40Words(false,this.input.getFNC1Character());case Mode$3.X12:return this.getX12Words();case Mode$3.EDF:return this.getEDFBytes();}}}
class Input extends MinimalECIInput{constructor(stringToEncode,priorityCharset,fnc1,shape,macroId){super(stringToEncode,priorityCharset,fnc1);this.shape=shape;this.macroId=macroId;}
getMacroId(){return this.macroId;}
getShapeHint(){return this.shape;}}
class DataMatrixWriter{encode(contents,format,width,height,hints=null){if(contents.trim()===''){throw new Error('Found empty contents');}
if(format!==BarcodeFormat$1.DATA_MATRIX){throw new Error('Can only encode DATA_MATRIX, but got '+format);}
if(width<0||height<0){throw new Error('Requested dimensions can\'t be negative: '+width+'x'+height);}
let shape=0;let minSize=null;let maxSize=null;if(hints!=null){const requestedShape=hints.get(EncodeHintType$1.DATA_MATRIX_SHAPE);if(requestedShape!=null){shape=requestedShape;}
const requestedMinSize=hints.get(EncodeHintType$1.MIN_SIZE);if(requestedMinSize!=null){minSize=requestedMinSize;}
const requestedMaxSize=hints.get(EncodeHintType$1.MAX_SIZE);if(requestedMaxSize!=null){maxSize=requestedMaxSize;}}
let encoded;const hasCompactionHint=hints!=null&&hints.has(EncodeHintType$1.DATA_MATRIX_COMPACT)&&Boolean(hints.get(EncodeHintType$1.DATA_MATRIX_COMPACT).toString());if(hasCompactionHint){const hasGS1FormatHint=hints.has(EncodeHintType$1.GS1_FORMAT)&&Boolean(hints.get(EncodeHintType$1.GS1_FORMAT).toString());let charset=null;const hasEncodingHint=hints.has(EncodeHintType$1.CHARACTER_SET);if(hasEncodingHint){charset=Charset.forName(hints.get(EncodeHintType$1.CHARACTER_SET).toString());}
encoded=MinimalEncoder.encodeHighLevel(contents,charset,hasGS1FormatHint?0x1d:-1,shape);}
else{const hasForceC40Hint=hints!=null&&hints.has(EncodeHintType$1.FORCE_C40)&&Boolean(hints.get(EncodeHintType$1.FORCE_C40).toString());encoded=HighLevelEncoder.encodeHighLevel(contents,shape,minSize,maxSize,hasForceC40Hint);}
const symbolInfo=SymbolInfo.lookup(encoded.length,shape,minSize,maxSize,true);const codewords=ErrorCorrection$1.encodeECC200(encoded,symbolInfo);const placement=new DefaultPlacement(codewords,symbolInfo.getSymbolDataWidth(),symbolInfo.getSymbolDataHeight());placement.place();return this.encodeLowLevel(placement,symbolInfo,width,height);}
encodeLowLevel(placement,symbolInfo,width,height){const symbolWidth=symbolInfo.getSymbolDataWidth();const symbolHeight=symbolInfo.getSymbolDataHeight();const matrix=new ByteMatrix(symbolInfo.getSymbolWidth(),symbolInfo.getSymbolHeight());let matrixY=0;for(let y=0;y<symbolHeight;y++){let matrixX;if(y%symbolInfo.matrixHeight===0){matrixX=0;for(let x=0;x<symbolInfo.getSymbolWidth();x++){matrix.setBoolean(matrixX,matrixY,x%2===0);matrixX++;}
matrixY++;}
matrixX=0;for(let x=0;x<symbolWidth;x++){if(x%symbolInfo.matrixWidth===0){matrix.setBoolean(matrixX,matrixY,true);matrixX++;}
matrix.setBoolean(matrixX,matrixY,placement.getBit(x,y));matrixX++;if(x%symbolInfo.matrixWidth===symbolInfo.matrixWidth-1){matrix.setBoolean(matrixX,matrixY,y%2===0);matrixX++;}}
matrixY++;if(y%symbolInfo.matrixHeight===symbolInfo.matrixHeight-1){matrixX=0;for(let x=0;x<symbolInfo.getSymbolWidth();x++){matrix.setBoolean(matrixX,matrixY,true);matrixX++;}
matrixY++;}}
return this.convertByteMatrixToBitMatrix(matrix,width,height);}
convertByteMatrixToBitMatrix(matrix,reqWidth,reqHeight){const matrixWidth=matrix.getWidth();const matrixHeight=matrix.getHeight();const outputWidth=Math.max(reqWidth,matrixWidth);const outputHeight=Math.max(reqHeight,matrixHeight);const multiple=Math.min(outputWidth/matrixWidth,outputHeight/matrixHeight);let leftPadding=(outputWidth-matrixWidth*multiple)/2;let topPadding=(outputHeight-matrixHeight*multiple)/2;let output;if(reqHeight<matrixHeight||reqWidth<matrixWidth){leftPadding=0;topPadding=0;output=new BitMatrix(matrixWidth,matrixHeight);}
else{output=new BitMatrix(reqWidth,reqHeight);}
output.clear();for(let inputY=0,outputY=topPadding;inputY<matrixHeight;inputY++,outputY+=multiple){for(let inputX=0,outputX=leftPadding;inputX<matrixWidth;inputX++,outputX+=multiple){if(matrix.get(inputX,inputY)===1){output.setRegion(outputX,outputY,multiple,multiple);}}}
return output;}}
class AztecCode{isCompact(){return this.compact;}
setCompact(compact){this.compact=compact;}
getSize(){return this.size;}
setSize(size){this.size=size;}
getLayers(){return this.layers;}
setLayers(layers){this.layers=layers;}
getCodeWords(){return this.codeWords;}
setCodeWords(codeWords){this.codeWords=codeWords;}
getMatrix(){return this.matrix;}
setMatrix(matrix){this.matrix=matrix;}}
class Collections{static singletonList(item){return[item];}
static min(collection,comparator){return collection.sort(comparator)[0];}}
class Token{constructor(previous){this.previous=previous;}
getPrevious(){return this.previous;}}
class SimpleToken extends Token{constructor(previous,value,bitCount){super(previous);this.value=value;this.bitCount=bitCount;}
appendTo(bitArray,text){bitArray.appendBits(this.value,this.bitCount);}
add(value,bitCount){return new SimpleToken(this,value,bitCount);}
addBinaryShift(start,byteCount){console.warn('addBinaryShift on SimpleToken, this simply returns a copy of this token');return new SimpleToken(this,start,byteCount);}
toString(){let value=this.value&((1<<this.bitCount)-1);value|=1<<this.bitCount;return'<'+Integer.toBinaryString(value|(1<<this.bitCount)).substring(1)+'>';}}
class BinaryShiftToken extends SimpleToken{constructor(previous,binaryShiftStart,binaryShiftByteCount){super(previous,0,0);this.binaryShiftStart=binaryShiftStart;this.binaryShiftByteCount=binaryShiftByteCount;}
appendTo(bitArray,text){for(let i=0;i<this.binaryShiftByteCount;i++){if(i===0||(i===31&&this.binaryShiftByteCount<=62)){bitArray.appendBits(31,5);if(this.binaryShiftByteCount>62){bitArray.appendBits(this.binaryShiftByteCount-31,16);}
else if(i===0){bitArray.appendBits(Math.min(this.binaryShiftByteCount,31),5);}
else{bitArray.appendBits(this.binaryShiftByteCount-31,5);}}
bitArray.appendBits(text[this.binaryShiftStart+i],8);}}
addBinaryShift(start,byteCount){return new BinaryShiftToken(this,start,byteCount);}
toString(){return'<'+this.binaryShiftStart+'::'+(this.binaryShiftStart+this.binaryShiftByteCount-1)+'>';}}
function addBinaryShift(token,start,byteCount){return new BinaryShiftToken(token,start,byteCount);}
function add(token,value,bitCount){return new SimpleToken(token,value,bitCount);}
const MODE_NAMES=['UPPER','LOWER','DIGIT','MIXED','PUNCT'];const MODE_UPPER=0;const MODE_LOWER=1;const MODE_DIGIT=2;const MODE_MIXED=3;const MODE_PUNCT=4;const EMPTY_TOKEN=new SimpleToken(null,0,0);const LATCH_TABLE=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,(10<<16)+(29<<5)+30]),Int32Array.from([(9<<16)+(30<<4)+14,0,(5<<16)+30,(5<<16)+29,(10<<16)+(29<<5)+30]),Int32Array.from([(4<<16)+14,(9<<16)+(14<<5)+28,0,(9<<16)+(14<<5)+29,(14<<16)+(14<<10)+(29<<5)+30]),Int32Array.from([(5<<16)+29,(5<<16)+28,(10<<16)+(29<<5)+30,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,(10<<16)+(31<<5)+28,(10<<16)+(31<<5)+30,(10<<16)+(31<<5)+29,0])];function static_SHIFT_TABLE(SHIFT_TABLE){for(let table of SHIFT_TABLE){Arrays.fill(table,-1);}
SHIFT_TABLE[MODE_UPPER][MODE_PUNCT]=0;SHIFT_TABLE[MODE_LOWER][MODE_PUNCT]=0;SHIFT_TABLE[MODE_LOWER][MODE_UPPER]=28;SHIFT_TABLE[MODE_MIXED][MODE_PUNCT]=0;SHIFT_TABLE[MODE_DIGIT][MODE_PUNCT]=0;SHIFT_TABLE[MODE_DIGIT][MODE_UPPER]=15;return SHIFT_TABLE;}
const SHIFT_TABLE=static_SHIFT_TABLE(Arrays.createInt32Array(6,6));class State{constructor(token,mode,binaryBytes,bitCount){this.token=token;this.mode=mode;this.binaryShiftByteCount=binaryBytes;this.bitCount=bitCount;}
getMode(){return this.mode;}
getToken(){return this.token;}
getBinaryShiftByteCount(){return this.binaryShiftByteCount;}
getBitCount(){return this.bitCount;}
latchAndAppend(mode,value){let bitCount=this.bitCount;let token=this.token;if(mode!==this.mode){let latch=LATCH_TABLE[this.mode][mode];token=add(token,latch&0xffff,latch>>16);bitCount+=latch>>16;}
let latchModeBitCount=mode===MODE_DIGIT?4:5;token=add(token,value,latchModeBitCount);return new State(token,mode,0,bitCount+latchModeBitCount);}
shiftAndAppend(mode,value){let token=this.token;let thisModeBitCount=this.mode===MODE_DIGIT?4:5;token=add(token,SHIFT_TABLE[this.mode][mode],thisModeBitCount);token=add(token,value,5);return new State(token,this.mode,0,this.bitCount+thisModeBitCount+5);}
addBinaryShiftChar(index){let token=this.token;let mode=this.mode;let bitCount=this.bitCount;if(this.mode===MODE_PUNCT||this.mode===MODE_DIGIT){let latch=LATCH_TABLE[mode][MODE_UPPER];token=add(token,latch&0xffff,latch>>16);bitCount+=latch>>16;mode=MODE_UPPER;}
let deltaBitCount=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8;let result=new State(token,mode,this.binaryShiftByteCount+1,bitCount+deltaBitCount);if(result.binaryShiftByteCount===2047+31){result=result.endBinaryShift(index+1);}
return result;}
endBinaryShift(index){if(this.binaryShiftByteCount===0){return this;}
let token=this.token;token=addBinaryShift(token,index-this.binaryShiftByteCount,this.binaryShiftByteCount);return new State(token,this.mode,0,this.bitCount);}
isBetterThanOrEqualTo(other){let newModeBitCount=this.bitCount+(LATCH_TABLE[this.mode][other.mode]>>16);if(this.binaryShiftByteCount<other.binaryShiftByteCount){newModeBitCount+=State.calculateBinaryShiftCost(other)-
State.calculateBinaryShiftCost(this);}
else if(this.binaryShiftByteCount>other.binaryShiftByteCount&&other.binaryShiftByteCount>0){newModeBitCount+=10;}
return newModeBitCount<=other.bitCount;}
toBitArray(text){let symbols=[];for(let token=this.endBinaryShift(text.length).token;token!==null;token=token.getPrevious()){symbols.unshift(token);}
let bitArray=new BitArray();for(const symbol of symbols){symbol.appendTo(bitArray,text);}
return bitArray;}
toString(){return StringUtils.format('%s bits=%d bytes=%d',MODE_NAMES[this.mode],this.bitCount,this.binaryShiftByteCount);}
static calculateBinaryShiftCost(state){if(state.binaryShiftByteCount>62){return 21;}
if(state.binaryShiftByteCount>31){return 20;}
if(state.binaryShiftByteCount>0){return 10;}
return 0;}}
State.INITIAL_STATE=new State(EMPTY_TOKEN,MODE_UPPER,0,0);function static_CHAR_MAP(CHAR_MAP){const spaceCharCode=StringUtils.getCharCode(' ');const pointCharCode=StringUtils.getCharCode('.');const commaCharCode=StringUtils.getCharCode(',');CHAR_MAP[MODE_UPPER][spaceCharCode]=1;const zUpperCharCode=StringUtils.getCharCode('Z');const aUpperCharCode=StringUtils.getCharCode('A');for(let c=aUpperCharCode;c<=zUpperCharCode;c++){CHAR_MAP[MODE_UPPER][c]=c-aUpperCharCode+2;}
CHAR_MAP[MODE_LOWER][spaceCharCode]=1;const zLowerCharCode=StringUtils.getCharCode('z');const aLowerCharCode=StringUtils.getCharCode('a');for(let c=aLowerCharCode;c<=zLowerCharCode;c++){CHAR_MAP[MODE_LOWER][c]=c-aLowerCharCode+2;}
CHAR_MAP[MODE_DIGIT][spaceCharCode]=1;const nineCharCode=StringUtils.getCharCode('9');const zeroCharCode=StringUtils.getCharCode('0');for(let c=zeroCharCode;c<=nineCharCode;c++){CHAR_MAP[MODE_DIGIT][c]=c-zeroCharCode+2;}
CHAR_MAP[MODE_DIGIT][commaCharCode]=12;CHAR_MAP[MODE_DIGIT][pointCharCode]=13;const mixedTable=['\x00',' ','\x01','\x02','\x03','\x04','\x05','\x06','\x07','\b','\t','\n','\x0b','\f','\r','\x1b','\x1c','\x1d','\x1e','\x1f','@','\\','^','_','`','|','~','\x7f'];for(let i=0;i<mixedTable.length;i++){CHAR_MAP[MODE_MIXED][StringUtils.getCharCode(mixedTable[i])]=i;}
const punctTable=['\x00','\r','\x00','\x00','\x00','\x00','!','\'','#','$','%','&','\'','(',')','*','+',',','-','.','/',':',';','<','=','>','?','[',']','{','}'];for(let i=0;i<punctTable.length;i++){if(StringUtils.getCharCode(punctTable[i])>0){CHAR_MAP[MODE_PUNCT][StringUtils.getCharCode(punctTable[i])]=i;}}
return CHAR_MAP;}
const CHAR_MAP=static_CHAR_MAP(Arrays.createInt32Array(5,256));class HighLevelEncoder$1{constructor(text){this.text=text;}
encode(){const spaceCharCode=StringUtils.getCharCode(' ');const lineBreakCharCode=StringUtils.getCharCode('\n');let states=Collections.singletonList(State.INITIAL_STATE);for(let index=0;index<this.text.length;index++){let pairCode;let nextChar=index+1<this.text.length?this.text[index+1]:0;switch(this.text[index]){case StringUtils.getCharCode('\r'):pairCode=nextChar===lineBreakCharCode?2:0;break;case StringUtils.getCharCode('.'):pairCode=nextChar===spaceCharCode?3:0;break;case StringUtils.getCharCode(','):pairCode=nextChar===spaceCharCode?4:0;break;case StringUtils.getCharCode(':'):pairCode=nextChar===spaceCharCode?5:0;break;default:pairCode=0;}
if(pairCode>0){states=HighLevelEncoder$1.updateStateListForPair(states,index,pairCode);index++;}
else{states=this.updateStateListForChar(states,index);}}
const minState=Collections.min(states,(a,b)=>{return a.getBitCount()-b.getBitCount();});return minState.toBitArray(this.text);}
updateStateListForChar(states,index){const result=[];for(let state of states){this.updateStateForChar(state,index,result);}
return HighLevelEncoder$1.simplifyStates(result);}
updateStateForChar(state,index,result){let ch=(this.text[index]&0xff);let charInCurrentTable=CHAR_MAP[state.getMode()][ch]>0;let stateNoBinary=null;for(let mode=0;mode<=MODE_PUNCT;mode++){let charInMode=CHAR_MAP[mode][ch];if(charInMode>0){if(stateNoBinary==null){stateNoBinary=state.endBinaryShift(index);}
if(!charInCurrentTable||mode===state.getMode()||mode===MODE_DIGIT){const latchState=stateNoBinary.latchAndAppend(mode,charInMode);result.push(latchState);}
if(!charInCurrentTable&&SHIFT_TABLE[state.getMode()][mode]>=0){const shiftState=stateNoBinary.shiftAndAppend(mode,charInMode);result.push(shiftState);}}}
if(state.getBinaryShiftByteCount()>0||CHAR_MAP[state.getMode()][ch]===0){let binaryState=state.addBinaryShiftChar(index);result.push(binaryState);}}
static updateStateListForPair(states,index,pairCode){const result=[];for(let state of states){this.updateStateForPair(state,index,pairCode,result);}
return this.simplifyStates(result);}
static updateStateForPair(state,index,pairCode,result){let stateNoBinary=state.endBinaryShift(index);result.push(stateNoBinary.latchAndAppend(MODE_PUNCT,pairCode));if(state.getMode()!==MODE_PUNCT){result.push(stateNoBinary.shiftAndAppend(MODE_PUNCT,pairCode));}
if(pairCode===3||pairCode===4){let digitState=stateNoBinary.latchAndAppend(MODE_DIGIT,16-pairCode).latchAndAppend(MODE_DIGIT,1);result.push(digitState);}
if(state.getBinaryShiftByteCount()>0){let binaryState=state.addBinaryShiftChar(index).addBinaryShiftChar(index+1);result.push(binaryState);}}
static simplifyStates(states){let result=[];for(const newState of states){let add=true;for(const oldState of result){if(oldState.isBetterThanOrEqualTo(newState)){add=false;break;}
if(newState.isBetterThanOrEqualTo(oldState)){result=result.filter(x=>x!==oldState);}}
if(add){result.push(newState);}}
return result;}}
class Encoder$1{constructor(){}
static encodeBytes(data){return Encoder$1.encode(data,Encoder$1.DEFAULT_EC_PERCENT,Encoder$1.DEFAULT_AZTEC_LAYERS);}
static encode(data,minECCPercent,userSpecifiedLayers){let bits=new HighLevelEncoder$1(data).encode();let eccBits=Integer.truncDivision((bits.getSize()*minECCPercent),100)+11;let totalSizeBits=bits.getSize()+eccBits;let compact;let layers;let totalBitsInLayer;let wordSize;let stuffedBits;if(userSpecifiedLayers!==Encoder$1.DEFAULT_AZTEC_LAYERS){compact=userSpecifiedLayers<0;layers=Math.abs(userSpecifiedLayers);if(layers>(compact?Encoder$1.MAX_NB_BITS_COMPACT:Encoder$1.MAX_NB_BITS)){throw new IllegalArgumentException(StringUtils.format('Illegal value %s for layers',userSpecifiedLayers));}
totalBitsInLayer=Encoder$1.totalBitsInLayer(layers,compact);wordSize=Encoder$1.WORD_SIZE[layers];let usableBitsInLayers=totalBitsInLayer-(totalBitsInLayer%wordSize);stuffedBits=Encoder$1.stuffBits(bits,wordSize);if(stuffedBits.getSize()+eccBits>usableBitsInLayers){throw new IllegalArgumentException('Data to large for user specified layer');}
if(compact&&stuffedBits.getSize()>wordSize*64){throw new IllegalArgumentException('Data to large for user specified layer');}}
else{wordSize=0;stuffedBits=null;for(let i=0;;i++){if(i>Encoder$1.MAX_NB_BITS){throw new IllegalArgumentException('Data too large for an Aztec code');}
compact=i<=3;layers=compact?i+1:i;totalBitsInLayer=Encoder$1.totalBitsInLayer(layers,compact);if(totalSizeBits>totalBitsInLayer){continue;}
if(stuffedBits==null||wordSize!==Encoder$1.WORD_SIZE[layers]){wordSize=Encoder$1.WORD_SIZE[layers];stuffedBits=Encoder$1.stuffBits(bits,wordSize);}
let usableBitsInLayers=totalBitsInLayer-(totalBitsInLayer%wordSize);if(compact&&stuffedBits.getSize()>wordSize*64){continue;}
if(stuffedBits.getSize()+eccBits<=usableBitsInLayers){break;}}}
let messageBits=Encoder$1.generateCheckWords(stuffedBits,totalBitsInLayer,wordSize);let messageSizeInWords=stuffedBits.getSize()/wordSize;let modeMessage=Encoder$1.generateModeMessage(compact,layers,messageSizeInWords);let baseMatrixSize=(compact?11:14)+layers*4;let alignmentMap=new Int32Array(baseMatrixSize);let matrixSize;if(compact){matrixSize=baseMatrixSize;for(let i=0;i<alignmentMap.length;i++){alignmentMap[i]=i;}}
else{matrixSize=baseMatrixSize+1+2*Integer.truncDivision((Integer.truncDivision(baseMatrixSize,2)-1),15);let origCenter=Integer.truncDivision(baseMatrixSize,2);let center=Integer.truncDivision(matrixSize,2);for(let i=0;i<origCenter;i++){let newOffset=i+Integer.truncDivision(i,15);alignmentMap[origCenter-i-1]=center-newOffset-1;alignmentMap[origCenter+i]=center+newOffset+1;}}
let matrix=new BitMatrix(matrixSize);for(let i=0,rowOffset=0;i<layers;i++){let rowSize=(layers-i)*4+(compact?9:12);for(let j=0;j<rowSize;j++){let columnOffset=j*2;for(let k=0;k<2;k++){if(messageBits.get(rowOffset+columnOffset+k)){matrix.set(alignmentMap[i*2+k],alignmentMap[i*2+j]);}
if(messageBits.get(rowOffset+rowSize*2+columnOffset+k)){matrix.set(alignmentMap[i*2+j],alignmentMap[baseMatrixSize-1-i*2-k]);}
if(messageBits.get(rowOffset+rowSize*4+columnOffset+k)){matrix.set(alignmentMap[baseMatrixSize-1-i*2-k],alignmentMap[baseMatrixSize-1-i*2-j]);}
if(messageBits.get(rowOffset+rowSize*6+columnOffset+k)){matrix.set(alignmentMap[baseMatrixSize-1-i*2-j],alignmentMap[i*2+k]);}}}
rowOffset+=rowSize*8;}
Encoder$1.drawModeMessage(matrix,compact,matrixSize,modeMessage);if(compact){Encoder$1.drawBullsEye(matrix,Integer.truncDivision(matrixSize,2),5);}
else{Encoder$1.drawBullsEye(matrix,Integer.truncDivision(matrixSize,2),7);for(let i=0,j=0;i<Integer.truncDivision(baseMatrixSize,2)-1;i+=15,j+=16){for(let k=Integer.truncDivision(matrixSize,2)&1;k<matrixSize;k+=2){matrix.set(Integer.truncDivision(matrixSize,2)-j,k);matrix.set(Integer.truncDivision(matrixSize,2)+j,k);matrix.set(k,Integer.truncDivision(matrixSize,2)-j);matrix.set(k,Integer.truncDivision(matrixSize,2)+j);}}}
let aztec=new AztecCode();aztec.setCompact(compact);aztec.setSize(matrixSize);aztec.setLayers(layers);aztec.setCodeWords(messageSizeInWords);aztec.setMatrix(matrix);return aztec;}
static drawBullsEye(matrix,center,size){for(let i=0;i<size;i+=2){for(let j=center-i;j<=center+i;j++){matrix.set(j,center-i);matrix.set(j,center+i);matrix.set(center-i,j);matrix.set(center+i,j);}}
matrix.set(center-size,center-size);matrix.set(center-size+1,center-size);matrix.set(center-size,center-size+1);matrix.set(center+size,center-size);matrix.set(center+size,center-size+1);matrix.set(center+size,center+size-1);}
static generateModeMessage(compact,layers,messageSizeInWords){let modeMessage=new BitArray();if(compact){modeMessage.appendBits(layers-1,2);modeMessage.appendBits(messageSizeInWords-1,6);modeMessage=Encoder$1.generateCheckWords(modeMessage,28,4);}
else{modeMessage.appendBits(layers-1,5);modeMessage.appendBits(messageSizeInWords-1,11);modeMessage=Encoder$1.generateCheckWords(modeMessage,40,4);}
return modeMessage;}
static drawModeMessage(matrix,compact,matrixSize,modeMessage){let center=Integer.truncDivision(matrixSize,2);if(compact){for(let i=0;i<7;i++){let offset=center-3+i;if(modeMessage.get(i)){matrix.set(offset,center-5);}
if(modeMessage.get(i+7)){matrix.set(center+5,offset);}
if(modeMessage.get(20-i)){matrix.set(offset,center+5);}
if(modeMessage.get(27-i)){matrix.set(center-5,offset);}}}
else{for(let i=0;i<10;i++){let offset=center-5+i+Integer.truncDivision(i,5);if(modeMessage.get(i)){matrix.set(offset,center-7);}
if(modeMessage.get(i+10)){matrix.set(center+7,offset);}
if(modeMessage.get(29-i)){matrix.set(offset,center+7);}
if(modeMessage.get(39-i)){matrix.set(center-7,offset);}}}}
static generateCheckWords(bitArray,totalBits,wordSize){let messageSizeInWords=bitArray.getSize()/wordSize;let rs=new ReedSolomonEncoder(Encoder$1.getGF(wordSize));let totalWords=Integer.truncDivision(totalBits,wordSize);let messageWords=Encoder$1.bitsToWords(bitArray,wordSize,totalWords);rs.encode(messageWords,totalWords-messageSizeInWords);let startPad=totalBits%wordSize;let messageBits=new BitArray();messageBits.appendBits(0,startPad);for(const messageWord of Array.from(messageWords)){messageBits.appendBits(messageWord,wordSize);}
return messageBits;}
static bitsToWords(stuffedBits,wordSize,totalWords){let message=new Int32Array(totalWords);let i;let n;for(i=0,n=stuffedBits.getSize()/wordSize;i<n;i++){let value=0;for(let j=0;j<wordSize;j++){value|=stuffedBits.get(i*wordSize+j)?(1<<wordSize-j-1):0;}
message[i]=value;}
return message;}
static getGF(wordSize){switch(wordSize){case 4:return GenericGF.AZTEC_PARAM;case 6:return GenericGF.AZTEC_DATA_6;case 8:return GenericGF.AZTEC_DATA_8;case 10:return GenericGF.AZTEC_DATA_10;case 12:return GenericGF.AZTEC_DATA_12;default:throw new IllegalArgumentException('Unsupported word size '+wordSize);}}
static stuffBits(bits,wordSize){let out=new BitArray();let n=bits.getSize();let mask=(1<<wordSize)-2;for(let i=0;i<n;i+=wordSize){let word=0;for(let j=0;j<wordSize;j++){if(i+j>=n||bits.get(i+j)){word|=1<<(wordSize-1-j);}}
if((word&mask)===mask){out.appendBits(word&mask,wordSize);i--;}
else if((word&mask)===0){out.appendBits(word|1,wordSize);i--;}
else{out.appendBits(word,wordSize);}}
return out;}
static totalBitsInLayer(layers,compact){return((compact?88:112)+16*layers)*layers;}}
Encoder$1.DEFAULT_EC_PERCENT=33;Encoder$1.DEFAULT_AZTEC_LAYERS=0;Encoder$1.MAX_NB_BITS=32;Encoder$1.MAX_NB_BITS_COMPACT=4;Encoder$1.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 AztecWriter{encode(contents,format,width,height){return this.encodeWithHints(contents,format,width,height,null);}
encodeWithHints(contents,format,width,height,hints){let charset=StandardCharsets.ISO_8859_1;let eccPercent=Encoder$1.DEFAULT_EC_PERCENT;let layers=Encoder$1.DEFAULT_AZTEC_LAYERS;if(hints!=null){if(hints.has(EncodeHintType$1.CHARACTER_SET)){charset=Charset.forName(hints.get(EncodeHintType$1.CHARACTER_SET).toString());}
if(hints.has(EncodeHintType$1.ERROR_CORRECTION)){eccPercent=Integer.parseInt(hints.get(EncodeHintType$1.ERROR_CORRECTION).toString());}
if(hints.has(EncodeHintType$1.AZTEC_LAYERS)){layers=Integer.parseInt(hints.get(EncodeHintType$1.AZTEC_LAYERS).toString());}}
return AztecWriter.encodeLayers(contents,format,width,height,charset,eccPercent,layers);}
static encodeLayers(contents,format,width,height,charset,eccPercent,layers){if(format!==BarcodeFormat$1.AZTEC){throw new IllegalArgumentException('Can only encode AZTEC, but got '+format);}
let aztec=Encoder$1.encode(StringUtils.getBytes(contents,charset),eccPercent,layers);return AztecWriter.renderResult(aztec,width,height);}
static renderResult(code,width,height){let input=code.getMatrix();if(input==null){throw new IllegalStateException();}
let inputWidth=input.getWidth();let inputHeight=input.getHeight();let outputWidth=Math.max(width,inputWidth);let outputHeight=Math.max(height,inputHeight);let multiple=Math.min(outputWidth/inputWidth,outputHeight/inputHeight);let leftPadding=(outputWidth-(inputWidth*multiple))/2;let topPadding=(outputHeight-(inputHeight*multiple))/2;let output=new BitMatrix(outputWidth,outputHeight);for(let inputY=0,outputY=topPadding;inputY<inputHeight;inputY++,outputY+=multiple){for(let inputX=0,outputX=leftPadding;inputX<inputWidth;inputX++,outputX+=multiple){if(input.get(inputX,inputY)){output.setRegion(outputX,outputY,multiple,multiple);}}}
return output;}}
exports.AbstractExpandedDecoder=AbstractExpandedDecoder;exports.ArgumentException=ArgumentException;exports.ArithmeticException=ArithmeticException;exports.AztecCode=AztecCode;exports.AztecCodeReader=AztecReader;exports.AztecCodeWriter=AztecWriter;exports.AztecDecoder=Decoder;exports.AztecDetector=Detector;exports.AztecDetectorResult=AztecDetectorResult;exports.AztecEncoder=Encoder$1;exports.AztecHighLevelEncoder=HighLevelEncoder$1;exports.AztecPoint=Point;exports.BarcodeFormat=BarcodeFormat$1;exports.Binarizer=Binarizer;exports.BinaryBitmap=BinaryBitmap;exports.BitArray=BitArray;exports.BitMatrix=BitMatrix;exports.BitSource=BitSource;exports.BrowserAztecCodeReader=BrowserAztecCodeReader;exports.BrowserBarcodeReader=BrowserBarcodeReader;exports.BrowserCodeReader=BrowserCodeReader;exports.BrowserDatamatrixCodeReader=BrowserDatamatrixCodeReader;exports.BrowserMultiFormatReader=BrowserMultiFormatReader;exports.BrowserPDF417Reader=BrowserPDF417Reader;exports.BrowserQRCodeReader=BrowserQRCodeReader;exports.BrowserQRCodeSvgWriter=BrowserQRCodeSvgWriter;exports.CharacterSetECI=CharacterSetECI;exports.ChecksumException=ChecksumException;exports.CodaBarReader=CodaBarReader;exports.Code128Reader=Code128Reader;exports.Code39Reader=Code39Reader;exports.Code93Reader=Code93Reader;exports.DataMatrixDecodedBitStreamParser=DecodedBitStreamParser;exports.DataMatrixDefaultPlacement=DefaultPlacement;exports.DataMatrixErrorCorrection=ErrorCorrection$1;exports.DataMatrixHighLevelEncoder=HighLevelEncoder;exports.DataMatrixReader=DataMatrixReader;exports.DataMatrixSymbolInfo=SymbolInfo;exports.DataMatrixWriter=DataMatrixWriter;exports.DecodeHintType=DecodeHintType$1;exports.DecoderResult=DecoderResult;exports.DefaultGridSampler=DefaultGridSampler;exports.DetectorResult=DetectorResult;exports.EAN13Reader=EAN13Reader;exports.EncodeHintType=EncodeHintType$1;exports.Exception=Exception;exports.FormatException=FormatException;exports.GenericGF=GenericGF;exports.GenericGFPoly=GenericGFPoly;exports.GlobalHistogramBinarizer=GlobalHistogramBinarizer;exports.GridSampler=GridSampler;exports.GridSamplerInstance=GridSamplerInstance;exports.HTMLCanvasElementLuminanceSource=HTMLCanvasElementLuminanceSource;exports.HybridBinarizer=HybridBinarizer;exports.ITFReader=ITFReader;exports.IllegalArgumentException=IllegalArgumentException;exports.IllegalStateException=IllegalStateException;exports.InvertedLuminanceSource=InvertedLuminanceSource;exports.LuminanceSource=LuminanceSource;exports.MathUtils=MathUtils;exports.MultiFormatOneDReader=MultiFormatOneDReader;exports.MultiFormatReader=MultiFormatReader;exports.MultiFormatWriter=MultiFormatWriter;exports.NotFoundException=NotFoundException;exports.OneDReader=OneDReader;exports.PDF417DecodedBitStreamParser=DecodedBitStreamParser$2;exports.PDF417DecoderErrorCorrection=ErrorCorrection;exports.PDF417Reader=PDF417Reader;exports.PDF417ResultMetadata=PDF417ResultMetadata;exports.PerspectiveTransform=PerspectiveTransform;exports.PlanarYUVLuminanceSource=PlanarYUVLuminanceSource;exports.QRCodeByteMatrix=ByteMatrix;exports.QRCodeDataMask=DataMask;exports.QRCodeDecodedBitStreamParser=DecodedBitStreamParser$1;exports.QRCodeDecoderErrorCorrectionLevel=ErrorCorrectionLevel;exports.QRCodeDecoderFormatInformation=FormatInformation;exports.QRCodeEncoder=Encoder;exports.QRCodeEncoderQRCode=QRCode;exports.QRCodeMaskUtil=MaskUtil;exports.QRCodeMatrixUtil=MatrixUtil;exports.QRCodeMode=Mode$1;exports.QRCodeReader=QRCodeReader;exports.QRCodeVersion=Version$1;exports.QRCodeWriter=QRCodeWriter;exports.RGBLuminanceSource=RGBLuminanceSource;exports.RSS14Reader=RSS14Reader;exports.RSSExpandedReader=RSSExpandedReader;exports.ReaderException=ReaderException;exports.ReedSolomonDecoder=ReedSolomonDecoder;exports.ReedSolomonEncoder=ReedSolomonEncoder;exports.ReedSolomonException=ReedSolomonException;exports.Result=Result;exports.ResultMetadataType=ResultMetadataType$1;exports.ResultPoint=ResultPoint;exports.StringUtils=StringUtils;exports.UnsupportedOperationException=UnsupportedOperationException;exports.VideoInputDevice=VideoInputDevice;exports.WhiteRectangleDetector=WhiteRectangleDetector;exports.WriterException=WriterException;exports.ZXingArrays=Arrays;exports.ZXingCharset=Charset;exports.ZXingInteger=Integer;exports.ZXingStandardCharsets=StandardCharsets;exports.ZXingStringBuilder=StringBuilder;exports.ZXingStringEncoding=StringEncoding;exports.ZXingSystem=System;exports.createAbstractExpandedDecoder=createDecoder;Object.defineProperty(exports,'__esModule',{value:true});})));;

/* /frontdesk/static/src/drink_page/drink_page.js */
odoo.define('@frontdesk/drink_page/drink_page',['@web/core/registry','@odoo/owl','@web/core/network/rpc','@frontdesk/use_inactivity'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{Component}=require("@odoo/owl");const{rpc}=require("@web/core/network/rpc");const{useInactivity}=require("@frontdesk/use_inactivity");const DrinkPage=__exports.DrinkPage=class DrinkPage extends Component{static template="frontdesk.DrinkPage";static props={drinkInfo:{type:Object,optional:true},setDrink:Function,showScreen:Function,stationId:Number,theme:String,token:String,visitorId:Number,};setup(){useInactivity(()=>this.props.showScreen("EndPage"),15000);}
async _onDrinkSelect(drinkId){await rpc(`/frontdesk/${this.props.stationId}/${this.props.token}/prepare_visitor_data`,{visitor_id:this.props.visitorId,drink_ids:[drinkId],});this.props.setDrink(true);this.props.showScreen("EndPage");}}
registry.category("frontdesk_screens").add("DrinkPage",DrinkPage);return __exports;});;

/* /frontdesk/static/src/end_page/end_page.js */
odoo.define('@frontdesk/end_page/end_page',['@web/core/registry','@odoo/owl','@frontdesk/use_inactivity'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{Component,markup}=require("@odoo/owl");const{useInactivity}=require("@frontdesk/use_inactivity");const EndPage=__exports.EndPage=class EndPage extends Component{static template="frontdesk.EndPage";static props={hostData:{optional:true},isDrinkSelected:Boolean,isMobile:Boolean,onClose:Function,plannedVisitorData:{optional:true},showScreen:Function,theme:String,};setup(){if(!this.props.isMobile){useInactivity(()=>this.props.onClose(),15000);}}
get markupValue(){return markup(this.props.plannedVisitorData?.plannedVisitorMessage);}}
registry.category("frontdesk_screens").add("EndPage",EndPage);return __exports;});;

/* /frontdesk/static/src/frontdesk.js */
odoo.define('@frontdesk/frontdesk',['@web/core/network/rpc','@web/core/registry','@frontdesk/visitor_form/visitor_form','@frontdesk/welcome_page/welcome_page','@frontdesk/register_page/register_page','@frontdesk/drink_page/drink_page','@frontdesk/navbar/navbar','@frontdesk/host_page/host_page','@frontdesk/end_page/end_page','@frontdesk/quick_check_in/quick_check_in','@odoo/owl'],function(require){'use strict';let __exports={};const{rpc}=require("@web/core/network/rpc");const{registry}=require("@web/core/registry");const{VisitorForm}=require("@frontdesk/visitor_form/visitor_form");const{WelcomePage}=require("@frontdesk/welcome_page/welcome_page");const{RegisterPage}=require("@frontdesk/register_page/register_page");const{DrinkPage}=require("@frontdesk/drink_page/drink_page");const{Navbar}=require("@frontdesk/navbar/navbar");const{HostPage}=require("@frontdesk/host_page/host_page");const{EndPage}=require("@frontdesk/end_page/end_page");const{QuickCheckIn}=require("@frontdesk/quick_check_in/quick_check_in");const{Component,useState,onWillStart,markup}=require("@odoo/owl");const Frontdesk=__exports.Frontdesk=class Frontdesk extends Component{static template="frontdesk.Frontdesk";static components={WelcomePage,Navbar,VisitorForm,QuickCheckIn,HostPage,RegisterPage,DrinkPage,EndPage,};static props={id:Number,isMobile:Boolean,currentLang:String,};setup(){this.state=useState({currentComponent:!this.props.isMobile?WelcomePage:VisitorForm,plannedVisitors:[],});const urlToken=window.location.href.split("/").findLast((s)=>s);this.token=urlToken.includes("?")?urlToken.split("?")[0]:urlToken;this.frontdeskUrl=`/frontdesk/${this.props.id}/${this.token}`;onWillStart(this.onWillStart);if(this.props.isMobile){const savedComponent=sessionStorage.getItem("currentComponent");if(savedComponent){const component=registry.category("frontdesk_screens").get(savedComponent);this.state.currentComponent=component;}
window.addEventListener("beforeunload",()=>{sessionStorage.setItem("currentComponent",this.state.currentComponent.name);});}}
async onWillStart(){this.frontdeskData=await rpc(`${this.frontdeskUrl}/get_frontdesk_data`);this.station=this.frontdeskData.station[0];}
updatePlannedVisitors(){this._getPlannedVisitors();this.intervalId=setInterval(()=>this._getPlannedVisitors(),600000);}
async _getPlannedVisitors(){this.state.plannedVisitors=await rpc(`${this.frontdeskUrl}/get_planned_visitors`);}
async createVisitor(){const result=await rpc(`${this.frontdeskUrl}/prepare_visitor_data`,{name:this.visitorData.visitorName,phone:this.visitorData.visitorPhone,email:this.visitorData.visitorEmail,company:this.visitorData.visitorCompany,host_ids:this.hostData?[this.hostData.hostId]:[],});this.visitorId=result.visitor_id;}
onClose(){!this.props.isMobile?this.showScreen("WelcomePage"):this.showScreen("VisitorForm");}
onChangeLang(ev){window.location.href=window.location.pathname+`?lang=${encodeURIComponent(ev.currentTarget.value)}`;}
showScreen(name){const component=registry.category("frontdesk_screens").get(name);this.state.currentComponent=component;}
clearUpdatePlannedVisitors(){clearInterval(this.intervalId);}
resetData(){this.hostData=null;this.visitorData=null;this.plannedVisitorData=null;this.isDrinkSelected=false;}
setVisitorData(name,phone,email,company){this.visitorData={visitorName:name,visitorPhone:phone,visitorEmail:email,visitorCompany:company,};}
setHostData(host){this.hostData={hostId:host.id,hostName:host.display_name,};}
setPlannedVisitorData(plannedVisitorId,plannedVisitorMessage,plannedVisitorHosts){this.plannedVisitorData={plannedVisitorId:plannedVisitorId,plannedVisitorMessage:plannedVisitorMessage,plannedVisitorHosts:plannedVisitorHosts,};}
setDrink(boolean){this.isDrinkSelected=boolean;}
get frontdeskProps(){let props={};if(this.state.currentComponent===WelcomePage){props={showScreen:this.showScreen.bind(this),resetData:this.resetData.bind(this),onChangeLang:this.onChangeLang.bind(this),token:this.token,companyName:this.frontdeskData.company.name,stationInfo:this.station,langs:this.frontdeskData.langs.length>1?this.frontdeskData.langs:false,currentLang:this.props.currentLang,};}else if(this.state.currentComponent===VisitorForm){props={onChangeLang:this.onChangeLang.bind(this),showScreen:this.showScreen.bind(this),clearUpdatePlannedVisitors:this.clearUpdatePlannedVisitors.bind(this),setVisitorData:this.setVisitorData.bind(this),updatePlannedVisitors:this.updatePlannedVisitors.bind(this),visitorData:this.visitorData||false,isMobile:this.props.isMobile,currentComponent:this.state.currentComponent.name,isPlannedVisitors:this.state.plannedVisitors.length?true:false,stationInfo:this.station,langs:this.frontdeskData.langs.length>1?this.frontdeskData.langs:false,currentLang:this.props.currentLang,theme:this.station.theme,};}else if(this.state.currentComponent===HostPage){props={stationId:this.station.id,token:this.token,showScreen:this.showScreen.bind(this),setHostData:this.setHostData.bind(this),};}else if(this.state.currentComponent===RegisterPage){props={showScreen:this.showScreen.bind(this),onClose:this.onClose.bind(this),createVisitor:this.createVisitor.bind(this),theme:this.station.theme,isMobile:this.props.isMobile,isDrinkVisible:this.frontdeskData.drinks?.length?true:false,plannedVisitorData:this.plannedVisitorData,hostData:this.hostData,};}else if(this.state.currentComponent===DrinkPage){props={showScreen:this.showScreen.bind(this),setDrink:this.setDrink.bind(this),theme:this.station.theme,drinkInfo:this.frontdeskData.drinks,stationId:this.props.id,token:this.token,visitorId:this.plannedVisitorData?this.plannedVisitorData.plannedVisitorId:this.visitorId,};}else if(this.state.currentComponent===EndPage){props={showScreen:this.showScreen.bind(this),onClose:this.onClose.bind(this),isMobile:this.props.isMobile,isDrinkSelected:this.isDrinkSelected,theme:this.station.theme,plannedVisitorData:this.plannedVisitorData,hostData:this.hostData,};}
return props;}
get navBarProps(){return{showScreen:this.showScreen.bind(this),currentComponent:this.state.currentComponent.name,companyInfo:this.frontdeskData.company,isMobile:this.props.isMobile,isPlannedVisitors:this.state.plannedVisitors.length?true:false,theme:this.station.theme,onChangeLang:this.onChangeLang.bind(this),langs:this.frontdeskData.langs.length>1?this.frontdeskData.langs:false,currentLang:this.props.currentLang,};}
get quickCheckInProps(){return{setPlannedVisitorData:this.setPlannedVisitorData.bind(this),showScreen:this.showScreen.bind(this),stationId:this.props.id,token:this.token,plannedVisitors:this.state.plannedVisitors,theme:this.station.theme,};}
get markupValue(){return markup(this.station.description);}}
registry.category("public_components").add("frontdesk",Frontdesk);return __exports;});;

/* /frontdesk/static/src/host_page/host_page.js */
odoo.define('@frontdesk/host_page/host_page',['@web/core/registry','@odoo/owl','@frontdesk/host_page/many2one/many2one'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{Component,useRef}=require("@odoo/owl");const{Many2One}=require("@frontdesk/host_page/many2one/many2one");const HostPage=__exports.HostPage=class HostPage extends Component{static template="frontdesk.HostPage";static components={Many2One};static props={setHostData:Function,showScreen:Function,stationId:Number,token:String,};setup(){this.buttonRef=useRef("button");}
disableButton(isDisable){this.buttonRef.el.disabled=isDisable;}
_onConfirm(){this.props.setHostData(this.host);this.props.showScreen("RegisterPage");}
selectedHost(host){this.host=host;}}
registry.category("frontdesk_screens").add("HostPage",HostPage);return __exports;});;

/* /frontdesk/static/src/host_page/many2one/many2one.js */
odoo.define('@frontdesk/host_page/many2one/many2one',['@web/core/l10n/translation','@web/core/network/rpc','@web/core/autocomplete/autocomplete','@odoo/owl'],function(require){'use strict';let __exports={};const{_t}=require("@web/core/l10n/translation");const{rpc}=require("@web/core/network/rpc");const{AutoComplete}=require("@web/core/autocomplete/autocomplete");const{Component}=require("@odoo/owl");const Many2One=__exports.Many2One=class Many2One extends Component{static template="frontdesk.Many2One";static components={AutoComplete};static props={disableButton:Function,stationId:Number,token:String,update:Function,};async loadOptionsSource(request){if(this.lastProm){this.lastProm.abort(false);}
this.lastProm=this.search(request);const records=await this.lastProm;if(!records.length){this.props.disableButton(true);}
const options=records.map((result)=>this.mapRecordToOption(result));return options;}
mapRecordToOption(result){return{value:result[0],label:result[1].split("\n")[0],displayName:result[1],};}
onSelect(option,params={}){const record={id:option.value,display_name:option.displayName,};if(record){this.props.disableButton(false);}
params.input.value=option.displayName;this.props.update(record);}
search(name){return rpc(`/frontdesk/${this.props.stationId}/${this.props.token}/get_hosts`,{name:name,});}
get sources(){return[this.optionsSource];}
get optionsSource(){return{placeholder:_t("Loading..."),options:this.loadOptionsSource.bind(this),optionTemplate:"avatarAutoComplete",};}}
return __exports;});;

/* /frontdesk/static/src/js/tours/frontdesk.js */
odoo.define('@frontdesk/js/tours/frontdesk',['@web/core/l10n/translation','@web/core/registry','@web_tour/tour_service/tour_utils'],function(require){'use strict';let __exports={};const{_t}=require("@web/core/l10n/translation");const{registry}=require("@web/core/registry");const{stepUtils}=require("@web_tour/tour_service/tour_utils");registry.category("web_tour.tours").add("frontdesk_tour",{url:"/odoo",steps:()=>[stepUtils.showAppsMenuItem(),{trigger:'.o_app[data-menu-xmlid="frontdesk.frontdesk_menu_root"]',content:_t("Looking for a better way to manage your visitors? \n It begins right here."),tooltipPosition:"bottom",run:"click",},{trigger:'.dropdown-item[data-menu-xmlid="frontdesk.frontdesk_menu_visitors"]',content:_t("Here, you'll see list of all the visitors."),tooltipPosition:"bottom",run:"click",},{trigger:".o_list_button_add",content:_t("Let's add a new visitor."),tooltipPosition:"bottom",run:"click",},{trigger:".o_field_widget[name='name'] input",content:_t("Enter the visitor's name."),tooltipPosition:"bottom",run:"click",},{trigger:".o_field_widget[name='station_id'] .o_field_many2one_selection",content:_t("Select or create a station on the fly from where the visitor arrived."),tooltipPosition:"bottom",run:"click",},{trigger:".o_form_button_save",content:_t("Save the visitor."),tooltipPosition:"bottom",run:"click",},],});return __exports;});;

/* /frontdesk/static/src/navbar/navbar.js */
odoo.define('@frontdesk/navbar/navbar',['@odoo/owl'],function(require){'use strict';let __exports={};const{Component}=require("@odoo/owl");const Navbar=__exports.Navbar=class Navbar extends Component{static template="frontdesk.Navbar";static props={companyInfo:Object,currentComponent:String,isMobile:Boolean,isPlannedVisitors:Boolean,showScreen:Function,onChangeLang:Function,theme:String,langs:[Object,Boolean],currentLang:String,};}
return __exports;});;

/* /frontdesk/static/src/quick_check_in/quick_check_in.js */
odoo.define('@frontdesk/quick_check_in/quick_check_in',['@odoo/owl','@web/core/network/rpc'],function(require){'use strict';let __exports={};const{Component}=require("@odoo/owl");const{rpc}=require("@web/core/network/rpc");const QuickCheckIn=__exports.QuickCheckIn=class QuickCheckIn extends Component{static template="frontdesk.QuickCheckIn";static props={plannedVisitors:{type:Object,optional:true},setPlannedVisitorData:Function,showScreen:Function,token:String,stationId:Number,theme:String,};async _onClick(visitor){await rpc(`/frontdesk/${this.props.stationId}/${this.props.token}/prepare_visitor_data`,{visitor_id:visitor.id,});this.props.setPlannedVisitorData(visitor.id,visitor.message,visitor.host_ids);this.props.showScreen("RegisterPage");}}
return __exports;});;

/* /frontdesk/static/src/register_page/register_page.js */
odoo.define('@frontdesk/register_page/register_page',['@web/core/registry','@odoo/owl','@frontdesk/use_inactivity'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{Component,markup,onWillStart,onWillUnmount}=require("@odoo/owl");const{useInactivity}=require("@frontdesk/use_inactivity");const RegisterPage=__exports.RegisterPage=class RegisterPage extends Component{static template="frontdesk.RegisterPage";static props={createVisitor:Function,hostData:{optional:true},isDrinkVisible:Boolean,isMobile:Boolean,onClose:Function,plannedVisitorData:{optional:true},showScreen:Function,theme:String,};setup(){if(!this.props.isMobile){useInactivity(()=>this.props.onClose(),15000);}
onWillStart(async()=>{if(!this.props.plannedVisitorData){const visitorCreated=sessionStorage.getItem("visitorCreated");if(!visitorCreated){await this.props.createVisitor();if(this.props.isMobile){sessionStorage.setItem("visitorCreated","true");}}}});onWillUnmount(()=>{if(this.props.isMobile){sessionStorage.removeItem("visitorCreated");}});}
get markupValue(){return markup(this.props.plannedVisitorData.plannedVisitorMessage);}}
registry.category("frontdesk_screens").add("RegisterPage",RegisterPage);return __exports;});;

/* /frontdesk/static/src/use_inactivity.js */
odoo.define('@frontdesk/use_inactivity',['@odoo/owl'],function(require){'use strict';let __exports={};const{onMounted,onWillUnmount}=require("@odoo/owl");__exports.useInactivity=useInactivity;function useInactivity(callback,delay){let timeoutId=null;const resetTimeout=()=>{if(timeoutId){clearTimeout(timeoutId);}
timeoutId=setTimeout(callback,delay);};onMounted(()=>{resetTimeout();document.addEventListener("mousemove",resetTimeout);document.addEventListener("keydown",resetTimeout);document.addEventListener("touchstart",resetTimeout);});onWillUnmount(()=>{if(timeoutId){clearTimeout(timeoutId);}
document.removeEventListener("mousemove",resetTimeout);document.removeEventListener("keydown",resetTimeout);document.removeEventListener("touchstart",resetTimeout);});}
return __exports;});;

/* /frontdesk/static/src/visitor_form/visitor_form.js */
odoo.define('@frontdesk/visitor_form/visitor_form',['@web/core/registry','@odoo/owl'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{Component,onMounted,onWillUnmount,useRef}=require("@odoo/owl");const VisitorForm=__exports.VisitorForm=class VisitorForm extends Component{static template="frontdesk.VisitorForm";static props={clearUpdatePlannedVisitors:Function,currentComponent:String,currentLang:String,isMobile:Boolean,isPlannedVisitors:Boolean,langs:[Object,Boolean],onChangeLang:Function,setVisitorData:Function,showScreen:Function,stationInfo:Object,updatePlannedVisitors:Function,visitorData:[Object,Boolean],theme:String,};setup(){this.inputNameRef=useRef("inputName");this.inputPhoneRef=useRef("inputPhone");this.inputEmailRef=useRef("inputEmail");this.inputCompanyRef=useRef("inputCompany");this.props.updatePlannedVisitors();onMounted(()=>{this.inputNameRef.el.focus();});onWillUnmount(()=>{this.props.clearUpdatePlannedVisitors();});}
_onSubmit(){this.props.setVisitorData(this.inputNameRef.el.value,this.inputPhoneRef.el?.value||false,this.inputEmailRef.el?.value||false,this.inputCompanyRef.el?.value||false);this.props.stationInfo.host_selection?this.props.showScreen("HostPage"):this.props.showScreen("RegisterPage");}}
registry.category("frontdesk_screens").add("VisitorForm",VisitorForm);return __exports;});;

/* /frontdesk/static/src/welcome_page/welcome_page.js */
odoo.define('@frontdesk/welcome_page/welcome_page',['@web/core/registry','@web/core/network/rpc','@odoo/owl'],function(require){'use strict';let __exports={};const{registry}=require("@web/core/registry");const{rpc}=require("@web/core/network/rpc");const{Component,useState,onWillUnmount}=require("@odoo/owl");const{DateTime}=luxon;const WelcomePage=__exports.WelcomePage=class WelcomePage extends Component{static template="frontdesk.WelcomePage";static props={companyName:String,currentLang:String,langs:[Object,Boolean],onChangeLang:Function,token:String,resetData:Function,showScreen:Function,stationInfo:Object,};setup(){this.state=useState({today:this.getCurrentTime(),qrCode:false});this.timeInterval=setInterval(()=>(this.state.today=this.getCurrentTime()),1000);this.props.resetData();if(this.props.stationInfo.self_check_in){this._getQrCodeData();this.qrCodeInterval=setInterval(()=>this._getQrCodeData(),3600000);}
onWillUnmount(()=>{clearInterval(this.timeInterval);if(this.props.stationInfo.self_check_in){clearInterval(this.qrCodeInterval);}});}
getCurrentTime(){return DateTime.now().toLocaleString(DateTime.TIME_SIMPLE);}
async _getQrCodeData(){const response=await rpc(`/kiosk/${this.props.stationInfo.id}/get_tmp_code/${this.props.token}`);const token=encodeURIComponent(response[0]+response[1]);this.state.qrCode=this._makeQrCodeData(`${window.location.origin}/kiosk/${this.props.stationInfo.id}/mobile/${token}`);}
_makeQrCodeData(url){const codeWriter=new window.ZXing.BrowserQRCodeSvgWriter();const qrCodeSVG=new XMLSerializer().serializeToString(codeWriter.write(url,250,250));return"data:image/svg+xml;base64,"+window.btoa(qrCodeSVG);}}
registry.category("frontdesk_screens").add("WelcomePage",WelcomePage);return __exports;});

                    /*******************************************
                    *  Templates                               *
                    *******************************************/

                    odoo.define("frontdesk.assets_frontdesk.bundle.xml", ["@web/core/templates"], function(require) {
                        "use strict";
                        const { checkPrimaryTemplateParents, registerTemplate, registerTemplateExtension } = require("@web/core/templates");
                        /* frontdesk.assets_frontdesk */
                        registerTemplate("frontdesk.DrinkPage", `/frontdesk/static/src/drink_page/drink_page.xml`, `<t t-name="frontdesk.DrinkPage" xml:space="preserve">
        <div class="d-flex flex-column flex-grow-1 h-100">
            <h1 class="mb-0 text-center">How can we delight you?</h1>
            <div class="o_drink_container row row-cols-2 row-cols-sm-3 row-cols-md-4 g-3 my-4 overflow-auto" t-att-class="{'row-cols-lg-6': props.drinkInfo.length &gt; 4}">
                <div class="col" t-foreach="props.drinkInfo" t-as="drink" t-key="drink.id">
                    <div class="card justify-content-between h-100 cursor-pointer" t-att-class="props.theme === 'light' ? '' : 'bg-800'" t-on-click="() =&gt; this._onDrinkSelect(drink.id)">
                        <img class="card-img-top" t-attf-src="/frontdesk/{{drink.id}}/get_frontdesk_drinks" alt="Drink image"/>
                        <div class="flex-grow-0 p-3">
                            <div class="text-center fs-5" t-out="drink.name"/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-6 d-grid mx-lg-auto mt-auto">
                <button class="btn btn-secondary" t-on-click="() =&gt; props.showScreen('EndPage')">Nothing, thanks.</button>
            </div>
        </div>
    </t>
`);
registerTemplate("frontdesk.EndPage", `/frontdesk/static/src/end_page/end_page.xml`, `<t t-name="frontdesk.EndPage" xml:space="preserve">
        <div class="my-auto text-center">
            <h1 class="display-6 mb-0"><i class="fa fa-check-circle fa-3x d-block mb-3 text-success"/> Thank you for registering!</h1>
            <div class="mt-2 fs-4 text-break opacity-50">
                <t t-if="props.plannedVisitorData?.plannedVisitorMessage" t-out="markupValue"/>
                <t t-else="">
                    <t t-if="props.isDrinkSelected">Your drink is on the way. </t>
                    <t t-if="props.hostData or props.plannedVisitorData?.plannedVisitorHosts?.length">
                        <t t-if="props.hostData">
                            <t t-out="props.hostData.hostName"/>
                        </t>
                        <t t-elif="props.plannedVisitorData?.plannedVisitorHosts">
                            <t t-foreach="props.plannedVisitorData.plannedVisitorHosts" t-as="host" t-key="host.id">
                                <t t-out="host.name"/>,
                            </t>
                        </t>
                        <t t-if="props.hostData or props.plannedVisitorData?.plannedVisitorHosts"> has been informed.</t>
                    </t>
                </t>
                <t t-if="!props.isDrinkSelected and !props.hostData and !props.plannedVisitorData?.plannedVisitorHosts?.length">Please have a seat.</t>
            </div>
        </div>
        <div t-if="!props.isMobile" class="col-lg-6 d-grid mx-lg-auto">
            <button t-att-class="props.theme === 'light' ? 'bg-200' : 'bg-700'" class="btn" t-on-click="props.onClose">Close</button>
        </div>
    </t>
`);
registerTemplate("frontdesk.Frontdesk", `/frontdesk/static/src/frontdesk.xml`, `<t t-name="frontdesk.Frontdesk" xml:space="preserve">
        <div t-att-class="state.currentComponent.name === 'WelcomePage' ? '' : 'container-fluid p-0'" class="o_frontdesk_wrap d-flex">
            <WelcomePage t-if="state.currentComponent.name == 'WelcomePage'" t-props="frontdeskProps"/>
            <div t-elif="['VisitorForm', 'HostPage'].includes(state.currentComponent.name)" class="row g-0 flex-column flex-lg-row w-100">
                <div t-att-class="state.plannedVisitors.length and state.currentComponent.name === 'VisitorForm' ? 'col-lg-8' : ''" class="d-flex flex-column gap-4 p-3 p-md-4">
                    <Navbar t-props="navBarProps"/>
                    <t t-component="state.currentComponent" t-props="frontdeskProps"/>
                </div>
                <div t-if="state.plannedVisitors.length and state.currentComponent.name === 'VisitorForm'" class="col-lg-4 position-relative flex-fill">
                    <QuickCheckIn t-props="quickCheckInProps"/>
                </div>
            </div>
            <div t-else="" class="row g-0 flex-column flex-lg-row w-100">

                <div class="d-flex flex-column gap-5 justify-content-lg-between vh-100 p-3 p-md-4" t-att-class="station.description and station.description != '&lt;p&gt;&lt;br&gt;&lt;/p&gt;' ? 'col col-lg-8' : ''">
                    <t t-component="state.currentComponent" t-props="frontdeskProps"/>
                </div>
                <div t-if="station.description and station.description != '&lt;p&gt;&lt;br&gt;&lt;/p&gt;'" class="col-lg-4 position-relative flex-fill">
                    <div class="position-relative position-lg-absolute top-0 bottom-0 w-100 h-100 p-3 p-md-4 overflow-auto" t-att-class="station.theme === 'light' ? 'border bg-100' : 'bg-800'">
                        <div class="text-break" t-out="markupValue"/>
                    </div>
                </div>
            </div>
        </div>
    </t>
`);
registerTemplate("frontdesk.HostPage", `/frontdesk/static/src/host_page/host_page.xml`, `<t t-name="frontdesk.HostPage" xml:space="preserve">
        <div class="d-flex flex-column justify-content-center">
            <div class="container-fluid">
                <div class="row g-0 d-flex justify-content-center">
                    <div class="col-lg-6">
                        <form t-on-submit.prevent="_onConfirm">
                            <Many2One update.bind="selectedHost" disableButton.bind="disableButton" stationId="props.stationId" token="props.token"/>
                            <button t-ref="button" class="btn btn-primary mt-3 w-100" disabled="disabled">Confirm</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </t>
`);
registerTemplate("frontdesk.Many2One", `/frontdesk/static/src/host_page/many2one/many2one.xml`, `<t t-name="frontdesk.Many2One" xml:space="preserve">
        <div class="o_input_dropdown">
            <AutoComplete value="props.value || ''" id="props.id" placeholder="props.placeholder || 'Choose a Host'" sources="sources" onSelect.bind="onSelect" dropdown="true" autoSelect="true" autofocus="true"/>
        </div>
    </t>
    `);
registerTemplate("avatarAutoComplete", `/frontdesk/static/src/host_page/many2one/many2one.xml`, `<t t-name="avatarAutoComplete" xml:space="preserve">
        <span class="o_avatar_many2x_autocomplete o_avatar d-flex align-items-center">
            <img t-if="option.value" class="rounded me-1" t-attf-src="/web/image/hr.employee.public/{{option.value}}/avatar_128"/>
            <t t-esc="option.label"/>
        </span>
    </t>
`);
registerTemplate("frontdesk.Navbar", `/frontdesk/static/src/navbar/navbar.xml`, `<t t-name="frontdesk.Navbar" xml:space="preserve">
        <nav class="navbar align-items-start p-0">
            <div class="w-25">
                <a t-if="props.currentComponent === 'HostPage' or !props.isMobile" t-att-class="props.theme === 'light' ? 'bg-200' : 'bg-700'" class="btn btn-sm d-inline-flex align-items-center order-0" href="#" t-on-click="() =&gt; props.currentComponent === 'VisitorForm' ? props.showScreen('WelcomePage') : props.showScreen('VisitorForm')">
                    <i class="oi oi-arrow-left me-2"/>Back
                </a>
            </div>
            <div class="me-auto me-sm-0 w-50 px-3 text-center">
                <img t-attf-src="/web/image/res.company/{{ props.companyInfo.id }}/logo" alt="Company Logo" class="img-fluid o_company_logo"/>
            </div>
            <div class="align-self-end mt-3 mt-sm-0 w-100 w-sm-25">
                <select class="form-select form-select-lg ms-auto w-100" t-att-class="props.theme == 'dark' ? 'border-0 bg-800 text-white' : ' bg-white'" t-on-change="(ev) =&gt; props.onChangeLang(ev)" t-if="props.langs.length &gt; 1 and props.isMobile and props.currentComponent === 'VisitorForm'">
                    <t t-foreach="props.langs" t-as="lang" t-key="lang.code">
                        <option t-att-value="lang.code" t-att-selected="lang.code === props.currentLang ? true : undefined"><t t-out="lang.name"/></option>
                    </t>
                </select>
            </div>
            <h1 class="flex-fill mb-0 mt-4 fw-light text-center">
                <span t-if="props.currentComponent === 'VisitorForm'">Who are you?</span>
                <span t-if="props.currentComponent === 'HostPage'">Who are you visiting?</span>
            </h1>
        </nav>
    </t>
`);
registerTemplate("frontdesk.QuickCheckIn", `/frontdesk/static/src/quick_check_in/quick_check_in.xml`, `<t t-name="frontdesk.QuickCheckIn" xml:space="preserve">
        <div class="position-relative position-lg-absolute top-0 bottom-0 w-100 h-100 p-3 p-md-4 overflow-auto" t-att-class="props.theme === 'light' ? 'border bg-100' : 'bg-800'">
            <h3 class="mb-0">Quick Check In</h3>
            <div class="mt-2 text-muted">Are you one of these people?</div>
            <div class="d-flex flex-column gap-2 mt-4">
                <t t-foreach="props.plannedVisitors" t-as="visitor" t-key="visitor.id">
                    <div class="btn btn-secondary" t-on-click="() =&gt; this._onClick(visitor)" role="button">
                        <div class="visitor-card-body d-flex justify-content-between align-items-center gap-3">
                            <div class="text-start text-break">
                                <div t-out="visitor.name"/>
                                <div class="small opacity-75" t-if="visitor.company" t-out="visitor.company"/>
                            </div>
                            <i class="oi oi-arrow-right"/>
                        </div>
                    </div>
                </t>
            </div>
        </div>
    </t>
`);
registerTemplate("frontdesk.RegisterPage", `/frontdesk/static/src/register_page/register_page.xml`, `<t t-name="frontdesk.RegisterPage" xml:space="preserve">
        <div class="text-center">
            <h1 class="display-6 mb-0">You have been registered!</h1>
            <div class="mt-2 fs-5 text-break opacity-50">
                <t t-if="props.plannedVisitorData?.plannedVisitorMessage" t-out="markupValue"/>
                <t t-else="">
                    Please have a seat.
                    <t t-if="props.hostData">
                        <t t-out="props.hostData.hostName"/>
                    </t>
                    <t t-elif="props.plannedVisitorData?.plannedVisitorHosts?.length">
                        <t t-foreach="props.plannedVisitorData.plannedVisitorHosts" t-as="host" t-key="host.id">
                            <t t-out="host.name"/>,
                        </t>
                    </t>
                    <t t-if="props.hostData or props.plannedVisitorData?.plannedVisitorHosts?.length"> will get back to you.</t>
                </t>
            </div>
        </div>
        <div t-if="props.isDrinkVisible" t-att-class="props.isDrinkVisible ? 'd-flex flex-lg-fill align-items-center' : ''">
            <div class="w-100 text-center">
                <h3 class="mb-4">Do you want something to drink?</h3>
                <div class="col-lg-6 d-grid gap-3 mx-auto">
                    <button class="btn btn-primary" t-on-click="() =&gt; props.showScreen('DrinkPage')">Yes, please</button>
                    <button class="btn btn-secondary" t-on-click="() =&gt; props.showScreen('EndPage')">No, thank you</button>
                </div>
            </div>
        </div>
        <div t-if="!props.isMobile" class="col-lg-6 d-grid mx-lg-auto mt-auto">
            <button class="btn" t-att-class="props.theme === 'light' ? 'bg-200' : 'bg-700'" t-on-click="props.onClose">Close</button>
        </div>
    </t>
`);
registerTemplate("frontdesk.VisitorForm", `/frontdesk/static/src/visitor_form/visitor_form.xml`, `<t t-name="frontdesk.VisitorForm" xml:space="preserve">
        <div class="d-flex flex-column justify-content-center">
            <form class="row d-flex justify-content-center align-items-start" t-on-submit.prevent="_onSubmit">
                <div t-att-class="props.isPlannedVisitors ? 'col-xl-9' : 'col-lg-6'">
                    <div>
                        <label for="name" class="form-label">Your Name <span class="small text-danger">*</span></label>
                        <input type="text" class="form-control" t-att-class="props.theme === 'light' ? '' : 'bg-700 border-0 text-white'" id="name" t-ref="inputName" placeholder="e.g. John Doe" required="1" t-att-value="props.visitorData.visitorName"/>
                    </div>
                    <t t-if="props.stationInfo.authenticate_guest">
                        <div t-if="props.stationInfo.ask_email !== 'none'" class="mt-3">
                            <label for="email" class="form-label">Your Email <t t-if="props.stationInfo.ask_email != 'optional'"><span class="small text-danger">*</span></t></label>
                            <input type="email" class="form-control" t-att-class="props.theme === 'light' ? '' : 'bg-700 border-0 text-white'" id="email" t-ref="inputEmail" placeholder="e.g. john@company.com" t-att-required="props.stationInfo.ask_email === 'required'" t-att-value="props.visitorData.visitorEmail"/>
                        </div>
                        <div t-if="props.stationInfo.ask_phone !== 'none'" class="mt-3">
                            <label for="phone" class="form-label">Your Phone Number <t t-if="props.stationInfo.ask_phone != 'optional'"><span class="small text-danger">*</span></t></label>
                            <input type="phone" class="form-control" t-att-class="props.theme === 'light' ? '' : 'bg-700 border-0 text-white'" id="phone" t-ref="inputPhone" t-att-required="props.stationInfo.ask_phone === 'required'" t-att-value="props.visitorData.visitorPhone"/>
                        </div>
                        <div t-if="props.stationInfo.ask_company !== 'none'" class="mt-3">
                            <label for="company" class="form-label">Your Company <t t-if="props.stationInfo.ask_company != 'optional'"><span class="small text-danger">*</span></t></label>
                            <input type="text" class="form-control" t-att-class="props.theme === 'light' ? '' : 'bg-700 border-0 text-white'" id="company" t-ref="inputCompany" placeholder="e.g. My Company" t-att-required="props.stationInfo.ask_company === 'required'" t-att-value="props.visitorData.visitorCompany"/>
                        </div>
                    </t>
                    <button type="submit" class="btn btn-primary mt-4 w-100">Check In</button>
                </div>
            </form>
        </div>
    </t>
`);
registerTemplate("frontdesk.WelcomePage", `/frontdesk/static/src/welcome_page/welcome_page.xml`, `<t t-name="frontdesk.WelcomePage" xml:space="preserve">
        <div class="position-relative d-flex flex-column flex-lg-row justify-content-center w-100 o_main_bg_img" t-att-style="'background-image: url(/frontdesk/' + props.stationInfo.id + '/background), url(/frontdesk/static/img/frontdesk.svg'">
            <div class="position-relative d-flex flex-column align-items-center justify-content-center h-lg-100 p-4 pb-5 pb-lg-4 text-center">
                <div class="display-2 m-0 fw-bold">
                    Welcome to
                    <div class="fs-1 fw-light" t-out="props.companyName"/>
                </div>
                <div class="btn btn-lg btn-primary mt-4" t-on-click="() =&gt; props.showScreen('VisitorForm')">Check in</div>
            </div>
            <div class="position-lg-absolute start-0 end-0 top-0 bottom-0 d-flex gap-3 flex-column justify-content-between align-items-center align-items-lg-stretch p-4 pe-none">
                <div t-if="props.langs">
                    <div class="d-flex justify-content-center justify-content-lg-end">
                        <select class="form-select w-auto pe-auto" t-att-class="props.stationInfo.theme == 'dark' ? 'border-0 bg-800 text-white' : ' bg-white'" t-on-change="(ev) =&gt; props.onChangeLang(ev)">
                            <t t-foreach="props.langs" t-as="lang" t-key="lang.code">
                                <option t-att-value="lang.code" t-att-selected="lang.code === props.currentLang ? true : undefined"><t t-out="lang.name"/></option>
                            </t>
                        </select>
                    </div>
                </div>
                <div class="d-flex flex-column flex-lg-row justify-content-center justify-content-lg-between align-items-center align-items-lg-end gap-5 mt-auto">
                    <div class="display-5" t-out="state.today"/>
                    <img t-if="props.stationInfo.self_check_in" class="rounded p-2 bg-white o_qrcode" t-att-src="state.qrCode" alt="QR Code"/>
                </div>
            </div>
        </div>
    </t>
`);
                    });
