vue-qrcode.esm.js 149 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501
  1. /*!
  2. * vue-qrcode v1.0.2
  3. * https://fengyuanchen.github.io/vue-qrcode
  4. *
  5. * Copyright 2018-present Chen Fengyuan
  6. * Released under the MIT license
  7. *
  8. * Date: 2020-01-18T06:04:33.222Z
  9. */
  10. function commonjsRequire () {
  11. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  12. }
  13. function createCommonjsModule(fn, module) {
  14. return module = { exports: {} }, fn(module, module.exports), module.exports;
  15. }
  16. var qrcode = createCommonjsModule(function (module, exports) {
  17. (function(f){{module.exports=f();}})(function(){return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof commonjsRequire&&commonjsRequire;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t);}return n[i].exports}for(var u="function"==typeof commonjsRequire&&commonjsRequire,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  18. // can-promise has a crash in some versions of react native that dont have
  19. // standard global objects
  20. // https://github.com/soldair/node-qrcode/issues/157
  21. module.exports = function () {
  22. return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
  23. };
  24. },{}],2:[function(require,module,exports){
  25. /**
  26. * Alignment pattern are fixed reference pattern in defined positions
  27. * in a matrix symbology, which enables the decode software to re-synchronise
  28. * the coordinate mapping of the image modules in the event of moderate amounts
  29. * of distortion of the image.
  30. *
  31. * Alignment patterns are present only in QR Code symbols of version 2 or larger
  32. * and their number depends on the symbol version.
  33. */
  34. var getSymbolSize = require('./utils').getSymbolSize;
  35. /**
  36. * Calculate the row/column coordinates of the center module of each alignment pattern
  37. * for the specified QR Code version.
  38. *
  39. * The alignment patterns are positioned symmetrically on either side of the diagonal
  40. * running from the top left corner of the symbol to the bottom right corner.
  41. *
  42. * Since positions are simmetrical only half of the coordinates are returned.
  43. * Each item of the array will represent in turn the x and y coordinate.
  44. * @see {@link getPositions}
  45. *
  46. * @param {Number} version QR Code version
  47. * @return {Array} Array of coordinate
  48. */
  49. exports.getRowColCoords = function getRowColCoords (version) {
  50. if (version === 1) return []
  51. var posCount = Math.floor(version / 7) + 2;
  52. var size = getSymbolSize(version);
  53. var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
  54. var positions = [size - 7]; // Last coord is always (size - 7)
  55. for (var i = 1; i < posCount - 1; i++) {
  56. positions[i] = positions[i - 1] - intervals;
  57. }
  58. positions.push(6); // First coord is always 6
  59. return positions.reverse()
  60. };
  61. /**
  62. * Returns an array containing the positions of each alignment pattern.
  63. * Each array's element represent the center point of the pattern as (x, y) coordinates
  64. *
  65. * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
  66. * and filtering out the items that overlaps with finder pattern
  67. *
  68. * @example
  69. * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
  70. * The alignment patterns, therefore, are to be centered on (row, column)
  71. * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
  72. * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
  73. * and are not therefore used for alignment patterns.
  74. *
  75. * var pos = getPositions(7)
  76. * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
  77. *
  78. * @param {Number} version QR Code version
  79. * @return {Array} Array of coordinates
  80. */
  81. exports.getPositions = function getPositions (version) {
  82. var coords = [];
  83. var pos = exports.getRowColCoords(version);
  84. var posLength = pos.length;
  85. for (var i = 0; i < posLength; i++) {
  86. for (var j = 0; j < posLength; j++) {
  87. // Skip if position is occupied by finder patterns
  88. if ((i === 0 && j === 0) || // top-left
  89. (i === 0 && j === posLength - 1) || // bottom-left
  90. (i === posLength - 1 && j === 0)) { // top-right
  91. continue
  92. }
  93. coords.push([pos[i], pos[j]]);
  94. }
  95. }
  96. return coords
  97. };
  98. },{"./utils":21}],3:[function(require,module,exports){
  99. var Mode = require('./mode');
  100. /**
  101. * Array of characters available in alphanumeric mode
  102. *
  103. * As per QR Code specification, to each character
  104. * is assigned a value from 0 to 44 which in this case coincides
  105. * with the array index
  106. *
  107. * @type {Array}
  108. */
  109. var ALPHA_NUM_CHARS = [
  110. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  111. 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
  112. 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  113. ' ', '$', '%', '*', '+', '-', '.', '/', ':'
  114. ];
  115. function AlphanumericData (data) {
  116. this.mode = Mode.ALPHANUMERIC;
  117. this.data = data;
  118. }
  119. AlphanumericData.getBitsLength = function getBitsLength (length) {
  120. return 11 * Math.floor(length / 2) + 6 * (length % 2)
  121. };
  122. AlphanumericData.prototype.getLength = function getLength () {
  123. return this.data.length
  124. };
  125. AlphanumericData.prototype.getBitsLength = function getBitsLength () {
  126. return AlphanumericData.getBitsLength(this.data.length)
  127. };
  128. AlphanumericData.prototype.write = function write (bitBuffer) {
  129. var i;
  130. // Input data characters are divided into groups of two characters
  131. // and encoded as 11-bit binary codes.
  132. for (i = 0; i + 2 <= this.data.length; i += 2) {
  133. // The character value of the first character is multiplied by 45
  134. var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
  135. // The character value of the second digit is added to the product
  136. value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
  137. // The sum is then stored as 11-bit binary number
  138. bitBuffer.put(value, 11);
  139. }
  140. // If the number of input data characters is not a multiple of two,
  141. // the character value of the final character is encoded as a 6-bit binary number.
  142. if (this.data.length % 2) {
  143. bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
  144. }
  145. };
  146. module.exports = AlphanumericData;
  147. },{"./mode":14}],4:[function(require,module,exports){
  148. function BitBuffer () {
  149. this.buffer = [];
  150. this.length = 0;
  151. }
  152. BitBuffer.prototype = {
  153. get: function (index) {
  154. var bufIndex = Math.floor(index / 8);
  155. return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
  156. },
  157. put: function (num, length) {
  158. for (var i = 0; i < length; i++) {
  159. this.putBit(((num >>> (length - i - 1)) & 1) === 1);
  160. }
  161. },
  162. getLengthInBits: function () {
  163. return this.length
  164. },
  165. putBit: function (bit) {
  166. var bufIndex = Math.floor(this.length / 8);
  167. if (this.buffer.length <= bufIndex) {
  168. this.buffer.push(0);
  169. }
  170. if (bit) {
  171. this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
  172. }
  173. this.length++;
  174. }
  175. };
  176. module.exports = BitBuffer;
  177. },{}],5:[function(require,module,exports){
  178. var BufferUtil = require('../utils/buffer');
  179. /**
  180. * Helper class to handle QR Code symbol modules
  181. *
  182. * @param {Number} size Symbol size
  183. */
  184. function BitMatrix (size) {
  185. if (!size || size < 1) {
  186. throw new Error('BitMatrix size must be defined and greater than 0')
  187. }
  188. this.size = size;
  189. this.data = BufferUtil.alloc(size * size);
  190. this.reservedBit = BufferUtil.alloc(size * size);
  191. }
  192. /**
  193. * Set bit value at specified location
  194. * If reserved flag is set, this bit will be ignored during masking process
  195. *
  196. * @param {Number} row
  197. * @param {Number} col
  198. * @param {Boolean} value
  199. * @param {Boolean} reserved
  200. */
  201. BitMatrix.prototype.set = function (row, col, value, reserved) {
  202. var index = row * this.size + col;
  203. this.data[index] = value;
  204. if (reserved) this.reservedBit[index] = true;
  205. };
  206. /**
  207. * Returns bit value at specified location
  208. *
  209. * @param {Number} row
  210. * @param {Number} col
  211. * @return {Boolean}
  212. */
  213. BitMatrix.prototype.get = function (row, col) {
  214. return this.data[row * this.size + col]
  215. };
  216. /**
  217. * Applies xor operator at specified location
  218. * (used during masking process)
  219. *
  220. * @param {Number} row
  221. * @param {Number} col
  222. * @param {Boolean} value
  223. */
  224. BitMatrix.prototype.xor = function (row, col, value) {
  225. this.data[row * this.size + col] ^= value;
  226. };
  227. /**
  228. * Check if bit at specified location is reserved
  229. *
  230. * @param {Number} row
  231. * @param {Number} col
  232. * @return {Boolean}
  233. */
  234. BitMatrix.prototype.isReserved = function (row, col) {
  235. return this.reservedBit[row * this.size + col]
  236. };
  237. module.exports = BitMatrix;
  238. },{"../utils/buffer":28}],6:[function(require,module,exports){
  239. var BufferUtil = require('../utils/buffer');
  240. var Mode = require('./mode');
  241. function ByteData (data) {
  242. this.mode = Mode.BYTE;
  243. this.data = BufferUtil.from(data);
  244. }
  245. ByteData.getBitsLength = function getBitsLength (length) {
  246. return length * 8
  247. };
  248. ByteData.prototype.getLength = function getLength () {
  249. return this.data.length
  250. };
  251. ByteData.prototype.getBitsLength = function getBitsLength () {
  252. return ByteData.getBitsLength(this.data.length)
  253. };
  254. ByteData.prototype.write = function (bitBuffer) {
  255. for (var i = 0, l = this.data.length; i < l; i++) {
  256. bitBuffer.put(this.data[i], 8);
  257. }
  258. };
  259. module.exports = ByteData;
  260. },{"../utils/buffer":28,"./mode":14}],7:[function(require,module,exports){
  261. var ECLevel = require('./error-correction-level');
  262. var EC_BLOCKS_TABLE = [
  263. // L M Q H
  264. 1, 1, 1, 1,
  265. 1, 1, 1, 1,
  266. 1, 1, 2, 2,
  267. 1, 2, 2, 4,
  268. 1, 2, 4, 4,
  269. 2, 4, 4, 4,
  270. 2, 4, 6, 5,
  271. 2, 4, 6, 6,
  272. 2, 5, 8, 8,
  273. 4, 5, 8, 8,
  274. 4, 5, 8, 11,
  275. 4, 8, 10, 11,
  276. 4, 9, 12, 16,
  277. 4, 9, 16, 16,
  278. 6, 10, 12, 18,
  279. 6, 10, 17, 16,
  280. 6, 11, 16, 19,
  281. 6, 13, 18, 21,
  282. 7, 14, 21, 25,
  283. 8, 16, 20, 25,
  284. 8, 17, 23, 25,
  285. 9, 17, 23, 34,
  286. 9, 18, 25, 30,
  287. 10, 20, 27, 32,
  288. 12, 21, 29, 35,
  289. 12, 23, 34, 37,
  290. 12, 25, 34, 40,
  291. 13, 26, 35, 42,
  292. 14, 28, 38, 45,
  293. 15, 29, 40, 48,
  294. 16, 31, 43, 51,
  295. 17, 33, 45, 54,
  296. 18, 35, 48, 57,
  297. 19, 37, 51, 60,
  298. 19, 38, 53, 63,
  299. 20, 40, 56, 66,
  300. 21, 43, 59, 70,
  301. 22, 45, 62, 74,
  302. 24, 47, 65, 77,
  303. 25, 49, 68, 81
  304. ];
  305. var EC_CODEWORDS_TABLE = [
  306. // L M Q H
  307. 7, 10, 13, 17,
  308. 10, 16, 22, 28,
  309. 15, 26, 36, 44,
  310. 20, 36, 52, 64,
  311. 26, 48, 72, 88,
  312. 36, 64, 96, 112,
  313. 40, 72, 108, 130,
  314. 48, 88, 132, 156,
  315. 60, 110, 160, 192,
  316. 72, 130, 192, 224,
  317. 80, 150, 224, 264,
  318. 96, 176, 260, 308,
  319. 104, 198, 288, 352,
  320. 120, 216, 320, 384,
  321. 132, 240, 360, 432,
  322. 144, 280, 408, 480,
  323. 168, 308, 448, 532,
  324. 180, 338, 504, 588,
  325. 196, 364, 546, 650,
  326. 224, 416, 600, 700,
  327. 224, 442, 644, 750,
  328. 252, 476, 690, 816,
  329. 270, 504, 750, 900,
  330. 300, 560, 810, 960,
  331. 312, 588, 870, 1050,
  332. 336, 644, 952, 1110,
  333. 360, 700, 1020, 1200,
  334. 390, 728, 1050, 1260,
  335. 420, 784, 1140, 1350,
  336. 450, 812, 1200, 1440,
  337. 480, 868, 1290, 1530,
  338. 510, 924, 1350, 1620,
  339. 540, 980, 1440, 1710,
  340. 570, 1036, 1530, 1800,
  341. 570, 1064, 1590, 1890,
  342. 600, 1120, 1680, 1980,
  343. 630, 1204, 1770, 2100,
  344. 660, 1260, 1860, 2220,
  345. 720, 1316, 1950, 2310,
  346. 750, 1372, 2040, 2430
  347. ];
  348. /**
  349. * Returns the number of error correction block that the QR Code should contain
  350. * for the specified version and error correction level.
  351. *
  352. * @param {Number} version QR Code version
  353. * @param {Number} errorCorrectionLevel Error correction level
  354. * @return {Number} Number of error correction blocks
  355. */
  356. exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
  357. switch (errorCorrectionLevel) {
  358. case ECLevel.L:
  359. return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
  360. case ECLevel.M:
  361. return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
  362. case ECLevel.Q:
  363. return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
  364. case ECLevel.H:
  365. return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
  366. default:
  367. return undefined
  368. }
  369. };
  370. /**
  371. * Returns the number of error correction codewords to use for the specified
  372. * version and error correction level.
  373. *
  374. * @param {Number} version QR Code version
  375. * @param {Number} errorCorrectionLevel Error correction level
  376. * @return {Number} Number of error correction codewords
  377. */
  378. exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
  379. switch (errorCorrectionLevel) {
  380. case ECLevel.L:
  381. return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
  382. case ECLevel.M:
  383. return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
  384. case ECLevel.Q:
  385. return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
  386. case ECLevel.H:
  387. return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
  388. default:
  389. return undefined
  390. }
  391. };
  392. },{"./error-correction-level":8}],8:[function(require,module,exports){
  393. exports.L = { bit: 1 };
  394. exports.M = { bit: 0 };
  395. exports.Q = { bit: 3 };
  396. exports.H = { bit: 2 };
  397. function fromString (string) {
  398. if (typeof string !== 'string') {
  399. throw new Error('Param is not a string')
  400. }
  401. var lcStr = string.toLowerCase();
  402. switch (lcStr) {
  403. case 'l':
  404. case 'low':
  405. return exports.L
  406. case 'm':
  407. case 'medium':
  408. return exports.M
  409. case 'q':
  410. case 'quartile':
  411. return exports.Q
  412. case 'h':
  413. case 'high':
  414. return exports.H
  415. default:
  416. throw new Error('Unknown EC Level: ' + string)
  417. }
  418. }
  419. exports.isValid = function isValid (level) {
  420. return level && typeof level.bit !== 'undefined' &&
  421. level.bit >= 0 && level.bit < 4
  422. };
  423. exports.from = function from (value, defaultValue) {
  424. if (exports.isValid(value)) {
  425. return value
  426. }
  427. try {
  428. return fromString(value)
  429. } catch (e) {
  430. return defaultValue
  431. }
  432. };
  433. },{}],9:[function(require,module,exports){
  434. var getSymbolSize = require('./utils').getSymbolSize;
  435. var FINDER_PATTERN_SIZE = 7;
  436. /**
  437. * Returns an array containing the positions of each finder pattern.
  438. * Each array's element represent the top-left point of the pattern as (x, y) coordinates
  439. *
  440. * @param {Number} version QR Code version
  441. * @return {Array} Array of coordinates
  442. */
  443. exports.getPositions = function getPositions (version) {
  444. var size = getSymbolSize(version);
  445. return [
  446. // top-left
  447. [0, 0],
  448. // top-right
  449. [size - FINDER_PATTERN_SIZE, 0],
  450. // bottom-left
  451. [0, size - FINDER_PATTERN_SIZE]
  452. ]
  453. };
  454. },{"./utils":21}],10:[function(require,module,exports){
  455. var Utils = require('./utils');
  456. var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
  457. var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
  458. var G15_BCH = Utils.getBCHDigit(G15);
  459. /**
  460. * Returns format information with relative error correction bits
  461. *
  462. * The format information is a 15-bit sequence containing 5 data bits,
  463. * with 10 error correction bits calculated using the (15, 5) BCH code.
  464. *
  465. * @param {Number} errorCorrectionLevel Error correction level
  466. * @param {Number} mask Mask pattern
  467. * @return {Number} Encoded format information bits
  468. */
  469. exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
  470. var data = ((errorCorrectionLevel.bit << 3) | mask);
  471. var d = data << 10;
  472. while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
  473. d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH));
  474. }
  475. // xor final data with mask pattern in order to ensure that
  476. // no combination of Error Correction Level and data mask pattern
  477. // will result in an all-zero data string
  478. return ((data << 10) | d) ^ G15_MASK
  479. };
  480. },{"./utils":21}],11:[function(require,module,exports){
  481. var BufferUtil = require('../utils/buffer');
  482. var EXP_TABLE = BufferUtil.alloc(512);
  483. var LOG_TABLE = BufferUtil.alloc(256)
  484. /**
  485. * Precompute the log and anti-log tables for faster computation later
  486. *
  487. * For each possible value in the galois field 2^8, we will pre-compute
  488. * the logarithm and anti-logarithm (exponential) of this value
  489. *
  490. * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
  491. */
  492. ;(function initTables () {
  493. var x = 1;
  494. for (var i = 0; i < 255; i++) {
  495. EXP_TABLE[i] = x;
  496. LOG_TABLE[x] = i;
  497. x <<= 1; // multiply by 2
  498. // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
  499. // This means that when a number is 256 or larger, it should be XORed with 0x11D.
  500. if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
  501. x ^= 0x11D;
  502. }
  503. }
  504. // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
  505. // stay inside the bounds (because we will mainly use this table for the multiplication of
  506. // two GF numbers, no more).
  507. // @see {@link mul}
  508. for (i = 255; i < 512; i++) {
  509. EXP_TABLE[i] = EXP_TABLE[i - 255];
  510. }
  511. }());
  512. /**
  513. * Returns log value of n inside Galois Field
  514. *
  515. * @param {Number} n
  516. * @return {Number}
  517. */
  518. exports.log = function log (n) {
  519. if (n < 1) throw new Error('log(' + n + ')')
  520. return LOG_TABLE[n]
  521. };
  522. /**
  523. * Returns anti-log value of n inside Galois Field
  524. *
  525. * @param {Number} n
  526. * @return {Number}
  527. */
  528. exports.exp = function exp (n) {
  529. return EXP_TABLE[n]
  530. };
  531. /**
  532. * Multiplies two number inside Galois Field
  533. *
  534. * @param {Number} x
  535. * @param {Number} y
  536. * @return {Number}
  537. */
  538. exports.mul = function mul (x, y) {
  539. if (x === 0 || y === 0) return 0
  540. // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
  541. // @see {@link initTables}
  542. return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
  543. };
  544. },{"../utils/buffer":28}],12:[function(require,module,exports){
  545. var Mode = require('./mode');
  546. var Utils = require('./utils');
  547. function KanjiData (data) {
  548. this.mode = Mode.KANJI;
  549. this.data = data;
  550. }
  551. KanjiData.getBitsLength = function getBitsLength (length) {
  552. return length * 13
  553. };
  554. KanjiData.prototype.getLength = function getLength () {
  555. return this.data.length
  556. };
  557. KanjiData.prototype.getBitsLength = function getBitsLength () {
  558. return KanjiData.getBitsLength(this.data.length)
  559. };
  560. KanjiData.prototype.write = function (bitBuffer) {
  561. var i;
  562. // In the Shift JIS system, Kanji characters are represented by a two byte combination.
  563. // These byte values are shifted from the JIS X 0208 values.
  564. // JIS X 0208 gives details of the shift coded representation.
  565. for (i = 0; i < this.data.length; i++) {
  566. var value = Utils.toSJIS(this.data[i]);
  567. // For characters with Shift JIS values from 0x8140 to 0x9FFC:
  568. if (value >= 0x8140 && value <= 0x9FFC) {
  569. // Subtract 0x8140 from Shift JIS value
  570. value -= 0x8140;
  571. // For characters with Shift JIS values from 0xE040 to 0xEBBF
  572. } else if (value >= 0xE040 && value <= 0xEBBF) {
  573. // Subtract 0xC140 from Shift JIS value
  574. value -= 0xC140;
  575. } else {
  576. throw new Error(
  577. 'Invalid SJIS character: ' + this.data[i] + '\n' +
  578. 'Make sure your charset is UTF-8')
  579. }
  580. // Multiply most significant byte of result by 0xC0
  581. // and add least significant byte to product
  582. value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
  583. // Convert result to a 13-bit binary string
  584. bitBuffer.put(value, 13);
  585. }
  586. };
  587. module.exports = KanjiData;
  588. },{"./mode":14,"./utils":21}],13:[function(require,module,exports){
  589. /**
  590. * Data mask pattern reference
  591. * @type {Object}
  592. */
  593. exports.Patterns = {
  594. PATTERN000: 0,
  595. PATTERN001: 1,
  596. PATTERN010: 2,
  597. PATTERN011: 3,
  598. PATTERN100: 4,
  599. PATTERN101: 5,
  600. PATTERN110: 6,
  601. PATTERN111: 7
  602. };
  603. /**
  604. * Weighted penalty scores for the undesirable features
  605. * @type {Object}
  606. */
  607. var PenaltyScores = {
  608. N1: 3,
  609. N2: 3,
  610. N3: 40,
  611. N4: 10
  612. };
  613. /**
  614. * Check if mask pattern value is valid
  615. *
  616. * @param {Number} mask Mask pattern
  617. * @return {Boolean} true if valid, false otherwise
  618. */
  619. exports.isValid = function isValid (mask) {
  620. return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
  621. };
  622. /**
  623. * Returns mask pattern from a value.
  624. * If value is not valid, returns undefined
  625. *
  626. * @param {Number|String} value Mask pattern value
  627. * @return {Number} Valid mask pattern or undefined
  628. */
  629. exports.from = function from (value) {
  630. return exports.isValid(value) ? parseInt(value, 10) : undefined
  631. };
  632. /**
  633. * Find adjacent modules in row/column with the same color
  634. * and assign a penalty value.
  635. *
  636. * Points: N1 + i
  637. * i is the amount by which the number of adjacent modules of the same color exceeds 5
  638. */
  639. exports.getPenaltyN1 = function getPenaltyN1 (data) {
  640. var size = data.size;
  641. var points = 0;
  642. var sameCountCol = 0;
  643. var sameCountRow = 0;
  644. var lastCol = null;
  645. var lastRow = null;
  646. for (var row = 0; row < size; row++) {
  647. sameCountCol = sameCountRow = 0;
  648. lastCol = lastRow = null;
  649. for (var col = 0; col < size; col++) {
  650. var module = data.get(row, col);
  651. if (module === lastCol) {
  652. sameCountCol++;
  653. } else {
  654. if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
  655. lastCol = module;
  656. sameCountCol = 1;
  657. }
  658. module = data.get(col, row);
  659. if (module === lastRow) {
  660. sameCountRow++;
  661. } else {
  662. if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
  663. lastRow = module;
  664. sameCountRow = 1;
  665. }
  666. }
  667. if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
  668. if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
  669. }
  670. return points
  671. };
  672. /**
  673. * Find 2x2 blocks with the same color and assign a penalty value
  674. *
  675. * Points: N2 * (m - 1) * (n - 1)
  676. */
  677. exports.getPenaltyN2 = function getPenaltyN2 (data) {
  678. var size = data.size;
  679. var points = 0;
  680. for (var row = 0; row < size - 1; row++) {
  681. for (var col = 0; col < size - 1; col++) {
  682. var last = data.get(row, col) +
  683. data.get(row, col + 1) +
  684. data.get(row + 1, col) +
  685. data.get(row + 1, col + 1);
  686. if (last === 4 || last === 0) points++;
  687. }
  688. }
  689. return points * PenaltyScores.N2
  690. };
  691. /**
  692. * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
  693. * preceded or followed by light area 4 modules wide
  694. *
  695. * Points: N3 * number of pattern found
  696. */
  697. exports.getPenaltyN3 = function getPenaltyN3 (data) {
  698. var size = data.size;
  699. var points = 0;
  700. var bitsCol = 0;
  701. var bitsRow = 0;
  702. for (var row = 0; row < size; row++) {
  703. bitsCol = bitsRow = 0;
  704. for (var col = 0; col < size; col++) {
  705. bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
  706. if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
  707. bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
  708. if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
  709. }
  710. }
  711. return points * PenaltyScores.N3
  712. };
  713. /**
  714. * Calculate proportion of dark modules in entire symbol
  715. *
  716. * Points: N4 * k
  717. *
  718. * k is the rating of the deviation of the proportion of dark modules
  719. * in the symbol from 50% in steps of 5%
  720. */
  721. exports.getPenaltyN4 = function getPenaltyN4 (data) {
  722. var darkCount = 0;
  723. var modulesCount = data.data.length;
  724. for (var i = 0; i < modulesCount; i++) darkCount += data.data[i];
  725. var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
  726. return k * PenaltyScores.N4
  727. };
  728. /**
  729. * Return mask value at given position
  730. *
  731. * @param {Number} maskPattern Pattern reference value
  732. * @param {Number} i Row
  733. * @param {Number} j Column
  734. * @return {Boolean} Mask value
  735. */
  736. function getMaskAt (maskPattern, i, j) {
  737. switch (maskPattern) {
  738. case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
  739. case exports.Patterns.PATTERN001: return i % 2 === 0
  740. case exports.Patterns.PATTERN010: return j % 3 === 0
  741. case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
  742. case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
  743. case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
  744. case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
  745. case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
  746. default: throw new Error('bad maskPattern:' + maskPattern)
  747. }
  748. }
  749. /**
  750. * Apply a mask pattern to a BitMatrix
  751. *
  752. * @param {Number} pattern Pattern reference number
  753. * @param {BitMatrix} data BitMatrix data
  754. */
  755. exports.applyMask = function applyMask (pattern, data) {
  756. var size = data.size;
  757. for (var col = 0; col < size; col++) {
  758. for (var row = 0; row < size; row++) {
  759. if (data.isReserved(row, col)) continue
  760. data.xor(row, col, getMaskAt(pattern, row, col));
  761. }
  762. }
  763. };
  764. /**
  765. * Returns the best mask pattern for data
  766. *
  767. * @param {BitMatrix} data
  768. * @return {Number} Mask pattern reference number
  769. */
  770. exports.getBestMask = function getBestMask (data, setupFormatFunc) {
  771. var numPatterns = Object.keys(exports.Patterns).length;
  772. var bestPattern = 0;
  773. var lowerPenalty = Infinity;
  774. for (var p = 0; p < numPatterns; p++) {
  775. setupFormatFunc(p);
  776. exports.applyMask(p, data);
  777. // Calculate penalty
  778. var penalty =
  779. exports.getPenaltyN1(data) +
  780. exports.getPenaltyN2(data) +
  781. exports.getPenaltyN3(data) +
  782. exports.getPenaltyN4(data);
  783. // Undo previously applied mask
  784. exports.applyMask(p, data);
  785. if (penalty < lowerPenalty) {
  786. lowerPenalty = penalty;
  787. bestPattern = p;
  788. }
  789. }
  790. return bestPattern
  791. };
  792. },{}],14:[function(require,module,exports){
  793. var VersionCheck = require('./version-check');
  794. var Regex = require('./regex');
  795. /**
  796. * Numeric mode encodes data from the decimal digit set (0 - 9)
  797. * (byte values 30HEX to 39HEX).
  798. * Normally, 3 data characters are represented by 10 bits.
  799. *
  800. * @type {Object}
  801. */
  802. exports.NUMERIC = {
  803. id: 'Numeric',
  804. bit: 1 << 0,
  805. ccBits: [10, 12, 14]
  806. };
  807. /**
  808. * Alphanumeric mode encodes data from a set of 45 characters,
  809. * i.e. 10 numeric digits (0 - 9),
  810. * 26 alphabetic characters (A - Z),
  811. * and 9 symbols (SP, $, %, *, +, -, ., /, :).
  812. * Normally, two input characters are represented by 11 bits.
  813. *
  814. * @type {Object}
  815. */
  816. exports.ALPHANUMERIC = {
  817. id: 'Alphanumeric',
  818. bit: 1 << 1,
  819. ccBits: [9, 11, 13]
  820. };
  821. /**
  822. * In byte mode, data is encoded at 8 bits per character.
  823. *
  824. * @type {Object}
  825. */
  826. exports.BYTE = {
  827. id: 'Byte',
  828. bit: 1 << 2,
  829. ccBits: [8, 16, 16]
  830. };
  831. /**
  832. * The Kanji mode efficiently encodes Kanji characters in accordance with
  833. * the Shift JIS system based on JIS X 0208.
  834. * The Shift JIS values are shifted from the JIS X 0208 values.
  835. * JIS X 0208 gives details of the shift coded representation.
  836. * Each two-byte character value is compacted to a 13-bit binary codeword.
  837. *
  838. * @type {Object}
  839. */
  840. exports.KANJI = {
  841. id: 'Kanji',
  842. bit: 1 << 3,
  843. ccBits: [8, 10, 12]
  844. };
  845. /**
  846. * Mixed mode will contain a sequences of data in a combination of any of
  847. * the modes described above
  848. *
  849. * @type {Object}
  850. */
  851. exports.MIXED = {
  852. bit: -1
  853. };
  854. /**
  855. * Returns the number of bits needed to store the data length
  856. * according to QR Code specifications.
  857. *
  858. * @param {Mode} mode Data mode
  859. * @param {Number} version QR Code version
  860. * @return {Number} Number of bits
  861. */
  862. exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
  863. if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
  864. if (!VersionCheck.isValid(version)) {
  865. throw new Error('Invalid version: ' + version)
  866. }
  867. if (version >= 1 && version < 10) return mode.ccBits[0]
  868. else if (version < 27) return mode.ccBits[1]
  869. return mode.ccBits[2]
  870. };
  871. /**
  872. * Returns the most efficient mode to store the specified data
  873. *
  874. * @param {String} dataStr Input data string
  875. * @return {Mode} Best mode
  876. */
  877. exports.getBestModeForData = function getBestModeForData (dataStr) {
  878. if (Regex.testNumeric(dataStr)) return exports.NUMERIC
  879. else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
  880. else if (Regex.testKanji(dataStr)) return exports.KANJI
  881. else return exports.BYTE
  882. };
  883. /**
  884. * Return mode name as string
  885. *
  886. * @param {Mode} mode Mode object
  887. * @returns {String} Mode name
  888. */
  889. exports.toString = function toString (mode) {
  890. if (mode && mode.id) return mode.id
  891. throw new Error('Invalid mode')
  892. };
  893. /**
  894. * Check if input param is a valid mode object
  895. *
  896. * @param {Mode} mode Mode object
  897. * @returns {Boolean} True if valid mode, false otherwise
  898. */
  899. exports.isValid = function isValid (mode) {
  900. return mode && mode.bit && mode.ccBits
  901. };
  902. /**
  903. * Get mode object from its name
  904. *
  905. * @param {String} string Mode name
  906. * @returns {Mode} Mode object
  907. */
  908. function fromString (string) {
  909. if (typeof string !== 'string') {
  910. throw new Error('Param is not a string')
  911. }
  912. var lcStr = string.toLowerCase();
  913. switch (lcStr) {
  914. case 'numeric':
  915. return exports.NUMERIC
  916. case 'alphanumeric':
  917. return exports.ALPHANUMERIC
  918. case 'kanji':
  919. return exports.KANJI
  920. case 'byte':
  921. return exports.BYTE
  922. default:
  923. throw new Error('Unknown mode: ' + string)
  924. }
  925. }
  926. /**
  927. * Returns mode from a value.
  928. * If value is not a valid mode, returns defaultValue
  929. *
  930. * @param {Mode|String} value Encoding mode
  931. * @param {Mode} defaultValue Fallback value
  932. * @return {Mode} Encoding mode
  933. */
  934. exports.from = function from (value, defaultValue) {
  935. if (exports.isValid(value)) {
  936. return value
  937. }
  938. try {
  939. return fromString(value)
  940. } catch (e) {
  941. return defaultValue
  942. }
  943. };
  944. },{"./regex":19,"./version-check":22}],15:[function(require,module,exports){
  945. var Mode = require('./mode');
  946. function NumericData (data) {
  947. this.mode = Mode.NUMERIC;
  948. this.data = data.toString();
  949. }
  950. NumericData.getBitsLength = function getBitsLength (length) {
  951. return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
  952. };
  953. NumericData.prototype.getLength = function getLength () {
  954. return this.data.length
  955. };
  956. NumericData.prototype.getBitsLength = function getBitsLength () {
  957. return NumericData.getBitsLength(this.data.length)
  958. };
  959. NumericData.prototype.write = function write (bitBuffer) {
  960. var i, group, value;
  961. // The input data string is divided into groups of three digits,
  962. // and each group is converted to its 10-bit binary equivalent.
  963. for (i = 0; i + 3 <= this.data.length; i += 3) {
  964. group = this.data.substr(i, 3);
  965. value = parseInt(group, 10);
  966. bitBuffer.put(value, 10);
  967. }
  968. // If the number of input digits is not an exact multiple of three,
  969. // the final one or two digits are converted to 4 or 7 bits respectively.
  970. var remainingNum = this.data.length - i;
  971. if (remainingNum > 0) {
  972. group = this.data.substr(i);
  973. value = parseInt(group, 10);
  974. bitBuffer.put(value, remainingNum * 3 + 1);
  975. }
  976. };
  977. module.exports = NumericData;
  978. },{"./mode":14}],16:[function(require,module,exports){
  979. var BufferUtil = require('../utils/buffer');
  980. var GF = require('./galois-field');
  981. /**
  982. * Multiplies two polynomials inside Galois Field
  983. *
  984. * @param {Buffer} p1 Polynomial
  985. * @param {Buffer} p2 Polynomial
  986. * @return {Buffer} Product of p1 and p2
  987. */
  988. exports.mul = function mul (p1, p2) {
  989. var coeff = BufferUtil.alloc(p1.length + p2.length - 1);
  990. for (var i = 0; i < p1.length; i++) {
  991. for (var j = 0; j < p2.length; j++) {
  992. coeff[i + j] ^= GF.mul(p1[i], p2[j]);
  993. }
  994. }
  995. return coeff
  996. };
  997. /**
  998. * Calculate the remainder of polynomials division
  999. *
  1000. * @param {Buffer} divident Polynomial
  1001. * @param {Buffer} divisor Polynomial
  1002. * @return {Buffer} Remainder
  1003. */
  1004. exports.mod = function mod (divident, divisor) {
  1005. var result = BufferUtil.from(divident);
  1006. while ((result.length - divisor.length) >= 0) {
  1007. var coeff = result[0];
  1008. for (var i = 0; i < divisor.length; i++) {
  1009. result[i] ^= GF.mul(divisor[i], coeff);
  1010. }
  1011. // remove all zeros from buffer head
  1012. var offset = 0;
  1013. while (offset < result.length && result[offset] === 0) offset++;
  1014. result = result.slice(offset);
  1015. }
  1016. return result
  1017. };
  1018. /**
  1019. * Generate an irreducible generator polynomial of specified degree
  1020. * (used by Reed-Solomon encoder)
  1021. *
  1022. * @param {Number} degree Degree of the generator polynomial
  1023. * @return {Buffer} Buffer containing polynomial coefficients
  1024. */
  1025. exports.generateECPolynomial = function generateECPolynomial (degree) {
  1026. var poly = BufferUtil.from([1]);
  1027. for (var i = 0; i < degree; i++) {
  1028. poly = exports.mul(poly, [1, GF.exp(i)]);
  1029. }
  1030. return poly
  1031. };
  1032. },{"../utils/buffer":28,"./galois-field":11}],17:[function(require,module,exports){
  1033. var BufferUtil = require('../utils/buffer');
  1034. var Utils = require('./utils');
  1035. var ECLevel = require('./error-correction-level');
  1036. var BitBuffer = require('./bit-buffer');
  1037. var BitMatrix = require('./bit-matrix');
  1038. var AlignmentPattern = require('./alignment-pattern');
  1039. var FinderPattern = require('./finder-pattern');
  1040. var MaskPattern = require('./mask-pattern');
  1041. var ECCode = require('./error-correction-code');
  1042. var ReedSolomonEncoder = require('./reed-solomon-encoder');
  1043. var Version = require('./version');
  1044. var FormatInfo = require('./format-info');
  1045. var Mode = require('./mode');
  1046. var Segments = require('./segments');
  1047. var isArray = require('isarray');
  1048. /**
  1049. * QRCode for JavaScript
  1050. *
  1051. * modified by Ryan Day for nodejs support
  1052. * Copyright (c) 2011 Ryan Day
  1053. *
  1054. * Licensed under the MIT license:
  1055. * http://www.opensource.org/licenses/mit-license.php
  1056. *
  1057. //---------------------------------------------------------------------
  1058. // QRCode for JavaScript
  1059. //
  1060. // Copyright (c) 2009 Kazuhiko Arase
  1061. //
  1062. // URL: http://www.d-project.com/
  1063. //
  1064. // Licensed under the MIT license:
  1065. // http://www.opensource.org/licenses/mit-license.php
  1066. //
  1067. // The word "QR Code" is registered trademark of
  1068. // DENSO WAVE INCORPORATED
  1069. // http://www.denso-wave.com/qrcode/faqpatent-e.html
  1070. //
  1071. //---------------------------------------------------------------------
  1072. */
  1073. /**
  1074. * Add finder patterns bits to matrix
  1075. *
  1076. * @param {BitMatrix} matrix Modules matrix
  1077. * @param {Number} version QR Code version
  1078. */
  1079. function setupFinderPattern (matrix, version) {
  1080. var size = matrix.size;
  1081. var pos = FinderPattern.getPositions(version);
  1082. for (var i = 0; i < pos.length; i++) {
  1083. var row = pos[i][0];
  1084. var col = pos[i][1];
  1085. for (var r = -1; r <= 7; r++) {
  1086. if (row + r <= -1 || size <= row + r) continue
  1087. for (var c = -1; c <= 7; c++) {
  1088. if (col + c <= -1 || size <= col + c) continue
  1089. if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
  1090. (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
  1091. (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
  1092. matrix.set(row + r, col + c, true, true);
  1093. } else {
  1094. matrix.set(row + r, col + c, false, true);
  1095. }
  1096. }
  1097. }
  1098. }
  1099. }
  1100. /**
  1101. * Add timing pattern bits to matrix
  1102. *
  1103. * Note: this function must be called before {@link setupAlignmentPattern}
  1104. *
  1105. * @param {BitMatrix} matrix Modules matrix
  1106. */
  1107. function setupTimingPattern (matrix) {
  1108. var size = matrix.size;
  1109. for (var r = 8; r < size - 8; r++) {
  1110. var value = r % 2 === 0;
  1111. matrix.set(r, 6, value, true);
  1112. matrix.set(6, r, value, true);
  1113. }
  1114. }
  1115. /**
  1116. * Add alignment patterns bits to matrix
  1117. *
  1118. * Note: this function must be called after {@link setupTimingPattern}
  1119. *
  1120. * @param {BitMatrix} matrix Modules matrix
  1121. * @param {Number} version QR Code version
  1122. */
  1123. function setupAlignmentPattern (matrix, version) {
  1124. var pos = AlignmentPattern.getPositions(version);
  1125. for (var i = 0; i < pos.length; i++) {
  1126. var row = pos[i][0];
  1127. var col = pos[i][1];
  1128. for (var r = -2; r <= 2; r++) {
  1129. for (var c = -2; c <= 2; c++) {
  1130. if (r === -2 || r === 2 || c === -2 || c === 2 ||
  1131. (r === 0 && c === 0)) {
  1132. matrix.set(row + r, col + c, true, true);
  1133. } else {
  1134. matrix.set(row + r, col + c, false, true);
  1135. }
  1136. }
  1137. }
  1138. }
  1139. }
  1140. /**
  1141. * Add version info bits to matrix
  1142. *
  1143. * @param {BitMatrix} matrix Modules matrix
  1144. * @param {Number} version QR Code version
  1145. */
  1146. function setupVersionInfo (matrix, version) {
  1147. var size = matrix.size;
  1148. var bits = Version.getEncodedBits(version);
  1149. var row, col, mod;
  1150. for (var i = 0; i < 18; i++) {
  1151. row = Math.floor(i / 3);
  1152. col = i % 3 + size - 8 - 3;
  1153. mod = ((bits >> i) & 1) === 1;
  1154. matrix.set(row, col, mod, true);
  1155. matrix.set(col, row, mod, true);
  1156. }
  1157. }
  1158. /**
  1159. * Add format info bits to matrix
  1160. *
  1161. * @param {BitMatrix} matrix Modules matrix
  1162. * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
  1163. * @param {Number} maskPattern Mask pattern reference value
  1164. */
  1165. function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
  1166. var size = matrix.size;
  1167. var bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
  1168. var i, mod;
  1169. for (i = 0; i < 15; i++) {
  1170. mod = ((bits >> i) & 1) === 1;
  1171. // vertical
  1172. if (i < 6) {
  1173. matrix.set(i, 8, mod, true);
  1174. } else if (i < 8) {
  1175. matrix.set(i + 1, 8, mod, true);
  1176. } else {
  1177. matrix.set(size - 15 + i, 8, mod, true);
  1178. }
  1179. // horizontal
  1180. if (i < 8) {
  1181. matrix.set(8, size - i - 1, mod, true);
  1182. } else if (i < 9) {
  1183. matrix.set(8, 15 - i - 1 + 1, mod, true);
  1184. } else {
  1185. matrix.set(8, 15 - i - 1, mod, true);
  1186. }
  1187. }
  1188. // fixed module
  1189. matrix.set(size - 8, 8, 1, true);
  1190. }
  1191. /**
  1192. * Add encoded data bits to matrix
  1193. *
  1194. * @param {BitMatrix} matrix Modules matrix
  1195. * @param {Buffer} data Data codewords
  1196. */
  1197. function setupData (matrix, data) {
  1198. var size = matrix.size;
  1199. var inc = -1;
  1200. var row = size - 1;
  1201. var bitIndex = 7;
  1202. var byteIndex = 0;
  1203. for (var col = size - 1; col > 0; col -= 2) {
  1204. if (col === 6) col--;
  1205. while (true) {
  1206. for (var c = 0; c < 2; c++) {
  1207. if (!matrix.isReserved(row, col - c)) {
  1208. var dark = false;
  1209. if (byteIndex < data.length) {
  1210. dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
  1211. }
  1212. matrix.set(row, col - c, dark);
  1213. bitIndex--;
  1214. if (bitIndex === -1) {
  1215. byteIndex++;
  1216. bitIndex = 7;
  1217. }
  1218. }
  1219. }
  1220. row += inc;
  1221. if (row < 0 || size <= row) {
  1222. row -= inc;
  1223. inc = -inc;
  1224. break
  1225. }
  1226. }
  1227. }
  1228. }
  1229. /**
  1230. * Create encoded codewords from data input
  1231. *
  1232. * @param {Number} version QR Code version
  1233. * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
  1234. * @param {ByteData} data Data input
  1235. * @return {Buffer} Buffer containing encoded codewords
  1236. */
  1237. function createData (version, errorCorrectionLevel, segments) {
  1238. // Prepare data buffer
  1239. var buffer = new BitBuffer();
  1240. segments.forEach(function (data) {
  1241. // prefix data with mode indicator (4 bits)
  1242. buffer.put(data.mode.bit, 4);
  1243. // Prefix data with character count indicator.
  1244. // The character count indicator is a string of bits that represents the
  1245. // number of characters that are being encoded.
  1246. // The character count indicator must be placed after the mode indicator
  1247. // and must be a certain number of bits long, depending on the QR version
  1248. // and data mode
  1249. // @see {@link Mode.getCharCountIndicator}.
  1250. buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
  1251. // add binary data sequence to buffer
  1252. data.write(buffer);
  1253. });
  1254. // Calculate required number of bits
  1255. var totalCodewords = Utils.getSymbolTotalCodewords(version);
  1256. var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
  1257. var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
  1258. // Add a terminator.
  1259. // If the bit string is shorter than the total number of required bits,
  1260. // a terminator of up to four 0s must be added to the right side of the string.
  1261. // If the bit string is more than four bits shorter than the required number of bits,
  1262. // add four 0s to the end.
  1263. if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
  1264. buffer.put(0, 4);
  1265. }
  1266. // If the bit string is fewer than four bits shorter, add only the number of 0s that
  1267. // are needed to reach the required number of bits.
  1268. // After adding the terminator, if the number of bits in the string is not a multiple of 8,
  1269. // pad the string on the right with 0s to make the string's length a multiple of 8.
  1270. while (buffer.getLengthInBits() % 8 !== 0) {
  1271. buffer.putBit(0);
  1272. }
  1273. // Add pad bytes if the string is still shorter than the total number of required bits.
  1274. // Extend the buffer to fill the data capacity of the symbol corresponding to
  1275. // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
  1276. // and 00010001 (0x11) alternately.
  1277. var remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
  1278. for (var i = 0; i < remainingByte; i++) {
  1279. buffer.put(i % 2 ? 0x11 : 0xEC, 8);
  1280. }
  1281. return createCodewords(buffer, version, errorCorrectionLevel)
  1282. }
  1283. /**
  1284. * Encode input data with Reed-Solomon and return codewords with
  1285. * relative error correction bits
  1286. *
  1287. * @param {BitBuffer} bitBuffer Data to encode
  1288. * @param {Number} version QR Code version
  1289. * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
  1290. * @return {Buffer} Buffer containing encoded codewords
  1291. */
  1292. function createCodewords (bitBuffer, version, errorCorrectionLevel) {
  1293. // Total codewords for this QR code version (Data + Error correction)
  1294. var totalCodewords = Utils.getSymbolTotalCodewords(version);
  1295. // Total number of error correction codewords
  1296. var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
  1297. // Total number of data codewords
  1298. var dataTotalCodewords = totalCodewords - ecTotalCodewords;
  1299. // Total number of blocks
  1300. var ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
  1301. // Calculate how many blocks each group should contain
  1302. var blocksInGroup2 = totalCodewords % ecTotalBlocks;
  1303. var blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
  1304. var totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
  1305. var dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
  1306. var dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
  1307. // Number of EC codewords is the same for both groups
  1308. var ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
  1309. // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
  1310. var rs = new ReedSolomonEncoder(ecCount);
  1311. var offset = 0;
  1312. var dcData = new Array(ecTotalBlocks);
  1313. var ecData = new Array(ecTotalBlocks);
  1314. var maxDataSize = 0;
  1315. var buffer = BufferUtil.from(bitBuffer.buffer);
  1316. // Divide the buffer into the required number of blocks
  1317. for (var b = 0; b < ecTotalBlocks; b++) {
  1318. var dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
  1319. // extract a block of data from buffer
  1320. dcData[b] = buffer.slice(offset, offset + dataSize);
  1321. // Calculate EC codewords for this data block
  1322. ecData[b] = rs.encode(dcData[b]);
  1323. offset += dataSize;
  1324. maxDataSize = Math.max(maxDataSize, dataSize);
  1325. }
  1326. // Create final data
  1327. // Interleave the data and error correction codewords from each block
  1328. var data = BufferUtil.alloc(totalCodewords);
  1329. var index = 0;
  1330. var i, r;
  1331. // Add data codewords
  1332. for (i = 0; i < maxDataSize; i++) {
  1333. for (r = 0; r < ecTotalBlocks; r++) {
  1334. if (i < dcData[r].length) {
  1335. data[index++] = dcData[r][i];
  1336. }
  1337. }
  1338. }
  1339. // Apped EC codewords
  1340. for (i = 0; i < ecCount; i++) {
  1341. for (r = 0; r < ecTotalBlocks; r++) {
  1342. data[index++] = ecData[r][i];
  1343. }
  1344. }
  1345. return data
  1346. }
  1347. /**
  1348. * Build QR Code symbol
  1349. *
  1350. * @param {String} data Input string
  1351. * @param {Number} version QR Code version
  1352. * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
  1353. * @param {MaskPattern} maskPattern Mask pattern
  1354. * @return {Object} Object containing symbol data
  1355. */
  1356. function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
  1357. var segments;
  1358. if (isArray(data)) {
  1359. segments = Segments.fromArray(data);
  1360. } else if (typeof data === 'string') {
  1361. var estimatedVersion = version;
  1362. if (!estimatedVersion) {
  1363. var rawSegments = Segments.rawSplit(data);
  1364. // Estimate best version that can contain raw splitted segments
  1365. estimatedVersion = Version.getBestVersionForData(rawSegments,
  1366. errorCorrectionLevel);
  1367. }
  1368. // Build optimized segments
  1369. // If estimated version is undefined, try with the highest version
  1370. segments = Segments.fromString(data, estimatedVersion || 40);
  1371. } else {
  1372. throw new Error('Invalid data')
  1373. }
  1374. // Get the min version that can contain data
  1375. var bestVersion = Version.getBestVersionForData(segments,
  1376. errorCorrectionLevel);
  1377. // If no version is found, data cannot be stored
  1378. if (!bestVersion) {
  1379. throw new Error('The amount of data is too big to be stored in a QR Code')
  1380. }
  1381. // If not specified, use min version as default
  1382. if (!version) {
  1383. version = bestVersion;
  1384. // Check if the specified version can contain the data
  1385. } else if (version < bestVersion) {
  1386. throw new Error('\n' +
  1387. 'The chosen QR Code version cannot contain this amount of data.\n' +
  1388. 'Minimum version required to store current data is: ' + bestVersion + '.\n'
  1389. )
  1390. }
  1391. var dataBits = createData(version, errorCorrectionLevel, segments);
  1392. // Allocate matrix buffer
  1393. var moduleCount = Utils.getSymbolSize(version);
  1394. var modules = new BitMatrix(moduleCount);
  1395. // Add function modules
  1396. setupFinderPattern(modules, version);
  1397. setupTimingPattern(modules);
  1398. setupAlignmentPattern(modules, version);
  1399. // Add temporary dummy bits for format info just to set them as reserved.
  1400. // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
  1401. // since the masking operation must be performed only on the encoding region.
  1402. // These blocks will be replaced with correct values later in code.
  1403. setupFormatInfo(modules, errorCorrectionLevel, 0);
  1404. if (version >= 7) {
  1405. setupVersionInfo(modules, version);
  1406. }
  1407. // Add data codewords
  1408. setupData(modules, dataBits);
  1409. if (isNaN(maskPattern)) {
  1410. // Find best mask pattern
  1411. maskPattern = MaskPattern.getBestMask(modules,
  1412. setupFormatInfo.bind(null, modules, errorCorrectionLevel));
  1413. }
  1414. // Apply mask pattern
  1415. MaskPattern.applyMask(maskPattern, modules);
  1416. // Replace format info bits with correct values
  1417. setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
  1418. return {
  1419. modules: modules,
  1420. version: version,
  1421. errorCorrectionLevel: errorCorrectionLevel,
  1422. maskPattern: maskPattern,
  1423. segments: segments
  1424. }
  1425. }
  1426. /**
  1427. * QR Code
  1428. *
  1429. * @param {String | Array} data Input data
  1430. * @param {Object} options Optional configurations
  1431. * @param {Number} options.version QR Code version
  1432. * @param {String} options.errorCorrectionLevel Error correction level
  1433. * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
  1434. */
  1435. exports.create = function create (data, options) {
  1436. if (typeof data === 'undefined' || data === '') {
  1437. throw new Error('No input text')
  1438. }
  1439. var errorCorrectionLevel = ECLevel.M;
  1440. var version;
  1441. var mask;
  1442. if (typeof options !== 'undefined') {
  1443. // Use higher error correction level as default
  1444. errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
  1445. version = Version.from(options.version);
  1446. mask = MaskPattern.from(options.maskPattern);
  1447. if (options.toSJISFunc) {
  1448. Utils.setToSJISFunction(options.toSJISFunc);
  1449. }
  1450. }
  1451. return createSymbol(data, version, errorCorrectionLevel, mask)
  1452. };
  1453. },{"../utils/buffer":28,"./alignment-pattern":2,"./bit-buffer":4,"./bit-matrix":5,"./error-correction-code":7,"./error-correction-level":8,"./finder-pattern":9,"./format-info":10,"./mask-pattern":13,"./mode":14,"./reed-solomon-encoder":18,"./segments":20,"./utils":21,"./version":23,"isarray":33}],18:[function(require,module,exports){
  1454. var BufferUtil = require('../utils/buffer');
  1455. var Polynomial = require('./polynomial');
  1456. var Buffer = require('buffer').Buffer;
  1457. function ReedSolomonEncoder (degree) {
  1458. this.genPoly = undefined;
  1459. this.degree = degree;
  1460. if (this.degree) this.initialize(this.degree);
  1461. }
  1462. /**
  1463. * Initialize the encoder.
  1464. * The input param should correspond to the number of error correction codewords.
  1465. *
  1466. * @param {Number} degree
  1467. */
  1468. ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
  1469. // create an irreducible generator polynomial
  1470. this.degree = degree;
  1471. this.genPoly = Polynomial.generateECPolynomial(this.degree);
  1472. };
  1473. /**
  1474. * Encodes a chunk of data
  1475. *
  1476. * @param {Buffer} data Buffer containing input data
  1477. * @return {Buffer} Buffer containing encoded data
  1478. */
  1479. ReedSolomonEncoder.prototype.encode = function encode (data) {
  1480. if (!this.genPoly) {
  1481. throw new Error('Encoder not initialized')
  1482. }
  1483. // Calculate EC for this data block
  1484. // extends data size to data+genPoly size
  1485. var pad = BufferUtil.alloc(this.degree);
  1486. var paddedData = Buffer.concat([data, pad], data.length + this.degree);
  1487. // The error correction codewords are the remainder after dividing the data codewords
  1488. // by a generator polynomial
  1489. var remainder = Polynomial.mod(paddedData, this.genPoly);
  1490. // return EC data blocks (last n byte, where n is the degree of genPoly)
  1491. // If coefficients number in remainder are less than genPoly degree,
  1492. // pad with 0s to the left to reach the needed number of coefficients
  1493. var start = this.degree - remainder.length;
  1494. if (start > 0) {
  1495. var buff = BufferUtil.alloc(this.degree);
  1496. remainder.copy(buff, start);
  1497. return buff
  1498. }
  1499. return remainder
  1500. };
  1501. module.exports = ReedSolomonEncoder;
  1502. },{"../utils/buffer":28,"./polynomial":16,"buffer":30}],19:[function(require,module,exports){
  1503. var numeric = '[0-9]+';
  1504. var alphanumeric = '[A-Z $%*+\\-./:]+';
  1505. var kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
  1506. '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
  1507. '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
  1508. '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
  1509. kanji = kanji.replace(/u/g, '\\u');
  1510. var byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
  1511. exports.KANJI = new RegExp(kanji, 'g');
  1512. exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
  1513. exports.BYTE = new RegExp(byte, 'g');
  1514. exports.NUMERIC = new RegExp(numeric, 'g');
  1515. exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g');
  1516. var TEST_KANJI = new RegExp('^' + kanji + '$');
  1517. var TEST_NUMERIC = new RegExp('^' + numeric + '$');
  1518. var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
  1519. exports.testKanji = function testKanji (str) {
  1520. return TEST_KANJI.test(str)
  1521. };
  1522. exports.testNumeric = function testNumeric (str) {
  1523. return TEST_NUMERIC.test(str)
  1524. };
  1525. exports.testAlphanumeric = function testAlphanumeric (str) {
  1526. return TEST_ALPHANUMERIC.test(str)
  1527. };
  1528. },{}],20:[function(require,module,exports){
  1529. var Mode = require('./mode');
  1530. var NumericData = require('./numeric-data');
  1531. var AlphanumericData = require('./alphanumeric-data');
  1532. var ByteData = require('./byte-data');
  1533. var KanjiData = require('./kanji-data');
  1534. var Regex = require('./regex');
  1535. var Utils = require('./utils');
  1536. var dijkstra = require('dijkstrajs');
  1537. /**
  1538. * Returns UTF8 byte length
  1539. *
  1540. * @param {String} str Input string
  1541. * @return {Number} Number of byte
  1542. */
  1543. function getStringByteLength (str) {
  1544. return unescape(encodeURIComponent(str)).length
  1545. }
  1546. /**
  1547. * Get a list of segments of the specified mode
  1548. * from a string
  1549. *
  1550. * @param {Mode} mode Segment mode
  1551. * @param {String} str String to process
  1552. * @return {Array} Array of object with segments data
  1553. */
  1554. function getSegments (regex, mode, str) {
  1555. var segments = [];
  1556. var result;
  1557. while ((result = regex.exec(str)) !== null) {
  1558. segments.push({
  1559. data: result[0],
  1560. index: result.index,
  1561. mode: mode,
  1562. length: result[0].length
  1563. });
  1564. }
  1565. return segments
  1566. }
  1567. /**
  1568. * Extracts a series of segments with the appropriate
  1569. * modes from a string
  1570. *
  1571. * @param {String} dataStr Input string
  1572. * @return {Array} Array of object with segments data
  1573. */
  1574. function getSegmentsFromString (dataStr) {
  1575. var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
  1576. var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
  1577. var byteSegs;
  1578. var kanjiSegs;
  1579. if (Utils.isKanjiModeEnabled()) {
  1580. byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
  1581. kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
  1582. } else {
  1583. byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
  1584. kanjiSegs = [];
  1585. }
  1586. var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
  1587. return segs
  1588. .sort(function (s1, s2) {
  1589. return s1.index - s2.index
  1590. })
  1591. .map(function (obj) {
  1592. return {
  1593. data: obj.data,
  1594. mode: obj.mode,
  1595. length: obj.length
  1596. }
  1597. })
  1598. }
  1599. /**
  1600. * Returns how many bits are needed to encode a string of
  1601. * specified length with the specified mode
  1602. *
  1603. * @param {Number} length String length
  1604. * @param {Mode} mode Segment mode
  1605. * @return {Number} Bit length
  1606. */
  1607. function getSegmentBitsLength (length, mode) {
  1608. switch (mode) {
  1609. case Mode.NUMERIC:
  1610. return NumericData.getBitsLength(length)
  1611. case Mode.ALPHANUMERIC:
  1612. return AlphanumericData.getBitsLength(length)
  1613. case Mode.KANJI:
  1614. return KanjiData.getBitsLength(length)
  1615. case Mode.BYTE:
  1616. return ByteData.getBitsLength(length)
  1617. }
  1618. }
  1619. /**
  1620. * Merges adjacent segments which have the same mode
  1621. *
  1622. * @param {Array} segs Array of object with segments data
  1623. * @return {Array} Array of object with segments data
  1624. */
  1625. function mergeSegments (segs) {
  1626. return segs.reduce(function (acc, curr) {
  1627. var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
  1628. if (prevSeg && prevSeg.mode === curr.mode) {
  1629. acc[acc.length - 1].data += curr.data;
  1630. return acc
  1631. }
  1632. acc.push(curr);
  1633. return acc
  1634. }, [])
  1635. }
  1636. /**
  1637. * Generates a list of all possible nodes combination which
  1638. * will be used to build a segments graph.
  1639. *
  1640. * Nodes are divided by groups. Each group will contain a list of all the modes
  1641. * in which is possible to encode the given text.
  1642. *
  1643. * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
  1644. * The group for '12345' will contain then 3 objects, one for each
  1645. * possible encoding mode.
  1646. *
  1647. * Each node represents a possible segment.
  1648. *
  1649. * @param {Array} segs Array of object with segments data
  1650. * @return {Array} Array of object with segments data
  1651. */
  1652. function buildNodes (segs) {
  1653. var nodes = [];
  1654. for (var i = 0; i < segs.length; i++) {
  1655. var seg = segs[i];
  1656. switch (seg.mode) {
  1657. case Mode.NUMERIC:
  1658. nodes.push([seg,
  1659. { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
  1660. { data: seg.data, mode: Mode.BYTE, length: seg.length }
  1661. ]);
  1662. break
  1663. case Mode.ALPHANUMERIC:
  1664. nodes.push([seg,
  1665. { data: seg.data, mode: Mode.BYTE, length: seg.length }
  1666. ]);
  1667. break
  1668. case Mode.KANJI:
  1669. nodes.push([seg,
  1670. { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
  1671. ]);
  1672. break
  1673. case Mode.BYTE:
  1674. nodes.push([
  1675. { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
  1676. ]);
  1677. }
  1678. }
  1679. return nodes
  1680. }
  1681. /**
  1682. * Builds a graph from a list of nodes.
  1683. * All segments in each node group will be connected with all the segments of
  1684. * the next group and so on.
  1685. *
  1686. * At each connection will be assigned a weight depending on the
  1687. * segment's byte length.
  1688. *
  1689. * @param {Array} nodes Array of object with segments data
  1690. * @param {Number} version QR Code version
  1691. * @return {Object} Graph of all possible segments
  1692. */
  1693. function buildGraph (nodes, version) {
  1694. var table = {};
  1695. var graph = {'start': {}};
  1696. var prevNodeIds = ['start'];
  1697. for (var i = 0; i < nodes.length; i++) {
  1698. var nodeGroup = nodes[i];
  1699. var currentNodeIds = [];
  1700. for (var j = 0; j < nodeGroup.length; j++) {
  1701. var node = nodeGroup[j];
  1702. var key = '' + i + j;
  1703. currentNodeIds.push(key);
  1704. table[key] = { node: node, lastCount: 0 };
  1705. graph[key] = {};
  1706. for (var n = 0; n < prevNodeIds.length; n++) {
  1707. var prevNodeId = prevNodeIds[n];
  1708. if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
  1709. graph[prevNodeId][key] =
  1710. getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
  1711. getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
  1712. table[prevNodeId].lastCount += node.length;
  1713. } else {
  1714. if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
  1715. graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
  1716. 4 + Mode.getCharCountIndicator(node.mode, version); // switch cost
  1717. }
  1718. }
  1719. }
  1720. prevNodeIds = currentNodeIds;
  1721. }
  1722. for (n = 0; n < prevNodeIds.length; n++) {
  1723. graph[prevNodeIds[n]]['end'] = 0;
  1724. }
  1725. return { map: graph, table: table }
  1726. }
  1727. /**
  1728. * Builds a segment from a specified data and mode.
  1729. * If a mode is not specified, the more suitable will be used.
  1730. *
  1731. * @param {String} data Input data
  1732. * @param {Mode | String} modesHint Data mode
  1733. * @return {Segment} Segment
  1734. */
  1735. function buildSingleSegment (data, modesHint) {
  1736. var mode;
  1737. var bestMode = Mode.getBestModeForData(data);
  1738. mode = Mode.from(modesHint, bestMode);
  1739. // Make sure data can be encoded
  1740. if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
  1741. throw new Error('"' + data + '"' +
  1742. ' cannot be encoded with mode ' + Mode.toString(mode) +
  1743. '.\n Suggested mode is: ' + Mode.toString(bestMode))
  1744. }
  1745. // Use Mode.BYTE if Kanji support is disabled
  1746. if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
  1747. mode = Mode.BYTE;
  1748. }
  1749. switch (mode) {
  1750. case Mode.NUMERIC:
  1751. return new NumericData(data)
  1752. case Mode.ALPHANUMERIC:
  1753. return new AlphanumericData(data)
  1754. case Mode.KANJI:
  1755. return new KanjiData(data)
  1756. case Mode.BYTE:
  1757. return new ByteData(data)
  1758. }
  1759. }
  1760. /**
  1761. * Builds a list of segments from an array.
  1762. * Array can contain Strings or Objects with segment's info.
  1763. *
  1764. * For each item which is a string, will be generated a segment with the given
  1765. * string and the more appropriate encoding mode.
  1766. *
  1767. * For each item which is an object, will be generated a segment with the given
  1768. * data and mode.
  1769. * Objects must contain at least the property "data".
  1770. * If property "mode" is not present, the more suitable mode will be used.
  1771. *
  1772. * @param {Array} array Array of objects with segments data
  1773. * @return {Array} Array of Segments
  1774. */
  1775. exports.fromArray = function fromArray (array) {
  1776. return array.reduce(function (acc, seg) {
  1777. if (typeof seg === 'string') {
  1778. acc.push(buildSingleSegment(seg, null));
  1779. } else if (seg.data) {
  1780. acc.push(buildSingleSegment(seg.data, seg.mode));
  1781. }
  1782. return acc
  1783. }, [])
  1784. };
  1785. /**
  1786. * Builds an optimized sequence of segments from a string,
  1787. * which will produce the shortest possible bitstream.
  1788. *
  1789. * @param {String} data Input string
  1790. * @param {Number} version QR Code version
  1791. * @return {Array} Array of segments
  1792. */
  1793. exports.fromString = function fromString (data, version) {
  1794. var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
  1795. var nodes = buildNodes(segs);
  1796. var graph = buildGraph(nodes, version);
  1797. var path = dijkstra.find_path(graph.map, 'start', 'end');
  1798. var optimizedSegs = [];
  1799. for (var i = 1; i < path.length - 1; i++) {
  1800. optimizedSegs.push(graph.table[path[i]].node);
  1801. }
  1802. return exports.fromArray(mergeSegments(optimizedSegs))
  1803. };
  1804. /**
  1805. * Splits a string in various segments with the modes which
  1806. * best represent their content.
  1807. * The produced segments are far from being optimized.
  1808. * The output of this function is only used to estimate a QR Code version
  1809. * which may contain the data.
  1810. *
  1811. * @param {string} data Input string
  1812. * @return {Array} Array of segments
  1813. */
  1814. exports.rawSplit = function rawSplit (data) {
  1815. return exports.fromArray(
  1816. getSegmentsFromString(data, Utils.isKanjiModeEnabled())
  1817. )
  1818. };
  1819. },{"./alphanumeric-data":3,"./byte-data":6,"./kanji-data":12,"./mode":14,"./numeric-data":15,"./regex":19,"./utils":21,"dijkstrajs":31}],21:[function(require,module,exports){
  1820. var toSJISFunction;
  1821. var CODEWORDS_COUNT = [
  1822. 0, // Not used
  1823. 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
  1824. 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
  1825. 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
  1826. 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
  1827. ];
  1828. /**
  1829. * Returns the QR Code size for the specified version
  1830. *
  1831. * @param {Number} version QR Code version
  1832. * @return {Number} size of QR code
  1833. */
  1834. exports.getSymbolSize = function getSymbolSize (version) {
  1835. if (!version) throw new Error('"version" cannot be null or undefined')
  1836. if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
  1837. return version * 4 + 17
  1838. };
  1839. /**
  1840. * Returns the total number of codewords used to store data and EC information.
  1841. *
  1842. * @param {Number} version QR Code version
  1843. * @return {Number} Data length in bits
  1844. */
  1845. exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
  1846. return CODEWORDS_COUNT[version]
  1847. };
  1848. /**
  1849. * Encode data with Bose-Chaudhuri-Hocquenghem
  1850. *
  1851. * @param {Number} data Value to encode
  1852. * @return {Number} Encoded value
  1853. */
  1854. exports.getBCHDigit = function (data) {
  1855. var digit = 0;
  1856. while (data !== 0) {
  1857. digit++;
  1858. data >>>= 1;
  1859. }
  1860. return digit
  1861. };
  1862. exports.setToSJISFunction = function setToSJISFunction (f) {
  1863. if (typeof f !== 'function') {
  1864. throw new Error('"toSJISFunc" is not a valid function.')
  1865. }
  1866. toSJISFunction = f;
  1867. };
  1868. exports.isKanjiModeEnabled = function () {
  1869. return typeof toSJISFunction !== 'undefined'
  1870. };
  1871. exports.toSJIS = function toSJIS (kanji) {
  1872. return toSJISFunction(kanji)
  1873. };
  1874. },{}],22:[function(require,module,exports){
  1875. /**
  1876. * Check if QR Code version is valid
  1877. *
  1878. * @param {Number} version QR Code version
  1879. * @return {Boolean} true if valid version, false otherwise
  1880. */
  1881. exports.isValid = function isValid (version) {
  1882. return !isNaN(version) && version >= 1 && version <= 40
  1883. };
  1884. },{}],23:[function(require,module,exports){
  1885. var Utils = require('./utils');
  1886. var ECCode = require('./error-correction-code');
  1887. var ECLevel = require('./error-correction-level');
  1888. var Mode = require('./mode');
  1889. var VersionCheck = require('./version-check');
  1890. var isArray = require('isarray');
  1891. // Generator polynomial used to encode version information
  1892. var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
  1893. var G18_BCH = Utils.getBCHDigit(G18);
  1894. function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
  1895. for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
  1896. if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
  1897. return currentVersion
  1898. }
  1899. }
  1900. return undefined
  1901. }
  1902. function getReservedBitsCount (mode, version) {
  1903. // Character count indicator + mode indicator bits
  1904. return Mode.getCharCountIndicator(mode, version) + 4
  1905. }
  1906. function getTotalBitsFromDataArray (segments, version) {
  1907. var totalBits = 0;
  1908. segments.forEach(function (data) {
  1909. var reservedBits = getReservedBitsCount(data.mode, version);
  1910. totalBits += reservedBits + data.getBitsLength();
  1911. });
  1912. return totalBits
  1913. }
  1914. function getBestVersionForMixedData (segments, errorCorrectionLevel) {
  1915. for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
  1916. var length = getTotalBitsFromDataArray(segments, currentVersion);
  1917. if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
  1918. return currentVersion
  1919. }
  1920. }
  1921. return undefined
  1922. }
  1923. /**
  1924. * Returns version number from a value.
  1925. * If value is not a valid version, returns defaultValue
  1926. *
  1927. * @param {Number|String} value QR Code version
  1928. * @param {Number} defaultValue Fallback value
  1929. * @return {Number} QR Code version number
  1930. */
  1931. exports.from = function from (value, defaultValue) {
  1932. if (VersionCheck.isValid(value)) {
  1933. return parseInt(value, 10)
  1934. }
  1935. return defaultValue
  1936. };
  1937. /**
  1938. * Returns how much data can be stored with the specified QR code version
  1939. * and error correction level
  1940. *
  1941. * @param {Number} version QR Code version (1-40)
  1942. * @param {Number} errorCorrectionLevel Error correction level
  1943. * @param {Mode} mode Data mode
  1944. * @return {Number} Quantity of storable data
  1945. */
  1946. exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
  1947. if (!VersionCheck.isValid(version)) {
  1948. throw new Error('Invalid QR Code version')
  1949. }
  1950. // Use Byte mode as default
  1951. if (typeof mode === 'undefined') mode = Mode.BYTE;
  1952. // Total codewords for this QR code version (Data + Error correction)
  1953. var totalCodewords = Utils.getSymbolTotalCodewords(version);
  1954. // Total number of error correction codewords
  1955. var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
  1956. // Total number of data codewords
  1957. var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
  1958. if (mode === Mode.MIXED) return dataTotalCodewordsBits
  1959. var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
  1960. // Return max number of storable codewords
  1961. switch (mode) {
  1962. case Mode.NUMERIC:
  1963. return Math.floor((usableBits / 10) * 3)
  1964. case Mode.ALPHANUMERIC:
  1965. return Math.floor((usableBits / 11) * 2)
  1966. case Mode.KANJI:
  1967. return Math.floor(usableBits / 13)
  1968. case Mode.BYTE:
  1969. default:
  1970. return Math.floor(usableBits / 8)
  1971. }
  1972. };
  1973. /**
  1974. * Returns the minimum version needed to contain the amount of data
  1975. *
  1976. * @param {Segment} data Segment of data
  1977. * @param {Number} [errorCorrectionLevel=H] Error correction level
  1978. * @param {Mode} mode Data mode
  1979. * @return {Number} QR Code version
  1980. */
  1981. exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
  1982. var seg;
  1983. var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
  1984. if (isArray(data)) {
  1985. if (data.length > 1) {
  1986. return getBestVersionForMixedData(data, ecl)
  1987. }
  1988. if (data.length === 0) {
  1989. return 1
  1990. }
  1991. seg = data[0];
  1992. } else {
  1993. seg = data;
  1994. }
  1995. return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
  1996. };
  1997. /**
  1998. * Returns version information with relative error correction bits
  1999. *
  2000. * The version information is included in QR Code symbols of version 7 or larger.
  2001. * It consists of an 18-bit sequence containing 6 data bits,
  2002. * with 12 error correction bits calculated using the (18, 6) Golay code.
  2003. *
  2004. * @param {Number} version QR Code version
  2005. * @return {Number} Encoded version info bits
  2006. */
  2007. exports.getEncodedBits = function getEncodedBits (version) {
  2008. if (!VersionCheck.isValid(version) || version < 7) {
  2009. throw new Error('Invalid QR Code version')
  2010. }
  2011. var d = version << 12;
  2012. while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
  2013. d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH));
  2014. }
  2015. return (version << 12) | d
  2016. };
  2017. },{"./error-correction-code":7,"./error-correction-level":8,"./mode":14,"./utils":21,"./version-check":22,"isarray":33}],24:[function(require,module,exports){
  2018. var canPromise = require('./can-promise');
  2019. var QRCode = require('./core/qrcode');
  2020. var CanvasRenderer = require('./renderer/canvas');
  2021. var SvgRenderer = require('./renderer/svg-tag.js');
  2022. function renderCanvas (renderFunc, canvas, text, opts, cb) {
  2023. var args = [].slice.call(arguments, 1);
  2024. var argsNum = args.length;
  2025. var isLastArgCb = typeof args[argsNum - 1] === 'function';
  2026. if (!isLastArgCb && !canPromise()) {
  2027. throw new Error('Callback required as last argument')
  2028. }
  2029. if (isLastArgCb) {
  2030. if (argsNum < 2) {
  2031. throw new Error('Too few arguments provided')
  2032. }
  2033. if (argsNum === 2) {
  2034. cb = text;
  2035. text = canvas;
  2036. canvas = opts = undefined;
  2037. } else if (argsNum === 3) {
  2038. if (canvas.getContext && typeof cb === 'undefined') {
  2039. cb = opts;
  2040. opts = undefined;
  2041. } else {
  2042. cb = opts;
  2043. opts = text;
  2044. text = canvas;
  2045. canvas = undefined;
  2046. }
  2047. }
  2048. } else {
  2049. if (argsNum < 1) {
  2050. throw new Error('Too few arguments provided')
  2051. }
  2052. if (argsNum === 1) {
  2053. text = canvas;
  2054. canvas = opts = undefined;
  2055. } else if (argsNum === 2 && !canvas.getContext) {
  2056. opts = text;
  2057. text = canvas;
  2058. canvas = undefined;
  2059. }
  2060. return new Promise(function (resolve, reject) {
  2061. try {
  2062. var data = QRCode.create(text, opts);
  2063. resolve(renderFunc(data, canvas, opts));
  2064. } catch (e) {
  2065. reject(e);
  2066. }
  2067. })
  2068. }
  2069. try {
  2070. var data = QRCode.create(text, opts);
  2071. cb(null, renderFunc(data, canvas, opts));
  2072. } catch (e) {
  2073. cb(e);
  2074. }
  2075. }
  2076. exports.create = QRCode.create;
  2077. exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
  2078. exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
  2079. // only svg for now.
  2080. exports.toString = renderCanvas.bind(null, function (data, _, opts) {
  2081. return SvgRenderer.render(data, opts)
  2082. });
  2083. },{"./can-promise":1,"./core/qrcode":17,"./renderer/canvas":25,"./renderer/svg-tag.js":26}],25:[function(require,module,exports){
  2084. var Utils = require('./utils');
  2085. function clearCanvas (ctx, canvas, size) {
  2086. ctx.clearRect(0, 0, canvas.width, canvas.height);
  2087. if (!canvas.style) canvas.style = {};
  2088. canvas.height = size;
  2089. canvas.width = size;
  2090. canvas.style.height = size + 'px';
  2091. canvas.style.width = size + 'px';
  2092. }
  2093. function getCanvasElement () {
  2094. try {
  2095. return document.createElement('canvas')
  2096. } catch (e) {
  2097. throw new Error('You need to specify a canvas element')
  2098. }
  2099. }
  2100. exports.render = function render (qrData, canvas, options) {
  2101. var opts = options;
  2102. var canvasEl = canvas;
  2103. if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
  2104. opts = canvas;
  2105. canvas = undefined;
  2106. }
  2107. if (!canvas) {
  2108. canvasEl = getCanvasElement();
  2109. }
  2110. opts = Utils.getOptions(opts);
  2111. var size = Utils.getImageWidth(qrData.modules.size, opts);
  2112. var ctx = canvasEl.getContext('2d');
  2113. var image = ctx.createImageData(size, size);
  2114. Utils.qrToImageData(image.data, qrData, opts);
  2115. clearCanvas(ctx, canvasEl, size);
  2116. ctx.putImageData(image, 0, 0);
  2117. return canvasEl
  2118. };
  2119. exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
  2120. var opts = options;
  2121. if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
  2122. opts = canvas;
  2123. canvas = undefined;
  2124. }
  2125. if (!opts) opts = {};
  2126. var canvasEl = exports.render(qrData, canvas, opts);
  2127. var type = opts.type || 'image/png';
  2128. var rendererOpts = opts.rendererOpts || {};
  2129. return canvasEl.toDataURL(type, rendererOpts.quality)
  2130. };
  2131. },{"./utils":27}],26:[function(require,module,exports){
  2132. var Utils = require('./utils');
  2133. function getColorAttrib (color, attrib) {
  2134. var alpha = color.a / 255;
  2135. var str = attrib + '="' + color.hex + '"';
  2136. return alpha < 1
  2137. ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
  2138. : str
  2139. }
  2140. function svgCmd (cmd, x, y) {
  2141. var str = cmd + x;
  2142. if (typeof y !== 'undefined') str += ' ' + y;
  2143. return str
  2144. }
  2145. function qrToPath (data, size, margin) {
  2146. var path = '';
  2147. var moveBy = 0;
  2148. var newRow = false;
  2149. var lineLength = 0;
  2150. for (var i = 0; i < data.length; i++) {
  2151. var col = Math.floor(i % size);
  2152. var row = Math.floor(i / size);
  2153. if (!col && !newRow) newRow = true;
  2154. if (data[i]) {
  2155. lineLength++;
  2156. if (!(i > 0 && col > 0 && data[i - 1])) {
  2157. path += newRow
  2158. ? svgCmd('M', col + margin, 0.5 + row + margin)
  2159. : svgCmd('m', moveBy, 0);
  2160. moveBy = 0;
  2161. newRow = false;
  2162. }
  2163. if (!(col + 1 < size && data[i + 1])) {
  2164. path += svgCmd('h', lineLength);
  2165. lineLength = 0;
  2166. }
  2167. } else {
  2168. moveBy++;
  2169. }
  2170. }
  2171. return path
  2172. }
  2173. exports.render = function render (qrData, options, cb) {
  2174. var opts = Utils.getOptions(options);
  2175. var size = qrData.modules.size;
  2176. var data = qrData.modules.data;
  2177. var qrcodesize = size + opts.margin * 2;
  2178. var bg = !opts.color.light.a
  2179. ? ''
  2180. : '<path ' + getColorAttrib(opts.color.light, 'fill') +
  2181. ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
  2182. var path =
  2183. '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
  2184. ' d="' + qrToPath(data, size, opts.margin) + '"/>';
  2185. var viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
  2186. var width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
  2187. var svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
  2188. if (typeof cb === 'function') {
  2189. cb(null, svgTag);
  2190. }
  2191. return svgTag
  2192. };
  2193. },{"./utils":27}],27:[function(require,module,exports){
  2194. function hex2rgba (hex) {
  2195. if (typeof hex === 'number') {
  2196. hex = hex.toString();
  2197. }
  2198. if (typeof hex !== 'string') {
  2199. throw new Error('Color should be defined as hex string')
  2200. }
  2201. var hexCode = hex.slice().replace('#', '').split('');
  2202. if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
  2203. throw new Error('Invalid hex color: ' + hex)
  2204. }
  2205. // Convert from short to long form (fff -> ffffff)
  2206. if (hexCode.length === 3 || hexCode.length === 4) {
  2207. hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
  2208. return [c, c]
  2209. }));
  2210. }
  2211. // Add default alpha value
  2212. if (hexCode.length === 6) hexCode.push('F', 'F');
  2213. var hexValue = parseInt(hexCode.join(''), 16);
  2214. return {
  2215. r: (hexValue >> 24) & 255,
  2216. g: (hexValue >> 16) & 255,
  2217. b: (hexValue >> 8) & 255,
  2218. a: hexValue & 255,
  2219. hex: '#' + hexCode.slice(0, 6).join('')
  2220. }
  2221. }
  2222. exports.getOptions = function getOptions (options) {
  2223. if (!options) options = {};
  2224. if (!options.color) options.color = {};
  2225. var margin = typeof options.margin === 'undefined' ||
  2226. options.margin === null ||
  2227. options.margin < 0 ? 4 : options.margin;
  2228. var width = options.width && options.width >= 21 ? options.width : undefined;
  2229. var scale = options.scale || 4;
  2230. return {
  2231. width: width,
  2232. scale: width ? 4 : scale,
  2233. margin: margin,
  2234. color: {
  2235. dark: hex2rgba(options.color.dark || '#000000ff'),
  2236. light: hex2rgba(options.color.light || '#ffffffff')
  2237. },
  2238. type: options.type,
  2239. rendererOpts: options.rendererOpts || {}
  2240. }
  2241. };
  2242. exports.getScale = function getScale (qrSize, opts) {
  2243. return opts.width && opts.width >= qrSize + opts.margin * 2
  2244. ? opts.width / (qrSize + opts.margin * 2)
  2245. : opts.scale
  2246. };
  2247. exports.getImageWidth = function getImageWidth (qrSize, opts) {
  2248. var scale = exports.getScale(qrSize, opts);
  2249. return Math.floor((qrSize + opts.margin * 2) * scale)
  2250. };
  2251. exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
  2252. var size = qr.modules.size;
  2253. var data = qr.modules.data;
  2254. var scale = exports.getScale(size, opts);
  2255. var symbolSize = Math.floor((size + opts.margin * 2) * scale);
  2256. var scaledMargin = opts.margin * scale;
  2257. var palette = [opts.color.light, opts.color.dark];
  2258. for (var i = 0; i < symbolSize; i++) {
  2259. for (var j = 0; j < symbolSize; j++) {
  2260. var posDst = (i * symbolSize + j) * 4;
  2261. var pxColor = opts.color.light;
  2262. if (i >= scaledMargin && j >= scaledMargin &&
  2263. i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
  2264. var iSrc = Math.floor((i - scaledMargin) / scale);
  2265. var jSrc = Math.floor((j - scaledMargin) / scale);
  2266. pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
  2267. }
  2268. imgData[posDst++] = pxColor.r;
  2269. imgData[posDst++] = pxColor.g;
  2270. imgData[posDst++] = pxColor.b;
  2271. imgData[posDst] = pxColor.a;
  2272. }
  2273. }
  2274. };
  2275. },{}],28:[function(require,module,exports){
  2276. var isArray = require('isarray');
  2277. function typedArraySupport () {
  2278. // Can typed array instances be augmented?
  2279. try {
  2280. var arr = new Uint8Array(1);
  2281. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }};
  2282. return arr.foo() === 42
  2283. } catch (e) {
  2284. return false
  2285. }
  2286. }
  2287. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
  2288. var K_MAX_LENGTH = Buffer.TYPED_ARRAY_SUPPORT
  2289. ? 0x7fffffff
  2290. : 0x3fffffff;
  2291. function Buffer (arg, offset, length) {
  2292. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  2293. return new Buffer(arg, offset, length)
  2294. }
  2295. if (typeof arg === 'number') {
  2296. return allocUnsafe(this, arg)
  2297. }
  2298. return from(this, arg, offset, length)
  2299. }
  2300. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2301. Buffer.prototype.__proto__ = Uint8Array.prototype;
  2302. Buffer.__proto__ = Uint8Array;
  2303. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2304. if (typeof Symbol !== 'undefined' && Symbol.species &&
  2305. Buffer[Symbol.species] === Buffer) {
  2306. Object.defineProperty(Buffer, Symbol.species, {
  2307. value: null,
  2308. configurable: true,
  2309. enumerable: false,
  2310. writable: false
  2311. });
  2312. }
  2313. }
  2314. function checked (length) {
  2315. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2316. // length is NaN (which is otherwise coerced to zero.)
  2317. if (length >= K_MAX_LENGTH) {
  2318. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2319. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2320. }
  2321. return length | 0
  2322. }
  2323. function isnan (val) {
  2324. return val !== val // eslint-disable-line no-self-compare
  2325. }
  2326. function createBuffer (that, length) {
  2327. var buf;
  2328. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2329. buf = new Uint8Array(length);
  2330. buf.__proto__ = Buffer.prototype;
  2331. } else {
  2332. // Fallback: Return an object instance of the Buffer class
  2333. buf = that;
  2334. if (buf === null) {
  2335. buf = new Buffer(length);
  2336. }
  2337. buf.length = length;
  2338. }
  2339. return buf
  2340. }
  2341. function allocUnsafe (that, size) {
  2342. var buf = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
  2343. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  2344. for (var i = 0; i < size; ++i) {
  2345. buf[i] = 0;
  2346. }
  2347. }
  2348. return buf
  2349. }
  2350. function fromString (that, string) {
  2351. var length = byteLength(string) | 0;
  2352. var buf = createBuffer(that, length);
  2353. var actual = buf.write(string);
  2354. if (actual !== length) {
  2355. // Writing a hex string, for example, that contains invalid characters will
  2356. // cause everything after the first invalid character to be ignored. (e.g.
  2357. // 'abxxcd' will be treated as 'ab')
  2358. buf = buf.slice(0, actual);
  2359. }
  2360. return buf
  2361. }
  2362. function fromArrayLike (that, array) {
  2363. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  2364. var buf = createBuffer(that, length);
  2365. for (var i = 0; i < length; i += 1) {
  2366. buf[i] = array[i] & 255;
  2367. }
  2368. return buf
  2369. }
  2370. function fromArrayBuffer (that, array, byteOffset, length) {
  2371. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2372. throw new RangeError('\'offset\' is out of bounds')
  2373. }
  2374. if (array.byteLength < byteOffset + (length || 0)) {
  2375. throw new RangeError('\'length\' is out of bounds')
  2376. }
  2377. var buf;
  2378. if (byteOffset === undefined && length === undefined) {
  2379. buf = new Uint8Array(array);
  2380. } else if (length === undefined) {
  2381. buf = new Uint8Array(array, byteOffset);
  2382. } else {
  2383. buf = new Uint8Array(array, byteOffset, length);
  2384. }
  2385. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2386. // Return an augmented `Uint8Array` instance, for best performance
  2387. buf.__proto__ = Buffer.prototype;
  2388. } else {
  2389. // Fallback: Return an object instance of the Buffer class
  2390. buf = fromArrayLike(that, buf);
  2391. }
  2392. return buf
  2393. }
  2394. function fromObject (that, obj) {
  2395. if (Buffer.isBuffer(obj)) {
  2396. var len = checked(obj.length) | 0;
  2397. var buf = createBuffer(that, len);
  2398. if (buf.length === 0) {
  2399. return buf
  2400. }
  2401. obj.copy(buf, 0, 0, len);
  2402. return buf
  2403. }
  2404. if (obj) {
  2405. if ((typeof ArrayBuffer !== 'undefined' &&
  2406. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  2407. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  2408. return createBuffer(that, 0)
  2409. }
  2410. return fromArrayLike(that, obj)
  2411. }
  2412. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2413. return fromArrayLike(that, obj.data)
  2414. }
  2415. }
  2416. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  2417. }
  2418. function utf8ToBytes (string, units) {
  2419. units = units || Infinity;
  2420. var codePoint;
  2421. var length = string.length;
  2422. var leadSurrogate = null;
  2423. var bytes = [];
  2424. for (var i = 0; i < length; ++i) {
  2425. codePoint = string.charCodeAt(i);
  2426. // is surrogate component
  2427. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2428. // last char was a lead
  2429. if (!leadSurrogate) {
  2430. // no lead yet
  2431. if (codePoint > 0xDBFF) {
  2432. // unexpected trail
  2433. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2434. continue
  2435. } else if (i + 1 === length) {
  2436. // unpaired lead
  2437. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2438. continue
  2439. }
  2440. // valid lead
  2441. leadSurrogate = codePoint;
  2442. continue
  2443. }
  2444. // 2 leads in a row
  2445. if (codePoint < 0xDC00) {
  2446. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2447. leadSurrogate = codePoint;
  2448. continue
  2449. }
  2450. // valid surrogate pair
  2451. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  2452. } else if (leadSurrogate) {
  2453. // valid bmp char, but last char was a lead
  2454. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  2455. }
  2456. leadSurrogate = null;
  2457. // encode utf8
  2458. if (codePoint < 0x80) {
  2459. if ((units -= 1) < 0) break
  2460. bytes.push(codePoint);
  2461. } else if (codePoint < 0x800) {
  2462. if ((units -= 2) < 0) break
  2463. bytes.push(
  2464. codePoint >> 0x6 | 0xC0,
  2465. codePoint & 0x3F | 0x80
  2466. );
  2467. } else if (codePoint < 0x10000) {
  2468. if ((units -= 3) < 0) break
  2469. bytes.push(
  2470. codePoint >> 0xC | 0xE0,
  2471. codePoint >> 0x6 & 0x3F | 0x80,
  2472. codePoint & 0x3F | 0x80
  2473. );
  2474. } else if (codePoint < 0x110000) {
  2475. if ((units -= 4) < 0) break
  2476. bytes.push(
  2477. codePoint >> 0x12 | 0xF0,
  2478. codePoint >> 0xC & 0x3F | 0x80,
  2479. codePoint >> 0x6 & 0x3F | 0x80,
  2480. codePoint & 0x3F | 0x80
  2481. );
  2482. } else {
  2483. throw new Error('Invalid code point')
  2484. }
  2485. }
  2486. return bytes
  2487. }
  2488. function byteLength (string) {
  2489. if (Buffer.isBuffer(string)) {
  2490. return string.length
  2491. }
  2492. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  2493. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  2494. return string.byteLength
  2495. }
  2496. if (typeof string !== 'string') {
  2497. string = '' + string;
  2498. }
  2499. var len = string.length;
  2500. if (len === 0) return 0
  2501. return utf8ToBytes(string).length
  2502. }
  2503. function blitBuffer (src, dst, offset, length) {
  2504. for (var i = 0; i < length; ++i) {
  2505. if ((i + offset >= dst.length) || (i >= src.length)) break
  2506. dst[i + offset] = src[i];
  2507. }
  2508. return i
  2509. }
  2510. function utf8Write (buf, string, offset, length) {
  2511. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2512. }
  2513. function from (that, value, offset, length) {
  2514. if (typeof value === 'number') {
  2515. throw new TypeError('"value" argument must not be a number')
  2516. }
  2517. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  2518. return fromArrayBuffer(that, value, offset, length)
  2519. }
  2520. if (typeof value === 'string') {
  2521. return fromString(that, value)
  2522. }
  2523. return fromObject(that, value)
  2524. }
  2525. Buffer.prototype.write = function write (string, offset, length) {
  2526. // Buffer#write(string)
  2527. if (offset === undefined) {
  2528. length = this.length;
  2529. offset = 0;
  2530. // Buffer#write(string, encoding)
  2531. } else if (length === undefined && typeof offset === 'string') {
  2532. length = this.length;
  2533. offset = 0;
  2534. // Buffer#write(string, offset[, length])
  2535. } else if (isFinite(offset)) {
  2536. offset = offset | 0;
  2537. if (isFinite(length)) {
  2538. length = length | 0;
  2539. } else {
  2540. length = undefined;
  2541. }
  2542. }
  2543. var remaining = this.length - offset;
  2544. if (length === undefined || length > remaining) length = remaining;
  2545. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2546. throw new RangeError('Attempt to write outside buffer bounds')
  2547. }
  2548. return utf8Write(this, string, offset, length)
  2549. };
  2550. Buffer.prototype.slice = function slice (start, end) {
  2551. var len = this.length;
  2552. start = ~~start;
  2553. end = end === undefined ? len : ~~end;
  2554. if (start < 0) {
  2555. start += len;
  2556. if (start < 0) start = 0;
  2557. } else if (start > len) {
  2558. start = len;
  2559. }
  2560. if (end < 0) {
  2561. end += len;
  2562. if (end < 0) end = 0;
  2563. } else if (end > len) {
  2564. end = len;
  2565. }
  2566. if (end < start) end = start;
  2567. var newBuf;
  2568. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2569. newBuf = this.subarray(start, end);
  2570. // Return an augmented `Uint8Array` instance
  2571. newBuf.__proto__ = Buffer.prototype;
  2572. } else {
  2573. var sliceLen = end - start;
  2574. newBuf = new Buffer(sliceLen, undefined);
  2575. for (var i = 0; i < sliceLen; ++i) {
  2576. newBuf[i] = this[i + start];
  2577. }
  2578. }
  2579. return newBuf
  2580. };
  2581. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2582. if (!start) start = 0;
  2583. if (!end && end !== 0) end = this.length;
  2584. if (targetStart >= target.length) targetStart = target.length;
  2585. if (!targetStart) targetStart = 0;
  2586. if (end > 0 && end < start) end = start;
  2587. // Copy 0 bytes; we're done
  2588. if (end === start) return 0
  2589. if (target.length === 0 || this.length === 0) return 0
  2590. // Fatal error conditions
  2591. if (targetStart < 0) {
  2592. throw new RangeError('targetStart out of bounds')
  2593. }
  2594. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2595. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2596. // Are we oob?
  2597. if (end > this.length) end = this.length;
  2598. if (target.length - targetStart < end - start) {
  2599. end = target.length - targetStart + start;
  2600. }
  2601. var len = end - start;
  2602. var i;
  2603. if (this === target && start < targetStart && targetStart < end) {
  2604. // descending copy from end
  2605. for (i = len - 1; i >= 0; --i) {
  2606. target[i + targetStart] = this[i + start];
  2607. }
  2608. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2609. // ascending copy from start
  2610. for (i = 0; i < len; ++i) {
  2611. target[i + targetStart] = this[i + start];
  2612. }
  2613. } else {
  2614. Uint8Array.prototype.set.call(
  2615. target,
  2616. this.subarray(start, start + len),
  2617. targetStart
  2618. );
  2619. }
  2620. return len
  2621. };
  2622. Buffer.prototype.fill = function fill (val, start, end) {
  2623. // Handle string cases:
  2624. if (typeof val === 'string') {
  2625. if (typeof start === 'string') {
  2626. start = 0;
  2627. end = this.length;
  2628. } else if (typeof end === 'string') {
  2629. end = this.length;
  2630. }
  2631. if (val.length === 1) {
  2632. var code = val.charCodeAt(0);
  2633. if (code < 256) {
  2634. val = code;
  2635. }
  2636. }
  2637. } else if (typeof val === 'number') {
  2638. val = val & 255;
  2639. }
  2640. // Invalid ranges are not set to a default, so can range check early.
  2641. if (start < 0 || this.length < start || this.length < end) {
  2642. throw new RangeError('Out of range index')
  2643. }
  2644. if (end <= start) {
  2645. return this
  2646. }
  2647. start = start >>> 0;
  2648. end = end === undefined ? this.length : end >>> 0;
  2649. if (!val) val = 0;
  2650. var i;
  2651. if (typeof val === 'number') {
  2652. for (i = start; i < end; ++i) {
  2653. this[i] = val;
  2654. }
  2655. } else {
  2656. var bytes = Buffer.isBuffer(val)
  2657. ? val
  2658. : new Buffer(val);
  2659. var len = bytes.length;
  2660. for (i = 0; i < end - start; ++i) {
  2661. this[i + start] = bytes[i % len];
  2662. }
  2663. }
  2664. return this
  2665. };
  2666. Buffer.concat = function concat (list, length) {
  2667. if (!isArray(list)) {
  2668. throw new TypeError('"list" argument must be an Array of Buffers')
  2669. }
  2670. if (list.length === 0) {
  2671. return createBuffer(null, 0)
  2672. }
  2673. var i;
  2674. if (length === undefined) {
  2675. length = 0;
  2676. for (i = 0; i < list.length; ++i) {
  2677. length += list[i].length;
  2678. }
  2679. }
  2680. var buffer = allocUnsafe(null, length);
  2681. var pos = 0;
  2682. for (i = 0; i < list.length; ++i) {
  2683. var buf = list[i];
  2684. if (!Buffer.isBuffer(buf)) {
  2685. throw new TypeError('"list" argument must be an Array of Buffers')
  2686. }
  2687. buf.copy(buffer, pos);
  2688. pos += buf.length;
  2689. }
  2690. return buffer
  2691. };
  2692. Buffer.byteLength = byteLength;
  2693. Buffer.prototype._isBuffer = true;
  2694. Buffer.isBuffer = function isBuffer (b) {
  2695. return !!(b != null && b._isBuffer)
  2696. };
  2697. module.exports.alloc = function (size) {
  2698. var buffer = new Buffer(size);
  2699. buffer.fill(0);
  2700. return buffer
  2701. };
  2702. module.exports.from = function (data) {
  2703. return new Buffer(data)
  2704. };
  2705. },{"isarray":33}],29:[function(require,module,exports){
  2706. exports.byteLength = byteLength;
  2707. exports.toByteArray = toByteArray;
  2708. exports.fromByteArray = fromByteArray;
  2709. var lookup = [];
  2710. var revLookup = [];
  2711. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
  2712. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  2713. for (var i = 0, len = code.length; i < len; ++i) {
  2714. lookup[i] = code[i];
  2715. revLookup[code.charCodeAt(i)] = i;
  2716. }
  2717. // Support decoding URL-safe base64 strings, as Node.js does.
  2718. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2719. revLookup['-'.charCodeAt(0)] = 62;
  2720. revLookup['_'.charCodeAt(0)] = 63;
  2721. function getLens (b64) {
  2722. var len = b64.length;
  2723. if (len % 4 > 0) {
  2724. throw new Error('Invalid string. Length must be a multiple of 4')
  2725. }
  2726. // Trim off extra bytes after placeholder bytes are found
  2727. // See: https://github.com/beatgammit/base64-js/issues/42
  2728. var validLen = b64.indexOf('=');
  2729. if (validLen === -1) validLen = len;
  2730. var placeHoldersLen = validLen === len
  2731. ? 0
  2732. : 4 - (validLen % 4);
  2733. return [validLen, placeHoldersLen]
  2734. }
  2735. // base64 is 4/3 + up to two characters of the original data
  2736. function byteLength (b64) {
  2737. var lens = getLens(b64);
  2738. var validLen = lens[0];
  2739. var placeHoldersLen = lens[1];
  2740. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2741. }
  2742. function _byteLength (b64, validLen, placeHoldersLen) {
  2743. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2744. }
  2745. function toByteArray (b64) {
  2746. var tmp;
  2747. var lens = getLens(b64);
  2748. var validLen = lens[0];
  2749. var placeHoldersLen = lens[1];
  2750. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
  2751. var curByte = 0;
  2752. // if there are placeholders, only get up to the last complete 4 chars
  2753. var len = placeHoldersLen > 0
  2754. ? validLen - 4
  2755. : validLen;
  2756. var i;
  2757. for (i = 0; i < len; i += 4) {
  2758. tmp =
  2759. (revLookup[b64.charCodeAt(i)] << 18) |
  2760. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2761. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2762. revLookup[b64.charCodeAt(i + 3)];
  2763. arr[curByte++] = (tmp >> 16) & 0xFF;
  2764. arr[curByte++] = (tmp >> 8) & 0xFF;
  2765. arr[curByte++] = tmp & 0xFF;
  2766. }
  2767. if (placeHoldersLen === 2) {
  2768. tmp =
  2769. (revLookup[b64.charCodeAt(i)] << 2) |
  2770. (revLookup[b64.charCodeAt(i + 1)] >> 4);
  2771. arr[curByte++] = tmp & 0xFF;
  2772. }
  2773. if (placeHoldersLen === 1) {
  2774. tmp =
  2775. (revLookup[b64.charCodeAt(i)] << 10) |
  2776. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2777. (revLookup[b64.charCodeAt(i + 2)] >> 2);
  2778. arr[curByte++] = (tmp >> 8) & 0xFF;
  2779. arr[curByte++] = tmp & 0xFF;
  2780. }
  2781. return arr
  2782. }
  2783. function tripletToBase64 (num) {
  2784. return lookup[num >> 18 & 0x3F] +
  2785. lookup[num >> 12 & 0x3F] +
  2786. lookup[num >> 6 & 0x3F] +
  2787. lookup[num & 0x3F]
  2788. }
  2789. function encodeChunk (uint8, start, end) {
  2790. var tmp;
  2791. var output = [];
  2792. for (var i = start; i < end; i += 3) {
  2793. tmp =
  2794. ((uint8[i] << 16) & 0xFF0000) +
  2795. ((uint8[i + 1] << 8) & 0xFF00) +
  2796. (uint8[i + 2] & 0xFF);
  2797. output.push(tripletToBase64(tmp));
  2798. }
  2799. return output.join('')
  2800. }
  2801. function fromByteArray (uint8) {
  2802. var tmp;
  2803. var len = uint8.length;
  2804. var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
  2805. var parts = [];
  2806. var maxChunkLength = 16383; // must be multiple of 3
  2807. // go through the array every three bytes, we'll deal with trailing stuff later
  2808. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2809. parts.push(encodeChunk(
  2810. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  2811. ));
  2812. }
  2813. // pad the end with zeros, but make sure to not forget the extra bytes
  2814. if (extraBytes === 1) {
  2815. tmp = uint8[len - 1];
  2816. parts.push(
  2817. lookup[tmp >> 2] +
  2818. lookup[(tmp << 4) & 0x3F] +
  2819. '=='
  2820. );
  2821. } else if (extraBytes === 2) {
  2822. tmp = (uint8[len - 2] << 8) + uint8[len - 1];
  2823. parts.push(
  2824. lookup[tmp >> 10] +
  2825. lookup[(tmp >> 4) & 0x3F] +
  2826. lookup[(tmp << 2) & 0x3F] +
  2827. '='
  2828. );
  2829. }
  2830. return parts.join('')
  2831. }
  2832. },{}],30:[function(require,module,exports){
  2833. var base64 = require('base64-js');
  2834. var ieee754 = require('ieee754');
  2835. var customInspectSymbol =
  2836. (typeof Symbol === 'function' && typeof Symbol.for === 'function')
  2837. ? Symbol.for('nodejs.util.inspect.custom')
  2838. : null;
  2839. exports.Buffer = Buffer;
  2840. exports.SlowBuffer = SlowBuffer;
  2841. exports.INSPECT_MAX_BYTES = 50;
  2842. var K_MAX_LENGTH = 0x7fffffff;
  2843. exports.kMaxLength = K_MAX_LENGTH;
  2844. /**
  2845. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2846. * === true Use Uint8Array implementation (fastest)
  2847. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2848. * implementation (most compatible, even IE6)
  2849. *
  2850. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2851. * Opera 11.6+, iOS 4.2+.
  2852. *
  2853. * We report that the browser does not support typed arrays if the are not subclassable
  2854. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2855. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2856. * for __proto__ and has a buggy typed array implementation.
  2857. */
  2858. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
  2859. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2860. typeof console.error === 'function') {
  2861. console.error(
  2862. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2863. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2864. );
  2865. }
  2866. function typedArraySupport () {
  2867. // Can typed array instances can be augmented?
  2868. try {
  2869. var arr = new Uint8Array(1);
  2870. var proto = { foo: function () { return 42 } };
  2871. Object.setPrototypeOf(proto, Uint8Array.prototype);
  2872. Object.setPrototypeOf(arr, proto);
  2873. return arr.foo() === 42
  2874. } catch (e) {
  2875. return false
  2876. }
  2877. }
  2878. Object.defineProperty(Buffer.prototype, 'parent', {
  2879. enumerable: true,
  2880. get: function () {
  2881. if (!Buffer.isBuffer(this)) return undefined
  2882. return this.buffer
  2883. }
  2884. });
  2885. Object.defineProperty(Buffer.prototype, 'offset', {
  2886. enumerable: true,
  2887. get: function () {
  2888. if (!Buffer.isBuffer(this)) return undefined
  2889. return this.byteOffset
  2890. }
  2891. });
  2892. function createBuffer (length) {
  2893. if (length > K_MAX_LENGTH) {
  2894. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2895. }
  2896. // Return an augmented `Uint8Array` instance
  2897. var buf = new Uint8Array(length);
  2898. Object.setPrototypeOf(buf, Buffer.prototype);
  2899. return buf
  2900. }
  2901. /**
  2902. * The Buffer constructor returns instances of `Uint8Array` that have their
  2903. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2904. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2905. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2906. * returns a single octet.
  2907. *
  2908. * The `Uint8Array` prototype remains unmodified.
  2909. */
  2910. function Buffer (arg, encodingOrOffset, length) {
  2911. // Common case.
  2912. if (typeof arg === 'number') {
  2913. if (typeof encodingOrOffset === 'string') {
  2914. throw new TypeError(
  2915. 'The "string" argument must be of type string. Received type number'
  2916. )
  2917. }
  2918. return allocUnsafe(arg)
  2919. }
  2920. return from(arg, encodingOrOffset, length)
  2921. }
  2922. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2923. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2924. Buffer[Symbol.species] === Buffer) {
  2925. Object.defineProperty(Buffer, Symbol.species, {
  2926. value: null,
  2927. configurable: true,
  2928. enumerable: false,
  2929. writable: false
  2930. });
  2931. }
  2932. Buffer.poolSize = 8192; // not used by this implementation
  2933. function from (value, encodingOrOffset, length) {
  2934. if (typeof value === 'string') {
  2935. return fromString(value, encodingOrOffset)
  2936. }
  2937. if (ArrayBuffer.isView(value)) {
  2938. return fromArrayLike(value)
  2939. }
  2940. if (value == null) {
  2941. throw new TypeError(
  2942. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2943. 'or Array-like Object. Received type ' + (typeof value)
  2944. )
  2945. }
  2946. if (isInstance(value, ArrayBuffer) ||
  2947. (value && isInstance(value.buffer, ArrayBuffer))) {
  2948. return fromArrayBuffer(value, encodingOrOffset, length)
  2949. }
  2950. if (typeof value === 'number') {
  2951. throw new TypeError(
  2952. 'The "value" argument must not be of type number. Received type number'
  2953. )
  2954. }
  2955. var valueOf = value.valueOf && value.valueOf();
  2956. if (valueOf != null && valueOf !== value) {
  2957. return Buffer.from(valueOf, encodingOrOffset, length)
  2958. }
  2959. var b = fromObject(value);
  2960. if (b) return b
  2961. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2962. typeof value[Symbol.toPrimitive] === 'function') {
  2963. return Buffer.from(
  2964. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2965. )
  2966. }
  2967. throw new TypeError(
  2968. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2969. 'or Array-like Object. Received type ' + (typeof value)
  2970. )
  2971. }
  2972. /**
  2973. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2974. * if value is a number.
  2975. * Buffer.from(str[, encoding])
  2976. * Buffer.from(array)
  2977. * Buffer.from(buffer)
  2978. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2979. **/
  2980. Buffer.from = function (value, encodingOrOffset, length) {
  2981. return from(value, encodingOrOffset, length)
  2982. };
  2983. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2984. // https://github.com/feross/buffer/pull/148
  2985. Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
  2986. Object.setPrototypeOf(Buffer, Uint8Array);
  2987. function assertSize (size) {
  2988. if (typeof size !== 'number') {
  2989. throw new TypeError('"size" argument must be of type number')
  2990. } else if (size < 0) {
  2991. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2992. }
  2993. }
  2994. function alloc (size, fill, encoding) {
  2995. assertSize(size);
  2996. if (size <= 0) {
  2997. return createBuffer(size)
  2998. }
  2999. if (fill !== undefined) {
  3000. // Only pay attention to encoding if it's a string. This
  3001. // prevents accidentally sending in a number that would
  3002. // be interpretted as a start offset.
  3003. return typeof encoding === 'string'
  3004. ? createBuffer(size).fill(fill, encoding)
  3005. : createBuffer(size).fill(fill)
  3006. }
  3007. return createBuffer(size)
  3008. }
  3009. /**
  3010. * Creates a new filled Buffer instance.
  3011. * alloc(size[, fill[, encoding]])
  3012. **/
  3013. Buffer.alloc = function (size, fill, encoding) {
  3014. return alloc(size, fill, encoding)
  3015. };
  3016. function allocUnsafe (size) {
  3017. assertSize(size);
  3018. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  3019. }
  3020. /**
  3021. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  3022. * */
  3023. Buffer.allocUnsafe = function (size) {
  3024. return allocUnsafe(size)
  3025. };
  3026. /**
  3027. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  3028. */
  3029. Buffer.allocUnsafeSlow = function (size) {
  3030. return allocUnsafe(size)
  3031. };
  3032. function fromString (string, encoding) {
  3033. if (typeof encoding !== 'string' || encoding === '') {
  3034. encoding = 'utf8';
  3035. }
  3036. if (!Buffer.isEncoding(encoding)) {
  3037. throw new TypeError('Unknown encoding: ' + encoding)
  3038. }
  3039. var length = byteLength(string, encoding) | 0;
  3040. var buf = createBuffer(length);
  3041. var actual = buf.write(string, encoding);
  3042. if (actual !== length) {
  3043. // Writing a hex string, for example, that contains invalid characters will
  3044. // cause everything after the first invalid character to be ignored. (e.g.
  3045. // 'abxxcd' will be treated as 'ab')
  3046. buf = buf.slice(0, actual);
  3047. }
  3048. return buf
  3049. }
  3050. function fromArrayLike (array) {
  3051. var length = array.length < 0 ? 0 : checked(array.length) | 0;
  3052. var buf = createBuffer(length);
  3053. for (var i = 0; i < length; i += 1) {
  3054. buf[i] = array[i] & 255;
  3055. }
  3056. return buf
  3057. }
  3058. function fromArrayBuffer (array, byteOffset, length) {
  3059. if (byteOffset < 0 || array.byteLength < byteOffset) {
  3060. throw new RangeError('"offset" is outside of buffer bounds')
  3061. }
  3062. if (array.byteLength < byteOffset + (length || 0)) {
  3063. throw new RangeError('"length" is outside of buffer bounds')
  3064. }
  3065. var buf;
  3066. if (byteOffset === undefined && length === undefined) {
  3067. buf = new Uint8Array(array);
  3068. } else if (length === undefined) {
  3069. buf = new Uint8Array(array, byteOffset);
  3070. } else {
  3071. buf = new Uint8Array(array, byteOffset, length);
  3072. }
  3073. // Return an augmented `Uint8Array` instance
  3074. Object.setPrototypeOf(buf, Buffer.prototype);
  3075. return buf
  3076. }
  3077. function fromObject (obj) {
  3078. if (Buffer.isBuffer(obj)) {
  3079. var len = checked(obj.length) | 0;
  3080. var buf = createBuffer(len);
  3081. if (buf.length === 0) {
  3082. return buf
  3083. }
  3084. obj.copy(buf, 0, 0, len);
  3085. return buf
  3086. }
  3087. if (obj.length !== undefined) {
  3088. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  3089. return createBuffer(0)
  3090. }
  3091. return fromArrayLike(obj)
  3092. }
  3093. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  3094. return fromArrayLike(obj.data)
  3095. }
  3096. }
  3097. function checked (length) {
  3098. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  3099. // length is NaN (which is otherwise coerced to zero.)
  3100. if (length >= K_MAX_LENGTH) {
  3101. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  3102. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  3103. }
  3104. return length | 0
  3105. }
  3106. function SlowBuffer (length) {
  3107. if (+length != length) { // eslint-disable-line eqeqeq
  3108. length = 0;
  3109. }
  3110. return Buffer.alloc(+length)
  3111. }
  3112. Buffer.isBuffer = function isBuffer (b) {
  3113. return b != null && b._isBuffer === true &&
  3114. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  3115. };
  3116. Buffer.compare = function compare (a, b) {
  3117. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
  3118. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
  3119. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  3120. throw new TypeError(
  3121. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  3122. )
  3123. }
  3124. if (a === b) return 0
  3125. var x = a.length;
  3126. var y = b.length;
  3127. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  3128. if (a[i] !== b[i]) {
  3129. x = a[i];
  3130. y = b[i];
  3131. break
  3132. }
  3133. }
  3134. if (x < y) return -1
  3135. if (y < x) return 1
  3136. return 0
  3137. };
  3138. Buffer.isEncoding = function isEncoding (encoding) {
  3139. switch (String(encoding).toLowerCase()) {
  3140. case 'hex':
  3141. case 'utf8':
  3142. case 'utf-8':
  3143. case 'ascii':
  3144. case 'latin1':
  3145. case 'binary':
  3146. case 'base64':
  3147. case 'ucs2':
  3148. case 'ucs-2':
  3149. case 'utf16le':
  3150. case 'utf-16le':
  3151. return true
  3152. default:
  3153. return false
  3154. }
  3155. };
  3156. Buffer.concat = function concat (list, length) {
  3157. if (!Array.isArray(list)) {
  3158. throw new TypeError('"list" argument must be an Array of Buffers')
  3159. }
  3160. if (list.length === 0) {
  3161. return Buffer.alloc(0)
  3162. }
  3163. var i;
  3164. if (length === undefined) {
  3165. length = 0;
  3166. for (i = 0; i < list.length; ++i) {
  3167. length += list[i].length;
  3168. }
  3169. }
  3170. var buffer = Buffer.allocUnsafe(length);
  3171. var pos = 0;
  3172. for (i = 0; i < list.length; ++i) {
  3173. var buf = list[i];
  3174. if (isInstance(buf, Uint8Array)) {
  3175. buf = Buffer.from(buf);
  3176. }
  3177. if (!Buffer.isBuffer(buf)) {
  3178. throw new TypeError('"list" argument must be an Array of Buffers')
  3179. }
  3180. buf.copy(buffer, pos);
  3181. pos += buf.length;
  3182. }
  3183. return buffer
  3184. };
  3185. function byteLength (string, encoding) {
  3186. if (Buffer.isBuffer(string)) {
  3187. return string.length
  3188. }
  3189. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  3190. return string.byteLength
  3191. }
  3192. if (typeof string !== 'string') {
  3193. throw new TypeError(
  3194. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  3195. 'Received type ' + typeof string
  3196. )
  3197. }
  3198. var len = string.length;
  3199. var mustMatch = (arguments.length > 2 && arguments[2] === true);
  3200. if (!mustMatch && len === 0) return 0
  3201. // Use a for loop to avoid recursion
  3202. var loweredCase = false;
  3203. for (;;) {
  3204. switch (encoding) {
  3205. case 'ascii':
  3206. case 'latin1':
  3207. case 'binary':
  3208. return len
  3209. case 'utf8':
  3210. case 'utf-8':
  3211. return utf8ToBytes(string).length
  3212. case 'ucs2':
  3213. case 'ucs-2':
  3214. case 'utf16le':
  3215. case 'utf-16le':
  3216. return len * 2
  3217. case 'hex':
  3218. return len >>> 1
  3219. case 'base64':
  3220. return base64ToBytes(string).length
  3221. default:
  3222. if (loweredCase) {
  3223. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  3224. }
  3225. encoding = ('' + encoding).toLowerCase();
  3226. loweredCase = true;
  3227. }
  3228. }
  3229. }
  3230. Buffer.byteLength = byteLength;
  3231. function slowToString (encoding, start, end) {
  3232. var loweredCase = false;
  3233. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  3234. // property of a typed array.
  3235. // This behaves neither like String nor Uint8Array in that we set start/end
  3236. // to their upper/lower bounds if the value passed is out of range.
  3237. // undefined is handled specially as per ECMA-262 6th Edition,
  3238. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  3239. if (start === undefined || start < 0) {
  3240. start = 0;
  3241. }
  3242. // Return early if start > this.length. Done here to prevent potential uint32
  3243. // coercion fail below.
  3244. if (start > this.length) {
  3245. return ''
  3246. }
  3247. if (end === undefined || end > this.length) {
  3248. end = this.length;
  3249. }
  3250. if (end <= 0) {
  3251. return ''
  3252. }
  3253. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  3254. end >>>= 0;
  3255. start >>>= 0;
  3256. if (end <= start) {
  3257. return ''
  3258. }
  3259. if (!encoding) encoding = 'utf8';
  3260. while (true) {
  3261. switch (encoding) {
  3262. case 'hex':
  3263. return hexSlice(this, start, end)
  3264. case 'utf8':
  3265. case 'utf-8':
  3266. return utf8Slice(this, start, end)
  3267. case 'ascii':
  3268. return asciiSlice(this, start, end)
  3269. case 'latin1':
  3270. case 'binary':
  3271. return latin1Slice(this, start, end)
  3272. case 'base64':
  3273. return base64Slice(this, start, end)
  3274. case 'ucs2':
  3275. case 'ucs-2':
  3276. case 'utf16le':
  3277. case 'utf-16le':
  3278. return utf16leSlice(this, start, end)
  3279. default:
  3280. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3281. encoding = (encoding + '').toLowerCase();
  3282. loweredCase = true;
  3283. }
  3284. }
  3285. }
  3286. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  3287. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  3288. // reliably in a browserify context because there could be multiple different
  3289. // copies of the 'buffer' package in use. This method works even for Buffer
  3290. // instances that were created from another copy of the `buffer` package.
  3291. // See: https://github.com/feross/buffer/issues/154
  3292. Buffer.prototype._isBuffer = true;
  3293. function swap (b, n, m) {
  3294. var i = b[n];
  3295. b[n] = b[m];
  3296. b[m] = i;
  3297. }
  3298. Buffer.prototype.swap16 = function swap16 () {
  3299. var len = this.length;
  3300. if (len % 2 !== 0) {
  3301. throw new RangeError('Buffer size must be a multiple of 16-bits')
  3302. }
  3303. for (var i = 0; i < len; i += 2) {
  3304. swap(this, i, i + 1);
  3305. }
  3306. return this
  3307. };
  3308. Buffer.prototype.swap32 = function swap32 () {
  3309. var len = this.length;
  3310. if (len % 4 !== 0) {
  3311. throw new RangeError('Buffer size must be a multiple of 32-bits')
  3312. }
  3313. for (var i = 0; i < len; i += 4) {
  3314. swap(this, i, i + 3);
  3315. swap(this, i + 1, i + 2);
  3316. }
  3317. return this
  3318. };
  3319. Buffer.prototype.swap64 = function swap64 () {
  3320. var len = this.length;
  3321. if (len % 8 !== 0) {
  3322. throw new RangeError('Buffer size must be a multiple of 64-bits')
  3323. }
  3324. for (var i = 0; i < len; i += 8) {
  3325. swap(this, i, i + 7);
  3326. swap(this, i + 1, i + 6);
  3327. swap(this, i + 2, i + 5);
  3328. swap(this, i + 3, i + 4);
  3329. }
  3330. return this
  3331. };
  3332. Buffer.prototype.toString = function toString () {
  3333. var length = this.length;
  3334. if (length === 0) return ''
  3335. if (arguments.length === 0) return utf8Slice(this, 0, length)
  3336. return slowToString.apply(this, arguments)
  3337. };
  3338. Buffer.prototype.toLocaleString = Buffer.prototype.toString;
  3339. Buffer.prototype.equals = function equals (b) {
  3340. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  3341. if (this === b) return true
  3342. return Buffer.compare(this, b) === 0
  3343. };
  3344. Buffer.prototype.inspect = function inspect () {
  3345. var str = '';
  3346. var max = exports.INSPECT_MAX_BYTES;
  3347. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
  3348. if (this.length > max) str += ' ... ';
  3349. return '<Buffer ' + str + '>'
  3350. };
  3351. if (customInspectSymbol) {
  3352. Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
  3353. }
  3354. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  3355. if (isInstance(target, Uint8Array)) {
  3356. target = Buffer.from(target, target.offset, target.byteLength);
  3357. }
  3358. if (!Buffer.isBuffer(target)) {
  3359. throw new TypeError(
  3360. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  3361. 'Received type ' + (typeof target)
  3362. )
  3363. }
  3364. if (start === undefined) {
  3365. start = 0;
  3366. }
  3367. if (end === undefined) {
  3368. end = target ? target.length : 0;
  3369. }
  3370. if (thisStart === undefined) {
  3371. thisStart = 0;
  3372. }
  3373. if (thisEnd === undefined) {
  3374. thisEnd = this.length;
  3375. }
  3376. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  3377. throw new RangeError('out of range index')
  3378. }
  3379. if (thisStart >= thisEnd && start >= end) {
  3380. return 0
  3381. }
  3382. if (thisStart >= thisEnd) {
  3383. return -1
  3384. }
  3385. if (start >= end) {
  3386. return 1
  3387. }
  3388. start >>>= 0;
  3389. end >>>= 0;
  3390. thisStart >>>= 0;
  3391. thisEnd >>>= 0;
  3392. if (this === target) return 0
  3393. var x = thisEnd - thisStart;
  3394. var y = end - start;
  3395. var len = Math.min(x, y);
  3396. var thisCopy = this.slice(thisStart, thisEnd);
  3397. var targetCopy = target.slice(start, end);
  3398. for (var i = 0; i < len; ++i) {
  3399. if (thisCopy[i] !== targetCopy[i]) {
  3400. x = thisCopy[i];
  3401. y = targetCopy[i];
  3402. break
  3403. }
  3404. }
  3405. if (x < y) return -1
  3406. if (y < x) return 1
  3407. return 0
  3408. };
  3409. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  3410. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  3411. //
  3412. // Arguments:
  3413. // - buffer - a Buffer to search
  3414. // - val - a string, Buffer, or number
  3415. // - byteOffset - an index into `buffer`; will be clamped to an int32
  3416. // - encoding - an optional encoding, relevant is val is a string
  3417. // - dir - true for indexOf, false for lastIndexOf
  3418. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  3419. // Empty buffer means no match
  3420. if (buffer.length === 0) return -1
  3421. // Normalize byteOffset
  3422. if (typeof byteOffset === 'string') {
  3423. encoding = byteOffset;
  3424. byteOffset = 0;
  3425. } else if (byteOffset > 0x7fffffff) {
  3426. byteOffset = 0x7fffffff;
  3427. } else if (byteOffset < -0x80000000) {
  3428. byteOffset = -0x80000000;
  3429. }
  3430. byteOffset = +byteOffset; // Coerce to Number.
  3431. if (numberIsNaN(byteOffset)) {
  3432. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  3433. byteOffset = dir ? 0 : (buffer.length - 1);
  3434. }
  3435. // Normalize byteOffset: negative offsets start from the end of the buffer
  3436. if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
  3437. if (byteOffset >= buffer.length) {
  3438. if (dir) return -1
  3439. else byteOffset = buffer.length - 1;
  3440. } else if (byteOffset < 0) {
  3441. if (dir) byteOffset = 0;
  3442. else return -1
  3443. }
  3444. // Normalize val
  3445. if (typeof val === 'string') {
  3446. val = Buffer.from(val, encoding);
  3447. }
  3448. // Finally, search either indexOf (if dir is true) or lastIndexOf
  3449. if (Buffer.isBuffer(val)) {
  3450. // Special case: looking for empty string/buffer always fails
  3451. if (val.length === 0) {
  3452. return -1
  3453. }
  3454. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  3455. } else if (typeof val === 'number') {
  3456. val = val & 0xFF; // Search for a byte value [0-255]
  3457. if (typeof Uint8Array.prototype.indexOf === 'function') {
  3458. if (dir) {
  3459. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  3460. } else {
  3461. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  3462. }
  3463. }
  3464. return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
  3465. }
  3466. throw new TypeError('val must be string, number or Buffer')
  3467. }
  3468. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  3469. var indexSize = 1;
  3470. var arrLength = arr.length;
  3471. var valLength = val.length;
  3472. if (encoding !== undefined) {
  3473. encoding = String(encoding).toLowerCase();
  3474. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  3475. encoding === 'utf16le' || encoding === 'utf-16le') {
  3476. if (arr.length < 2 || val.length < 2) {
  3477. return -1
  3478. }
  3479. indexSize = 2;
  3480. arrLength /= 2;
  3481. valLength /= 2;
  3482. byteOffset /= 2;
  3483. }
  3484. }
  3485. function read (buf, i) {
  3486. if (indexSize === 1) {
  3487. return buf[i]
  3488. } else {
  3489. return buf.readUInt16BE(i * indexSize)
  3490. }
  3491. }
  3492. var i;
  3493. if (dir) {
  3494. var foundIndex = -1;
  3495. for (i = byteOffset; i < arrLength; i++) {
  3496. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  3497. if (foundIndex === -1) foundIndex = i;
  3498. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  3499. } else {
  3500. if (foundIndex !== -1) i -= i - foundIndex;
  3501. foundIndex = -1;
  3502. }
  3503. }
  3504. } else {
  3505. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
  3506. for (i = byteOffset; i >= 0; i--) {
  3507. var found = true;
  3508. for (var j = 0; j < valLength; j++) {
  3509. if (read(arr, i + j) !== read(val, j)) {
  3510. found = false;
  3511. break
  3512. }
  3513. }
  3514. if (found) return i
  3515. }
  3516. }
  3517. return -1
  3518. }
  3519. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  3520. return this.indexOf(val, byteOffset, encoding) !== -1
  3521. };
  3522. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  3523. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  3524. };
  3525. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  3526. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  3527. };
  3528. function hexWrite (buf, string, offset, length) {
  3529. offset = Number(offset) || 0;
  3530. var remaining = buf.length - offset;
  3531. if (!length) {
  3532. length = remaining;
  3533. } else {
  3534. length = Number(length);
  3535. if (length > remaining) {
  3536. length = remaining;
  3537. }
  3538. }
  3539. var strLen = string.length;
  3540. if (length > strLen / 2) {
  3541. length = strLen / 2;
  3542. }
  3543. for (var i = 0; i < length; ++i) {
  3544. var parsed = parseInt(string.substr(i * 2, 2), 16);
  3545. if (numberIsNaN(parsed)) return i
  3546. buf[offset + i] = parsed;
  3547. }
  3548. return i
  3549. }
  3550. function utf8Write (buf, string, offset, length) {
  3551. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3552. }
  3553. function asciiWrite (buf, string, offset, length) {
  3554. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3555. }
  3556. function latin1Write (buf, string, offset, length) {
  3557. return asciiWrite(buf, string, offset, length)
  3558. }
  3559. function base64Write (buf, string, offset, length) {
  3560. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3561. }
  3562. function ucs2Write (buf, string, offset, length) {
  3563. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3564. }
  3565. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3566. // Buffer#write(string)
  3567. if (offset === undefined) {
  3568. encoding = 'utf8';
  3569. length = this.length;
  3570. offset = 0;
  3571. // Buffer#write(string, encoding)
  3572. } else if (length === undefined && typeof offset === 'string') {
  3573. encoding = offset;
  3574. length = this.length;
  3575. offset = 0;
  3576. // Buffer#write(string, offset[, length][, encoding])
  3577. } else if (isFinite(offset)) {
  3578. offset = offset >>> 0;
  3579. if (isFinite(length)) {
  3580. length = length >>> 0;
  3581. if (encoding === undefined) encoding = 'utf8';
  3582. } else {
  3583. encoding = length;
  3584. length = undefined;
  3585. }
  3586. } else {
  3587. throw new Error(
  3588. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3589. )
  3590. }
  3591. var remaining = this.length - offset;
  3592. if (length === undefined || length > remaining) length = remaining;
  3593. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3594. throw new RangeError('Attempt to write outside buffer bounds')
  3595. }
  3596. if (!encoding) encoding = 'utf8';
  3597. var loweredCase = false;
  3598. for (;;) {
  3599. switch (encoding) {
  3600. case 'hex':
  3601. return hexWrite(this, string, offset, length)
  3602. case 'utf8':
  3603. case 'utf-8':
  3604. return utf8Write(this, string, offset, length)
  3605. case 'ascii':
  3606. return asciiWrite(this, string, offset, length)
  3607. case 'latin1':
  3608. case 'binary':
  3609. return latin1Write(this, string, offset, length)
  3610. case 'base64':
  3611. // Warning: maxLength not taken into account in base64Write
  3612. return base64Write(this, string, offset, length)
  3613. case 'ucs2':
  3614. case 'ucs-2':
  3615. case 'utf16le':
  3616. case 'utf-16le':
  3617. return ucs2Write(this, string, offset, length)
  3618. default:
  3619. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3620. encoding = ('' + encoding).toLowerCase();
  3621. loweredCase = true;
  3622. }
  3623. }
  3624. };
  3625. Buffer.prototype.toJSON = function toJSON () {
  3626. return {
  3627. type: 'Buffer',
  3628. data: Array.prototype.slice.call(this._arr || this, 0)
  3629. }
  3630. };
  3631. function base64Slice (buf, start, end) {
  3632. if (start === 0 && end === buf.length) {
  3633. return base64.fromByteArray(buf)
  3634. } else {
  3635. return base64.fromByteArray(buf.slice(start, end))
  3636. }
  3637. }
  3638. function utf8Slice (buf, start, end) {
  3639. end = Math.min(buf.length, end);
  3640. var res = [];
  3641. var i = start;
  3642. while (i < end) {
  3643. var firstByte = buf[i];
  3644. var codePoint = null;
  3645. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3646. : (firstByte > 0xDF) ? 3
  3647. : (firstByte > 0xBF) ? 2
  3648. : 1;
  3649. if (i + bytesPerSequence <= end) {
  3650. var secondByte, thirdByte, fourthByte, tempCodePoint;
  3651. switch (bytesPerSequence) {
  3652. case 1:
  3653. if (firstByte < 0x80) {
  3654. codePoint = firstByte;
  3655. }
  3656. break
  3657. case 2:
  3658. secondByte = buf[i + 1];
  3659. if ((secondByte & 0xC0) === 0x80) {
  3660. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
  3661. if (tempCodePoint > 0x7F) {
  3662. codePoint = tempCodePoint;
  3663. }
  3664. }
  3665. break
  3666. case 3:
  3667. secondByte = buf[i + 1];
  3668. thirdByte = buf[i + 2];
  3669. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3670. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
  3671. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3672. codePoint = tempCodePoint;
  3673. }
  3674. }
  3675. break
  3676. case 4:
  3677. secondByte = buf[i + 1];
  3678. thirdByte = buf[i + 2];
  3679. fourthByte = buf[i + 3];
  3680. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3681. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
  3682. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3683. codePoint = tempCodePoint;
  3684. }
  3685. }
  3686. }
  3687. }
  3688. if (codePoint === null) {
  3689. // we did not generate a valid codePoint so insert a
  3690. // replacement char (U+FFFD) and advance only 1 byte
  3691. codePoint = 0xFFFD;
  3692. bytesPerSequence = 1;
  3693. } else if (codePoint > 0xFFFF) {
  3694. // encode to utf16 (surrogate pair dance)
  3695. codePoint -= 0x10000;
  3696. res.push(codePoint >>> 10 & 0x3FF | 0xD800);
  3697. codePoint = 0xDC00 | codePoint & 0x3FF;
  3698. }
  3699. res.push(codePoint);
  3700. i += bytesPerSequence;
  3701. }
  3702. return decodeCodePointsArray(res)
  3703. }
  3704. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3705. // the lowest limit is Chrome, with 0x10000 args.
  3706. // We go 1 magnitude less, for safety
  3707. var MAX_ARGUMENTS_LENGTH = 0x1000;
  3708. function decodeCodePointsArray (codePoints) {
  3709. var len = codePoints.length;
  3710. if (len <= MAX_ARGUMENTS_LENGTH) {
  3711. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3712. }
  3713. // Decode in chunks to avoid "call stack size exceeded".
  3714. var res = '';
  3715. var i = 0;
  3716. while (i < len) {
  3717. res += String.fromCharCode.apply(
  3718. String,
  3719. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3720. );
  3721. }
  3722. return res
  3723. }
  3724. function asciiSlice (buf, start, end) {
  3725. var ret = '';
  3726. end = Math.min(buf.length, end);
  3727. for (var i = start; i < end; ++i) {
  3728. ret += String.fromCharCode(buf[i] & 0x7F);
  3729. }
  3730. return ret
  3731. }
  3732. function latin1Slice (buf, start, end) {
  3733. var ret = '';
  3734. end = Math.min(buf.length, end);
  3735. for (var i = start; i < end; ++i) {
  3736. ret += String.fromCharCode(buf[i]);
  3737. }
  3738. return ret
  3739. }
  3740. function hexSlice (buf, start, end) {
  3741. var len = buf.length;
  3742. if (!start || start < 0) start = 0;
  3743. if (!end || end < 0 || end > len) end = len;
  3744. var out = '';
  3745. for (var i = start; i < end; ++i) {
  3746. out += hexSliceLookupTable[buf[i]];
  3747. }
  3748. return out
  3749. }
  3750. function utf16leSlice (buf, start, end) {
  3751. var bytes = buf.slice(start, end);
  3752. var res = '';
  3753. for (var i = 0; i < bytes.length; i += 2) {
  3754. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
  3755. }
  3756. return res
  3757. }
  3758. Buffer.prototype.slice = function slice (start, end) {
  3759. var len = this.length;
  3760. start = ~~start;
  3761. end = end === undefined ? len : ~~end;
  3762. if (start < 0) {
  3763. start += len;
  3764. if (start < 0) start = 0;
  3765. } else if (start > len) {
  3766. start = len;
  3767. }
  3768. if (end < 0) {
  3769. end += len;
  3770. if (end < 0) end = 0;
  3771. } else if (end > len) {
  3772. end = len;
  3773. }
  3774. if (end < start) end = start;
  3775. var newBuf = this.subarray(start, end);
  3776. // Return an augmented `Uint8Array` instance
  3777. Object.setPrototypeOf(newBuf, Buffer.prototype);
  3778. return newBuf
  3779. };
  3780. /*
  3781. * Need to make sure that buffer isn't trying to write out of bounds.
  3782. */
  3783. function checkOffset (offset, ext, length) {
  3784. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3785. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3786. }
  3787. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3788. offset = offset >>> 0;
  3789. byteLength = byteLength >>> 0;
  3790. if (!noAssert) checkOffset(offset, byteLength, this.length);
  3791. var val = this[offset];
  3792. var mul = 1;
  3793. var i = 0;
  3794. while (++i < byteLength && (mul *= 0x100)) {
  3795. val += this[offset + i] * mul;
  3796. }
  3797. return val
  3798. };
  3799. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3800. offset = offset >>> 0;
  3801. byteLength = byteLength >>> 0;
  3802. if (!noAssert) {
  3803. checkOffset(offset, byteLength, this.length);
  3804. }
  3805. var val = this[offset + --byteLength];
  3806. var mul = 1;
  3807. while (byteLength > 0 && (mul *= 0x100)) {
  3808. val += this[offset + --byteLength] * mul;
  3809. }
  3810. return val
  3811. };
  3812. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3813. offset = offset >>> 0;
  3814. if (!noAssert) checkOffset(offset, 1, this.length);
  3815. return this[offset]
  3816. };
  3817. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3818. offset = offset >>> 0;
  3819. if (!noAssert) checkOffset(offset, 2, this.length);
  3820. return this[offset] | (this[offset + 1] << 8)
  3821. };
  3822. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3823. offset = offset >>> 0;
  3824. if (!noAssert) checkOffset(offset, 2, this.length);
  3825. return (this[offset] << 8) | this[offset + 1]
  3826. };
  3827. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3828. offset = offset >>> 0;
  3829. if (!noAssert) checkOffset(offset, 4, this.length);
  3830. return ((this[offset]) |
  3831. (this[offset + 1] << 8) |
  3832. (this[offset + 2] << 16)) +
  3833. (this[offset + 3] * 0x1000000)
  3834. };
  3835. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3836. offset = offset >>> 0;
  3837. if (!noAssert) checkOffset(offset, 4, this.length);
  3838. return (this[offset] * 0x1000000) +
  3839. ((this[offset + 1] << 16) |
  3840. (this[offset + 2] << 8) |
  3841. this[offset + 3])
  3842. };
  3843. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3844. offset = offset >>> 0;
  3845. byteLength = byteLength >>> 0;
  3846. if (!noAssert) checkOffset(offset, byteLength, this.length);
  3847. var val = this[offset];
  3848. var mul = 1;
  3849. var i = 0;
  3850. while (++i < byteLength && (mul *= 0x100)) {
  3851. val += this[offset + i] * mul;
  3852. }
  3853. mul *= 0x80;
  3854. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  3855. return val
  3856. };
  3857. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3858. offset = offset >>> 0;
  3859. byteLength = byteLength >>> 0;
  3860. if (!noAssert) checkOffset(offset, byteLength, this.length);
  3861. var i = byteLength;
  3862. var mul = 1;
  3863. var val = this[offset + --i];
  3864. while (i > 0 && (mul *= 0x100)) {
  3865. val += this[offset + --i] * mul;
  3866. }
  3867. mul *= 0x80;
  3868. if (val >= mul) val -= Math.pow(2, 8 * byteLength);
  3869. return val
  3870. };
  3871. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3872. offset = offset >>> 0;
  3873. if (!noAssert) checkOffset(offset, 1, this.length);
  3874. if (!(this[offset] & 0x80)) return (this[offset])
  3875. return ((0xff - this[offset] + 1) * -1)
  3876. };
  3877. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3878. offset = offset >>> 0;
  3879. if (!noAssert) checkOffset(offset, 2, this.length);
  3880. var val = this[offset] | (this[offset + 1] << 8);
  3881. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3882. };
  3883. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3884. offset = offset >>> 0;
  3885. if (!noAssert) checkOffset(offset, 2, this.length);
  3886. var val = this[offset + 1] | (this[offset] << 8);
  3887. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3888. };
  3889. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3890. offset = offset >>> 0;
  3891. if (!noAssert) checkOffset(offset, 4, this.length);
  3892. return (this[offset]) |
  3893. (this[offset + 1] << 8) |
  3894. (this[offset + 2] << 16) |
  3895. (this[offset + 3] << 24)
  3896. };
  3897. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3898. offset = offset >>> 0;
  3899. if (!noAssert) checkOffset(offset, 4, this.length);
  3900. return (this[offset] << 24) |
  3901. (this[offset + 1] << 16) |
  3902. (this[offset + 2] << 8) |
  3903. (this[offset + 3])
  3904. };
  3905. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3906. offset = offset >>> 0;
  3907. if (!noAssert) checkOffset(offset, 4, this.length);
  3908. return ieee754.read(this, offset, true, 23, 4)
  3909. };
  3910. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3911. offset = offset >>> 0;
  3912. if (!noAssert) checkOffset(offset, 4, this.length);
  3913. return ieee754.read(this, offset, false, 23, 4)
  3914. };
  3915. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3916. offset = offset >>> 0;
  3917. if (!noAssert) checkOffset(offset, 8, this.length);
  3918. return ieee754.read(this, offset, true, 52, 8)
  3919. };
  3920. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3921. offset = offset >>> 0;
  3922. if (!noAssert) checkOffset(offset, 8, this.length);
  3923. return ieee754.read(this, offset, false, 52, 8)
  3924. };
  3925. function checkInt (buf, value, offset, ext, max, min) {
  3926. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3927. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3928. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3929. }
  3930. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3931. value = +value;
  3932. offset = offset >>> 0;
  3933. byteLength = byteLength >>> 0;
  3934. if (!noAssert) {
  3935. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  3936. checkInt(this, value, offset, byteLength, maxBytes, 0);
  3937. }
  3938. var mul = 1;
  3939. var i = 0;
  3940. this[offset] = value & 0xFF;
  3941. while (++i < byteLength && (mul *= 0x100)) {
  3942. this[offset + i] = (value / mul) & 0xFF;
  3943. }
  3944. return offset + byteLength
  3945. };
  3946. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3947. value = +value;
  3948. offset = offset >>> 0;
  3949. byteLength = byteLength >>> 0;
  3950. if (!noAssert) {
  3951. var maxBytes = Math.pow(2, 8 * byteLength) - 1;
  3952. checkInt(this, value, offset, byteLength, maxBytes, 0);
  3953. }
  3954. var i = byteLength - 1;
  3955. var mul = 1;
  3956. this[offset + i] = value & 0xFF;
  3957. while (--i >= 0 && (mul *= 0x100)) {
  3958. this[offset + i] = (value / mul) & 0xFF;
  3959. }
  3960. return offset + byteLength
  3961. };
  3962. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3963. value = +value;
  3964. offset = offset >>> 0;
  3965. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
  3966. this[offset] = (value & 0xff);
  3967. return offset + 1
  3968. };
  3969. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3970. value = +value;
  3971. offset = offset >>> 0;
  3972. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  3973. this[offset] = (value & 0xff);
  3974. this[offset + 1] = (value >>> 8);
  3975. return offset + 2
  3976. };
  3977. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3978. value = +value;
  3979. offset = offset >>> 0;
  3980. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
  3981. this[offset] = (value >>> 8);
  3982. this[offset + 1] = (value & 0xff);
  3983. return offset + 2
  3984. };
  3985. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3986. value = +value;
  3987. offset = offset >>> 0;
  3988. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  3989. this[offset + 3] = (value >>> 24);
  3990. this[offset + 2] = (value >>> 16);
  3991. this[offset + 1] = (value >>> 8);
  3992. this[offset] = (value & 0xff);
  3993. return offset + 4
  3994. };
  3995. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3996. value = +value;
  3997. offset = offset >>> 0;
  3998. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
  3999. this[offset] = (value >>> 24);
  4000. this[offset + 1] = (value >>> 16);
  4001. this[offset + 2] = (value >>> 8);
  4002. this[offset + 3] = (value & 0xff);
  4003. return offset + 4
  4004. };
  4005. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  4006. value = +value;
  4007. offset = offset >>> 0;
  4008. if (!noAssert) {
  4009. var limit = Math.pow(2, (8 * byteLength) - 1);
  4010. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  4011. }
  4012. var i = 0;
  4013. var mul = 1;
  4014. var sub = 0;
  4015. this[offset] = value & 0xFF;
  4016. while (++i < byteLength && (mul *= 0x100)) {
  4017. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  4018. sub = 1;
  4019. }
  4020. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  4021. }
  4022. return offset + byteLength
  4023. };
  4024. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  4025. value = +value;
  4026. offset = offset >>> 0;
  4027. if (!noAssert) {
  4028. var limit = Math.pow(2, (8 * byteLength) - 1);
  4029. checkInt(this, value, offset, byteLength, limit - 1, -limit);
  4030. }
  4031. var i = byteLength - 1;
  4032. var mul = 1;
  4033. var sub = 0;
  4034. this[offset + i] = value & 0xFF;
  4035. while (--i >= 0 && (mul *= 0x100)) {
  4036. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  4037. sub = 1;
  4038. }
  4039. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
  4040. }
  4041. return offset + byteLength
  4042. };
  4043. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  4044. value = +value;
  4045. offset = offset >>> 0;
  4046. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
  4047. if (value < 0) value = 0xff + value + 1;
  4048. this[offset] = (value & 0xff);
  4049. return offset + 1
  4050. };
  4051. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  4052. value = +value;
  4053. offset = offset >>> 0;
  4054. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  4055. this[offset] = (value & 0xff);
  4056. this[offset + 1] = (value >>> 8);
  4057. return offset + 2
  4058. };
  4059. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  4060. value = +value;
  4061. offset = offset >>> 0;
  4062. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
  4063. this[offset] = (value >>> 8);
  4064. this[offset + 1] = (value & 0xff);
  4065. return offset + 2
  4066. };
  4067. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  4068. value = +value;
  4069. offset = offset >>> 0;
  4070. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  4071. this[offset] = (value & 0xff);
  4072. this[offset + 1] = (value >>> 8);
  4073. this[offset + 2] = (value >>> 16);
  4074. this[offset + 3] = (value >>> 24);
  4075. return offset + 4
  4076. };
  4077. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  4078. value = +value;
  4079. offset = offset >>> 0;
  4080. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
  4081. if (value < 0) value = 0xffffffff + value + 1;
  4082. this[offset] = (value >>> 24);
  4083. this[offset + 1] = (value >>> 16);
  4084. this[offset + 2] = (value >>> 8);
  4085. this[offset + 3] = (value & 0xff);
  4086. return offset + 4
  4087. };
  4088. function checkIEEE754 (buf, value, offset, ext, max, min) {
  4089. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  4090. if (offset < 0) throw new RangeError('Index out of range')
  4091. }
  4092. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  4093. value = +value;
  4094. offset = offset >>> 0;
  4095. if (!noAssert) {
  4096. checkIEEE754(buf, value, offset, 4);
  4097. }
  4098. ieee754.write(buf, value, offset, littleEndian, 23, 4);
  4099. return offset + 4
  4100. }
  4101. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  4102. return writeFloat(this, value, offset, true, noAssert)
  4103. };
  4104. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  4105. return writeFloat(this, value, offset, false, noAssert)
  4106. };
  4107. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  4108. value = +value;
  4109. offset = offset >>> 0;
  4110. if (!noAssert) {
  4111. checkIEEE754(buf, value, offset, 8);
  4112. }
  4113. ieee754.write(buf, value, offset, littleEndian, 52, 8);
  4114. return offset + 8
  4115. }
  4116. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  4117. return writeDouble(this, value, offset, true, noAssert)
  4118. };
  4119. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  4120. return writeDouble(this, value, offset, false, noAssert)
  4121. };
  4122. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  4123. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  4124. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  4125. if (!start) start = 0;
  4126. if (!end && end !== 0) end = this.length;
  4127. if (targetStart >= target.length) targetStart = target.length;
  4128. if (!targetStart) targetStart = 0;
  4129. if (end > 0 && end < start) end = start;
  4130. // Copy 0 bytes; we're done
  4131. if (end === start) return 0
  4132. if (target.length === 0 || this.length === 0) return 0
  4133. // Fatal error conditions
  4134. if (targetStart < 0) {
  4135. throw new RangeError('targetStart out of bounds')
  4136. }
  4137. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  4138. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  4139. // Are we oob?
  4140. if (end > this.length) end = this.length;
  4141. if (target.length - targetStart < end - start) {
  4142. end = target.length - targetStart + start;
  4143. }
  4144. var len = end - start;
  4145. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  4146. // Use built-in when available, missing from IE11
  4147. this.copyWithin(targetStart, start, end);
  4148. } else if (this === target && start < targetStart && targetStart < end) {
  4149. // descending copy from end
  4150. for (var i = len - 1; i >= 0; --i) {
  4151. target[i + targetStart] = this[i + start];
  4152. }
  4153. } else {
  4154. Uint8Array.prototype.set.call(
  4155. target,
  4156. this.subarray(start, end),
  4157. targetStart
  4158. );
  4159. }
  4160. return len
  4161. };
  4162. // Usage:
  4163. // buffer.fill(number[, offset[, end]])
  4164. // buffer.fill(buffer[, offset[, end]])
  4165. // buffer.fill(string[, offset[, end]][, encoding])
  4166. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  4167. // Handle string cases:
  4168. if (typeof val === 'string') {
  4169. if (typeof start === 'string') {
  4170. encoding = start;
  4171. start = 0;
  4172. end = this.length;
  4173. } else if (typeof end === 'string') {
  4174. encoding = end;
  4175. end = this.length;
  4176. }
  4177. if (encoding !== undefined && typeof encoding !== 'string') {
  4178. throw new TypeError('encoding must be a string')
  4179. }
  4180. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  4181. throw new TypeError('Unknown encoding: ' + encoding)
  4182. }
  4183. if (val.length === 1) {
  4184. var code = val.charCodeAt(0);
  4185. if ((encoding === 'utf8' && code < 128) ||
  4186. encoding === 'latin1') {
  4187. // Fast path: If `val` fits into a single byte, use that numeric value.
  4188. val = code;
  4189. }
  4190. }
  4191. } else if (typeof val === 'number') {
  4192. val = val & 255;
  4193. } else if (typeof val === 'boolean') {
  4194. val = Number(val);
  4195. }
  4196. // Invalid ranges are not set to a default, so can range check early.
  4197. if (start < 0 || this.length < start || this.length < end) {
  4198. throw new RangeError('Out of range index')
  4199. }
  4200. if (end <= start) {
  4201. return this
  4202. }
  4203. start = start >>> 0;
  4204. end = end === undefined ? this.length : end >>> 0;
  4205. if (!val) val = 0;
  4206. var i;
  4207. if (typeof val === 'number') {
  4208. for (i = start; i < end; ++i) {
  4209. this[i] = val;
  4210. }
  4211. } else {
  4212. var bytes = Buffer.isBuffer(val)
  4213. ? val
  4214. : Buffer.from(val, encoding);
  4215. var len = bytes.length;
  4216. if (len === 0) {
  4217. throw new TypeError('The value "' + val +
  4218. '" is invalid for argument "value"')
  4219. }
  4220. for (i = 0; i < end - start; ++i) {
  4221. this[i + start] = bytes[i % len];
  4222. }
  4223. }
  4224. return this
  4225. };
  4226. // HELPER FUNCTIONS
  4227. // ================
  4228. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
  4229. function base64clean (str) {
  4230. // Node takes equal signs as end of the Base64 encoding
  4231. str = str.split('=')[0];
  4232. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  4233. str = str.trim().replace(INVALID_BASE64_RE, '');
  4234. // Node converts strings with length < 2 to ''
  4235. if (str.length < 2) return ''
  4236. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  4237. while (str.length % 4 !== 0) {
  4238. str = str + '=';
  4239. }
  4240. return str
  4241. }
  4242. function utf8ToBytes (string, units) {
  4243. units = units || Infinity;
  4244. var codePoint;
  4245. var length = string.length;
  4246. var leadSurrogate = null;
  4247. var bytes = [];
  4248. for (var i = 0; i < length; ++i) {
  4249. codePoint = string.charCodeAt(i);
  4250. // is surrogate component
  4251. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  4252. // last char was a lead
  4253. if (!leadSurrogate) {
  4254. // no lead yet
  4255. if (codePoint > 0xDBFF) {
  4256. // unexpected trail
  4257. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  4258. continue
  4259. } else if (i + 1 === length) {
  4260. // unpaired lead
  4261. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  4262. continue
  4263. }
  4264. // valid lead
  4265. leadSurrogate = codePoint;
  4266. continue
  4267. }
  4268. // 2 leads in a row
  4269. if (codePoint < 0xDC00) {
  4270. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  4271. leadSurrogate = codePoint;
  4272. continue
  4273. }
  4274. // valid surrogate pair
  4275. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
  4276. } else if (leadSurrogate) {
  4277. // valid bmp char, but last char was a lead
  4278. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
  4279. }
  4280. leadSurrogate = null;
  4281. // encode utf8
  4282. if (codePoint < 0x80) {
  4283. if ((units -= 1) < 0) break
  4284. bytes.push(codePoint);
  4285. } else if (codePoint < 0x800) {
  4286. if ((units -= 2) < 0) break
  4287. bytes.push(
  4288. codePoint >> 0x6 | 0xC0,
  4289. codePoint & 0x3F | 0x80
  4290. );
  4291. } else if (codePoint < 0x10000) {
  4292. if ((units -= 3) < 0) break
  4293. bytes.push(
  4294. codePoint >> 0xC | 0xE0,
  4295. codePoint >> 0x6 & 0x3F | 0x80,
  4296. codePoint & 0x3F | 0x80
  4297. );
  4298. } else if (codePoint < 0x110000) {
  4299. if ((units -= 4) < 0) break
  4300. bytes.push(
  4301. codePoint >> 0x12 | 0xF0,
  4302. codePoint >> 0xC & 0x3F | 0x80,
  4303. codePoint >> 0x6 & 0x3F | 0x80,
  4304. codePoint & 0x3F | 0x80
  4305. );
  4306. } else {
  4307. throw new Error('Invalid code point')
  4308. }
  4309. }
  4310. return bytes
  4311. }
  4312. function asciiToBytes (str) {
  4313. var byteArray = [];
  4314. for (var i = 0; i < str.length; ++i) {
  4315. // Node's code seems to be doing this and not & 0x7F..
  4316. byteArray.push(str.charCodeAt(i) & 0xFF);
  4317. }
  4318. return byteArray
  4319. }
  4320. function utf16leToBytes (str, units) {
  4321. var c, hi, lo;
  4322. var byteArray = [];
  4323. for (var i = 0; i < str.length; ++i) {
  4324. if ((units -= 2) < 0) break
  4325. c = str.charCodeAt(i);
  4326. hi = c >> 8;
  4327. lo = c % 256;
  4328. byteArray.push(lo);
  4329. byteArray.push(hi);
  4330. }
  4331. return byteArray
  4332. }
  4333. function base64ToBytes (str) {
  4334. return base64.toByteArray(base64clean(str))
  4335. }
  4336. function blitBuffer (src, dst, offset, length) {
  4337. for (var i = 0; i < length; ++i) {
  4338. if ((i + offset >= dst.length) || (i >= src.length)) break
  4339. dst[i + offset] = src[i];
  4340. }
  4341. return i
  4342. }
  4343. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  4344. // the `instanceof` check but they should be treated as of that type.
  4345. // See: https://github.com/feross/buffer/issues/166
  4346. function isInstance (obj, type) {
  4347. return obj instanceof type ||
  4348. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  4349. obj.constructor.name === type.name)
  4350. }
  4351. function numberIsNaN (obj) {
  4352. // For IE11 support
  4353. return obj !== obj // eslint-disable-line no-self-compare
  4354. }
  4355. // Create lookup table for `toString('hex')`
  4356. // See: https://github.com/feross/buffer/issues/219
  4357. var hexSliceLookupTable = (function () {
  4358. var alphabet = '0123456789abcdef';
  4359. var table = new Array(256);
  4360. for (var i = 0; i < 16; ++i) {
  4361. var i16 = i * 16;
  4362. for (var j = 0; j < 16; ++j) {
  4363. table[i16 + j] = alphabet[i] + alphabet[j];
  4364. }
  4365. }
  4366. return table
  4367. })();
  4368. },{"base64-js":29,"ieee754":32}],31:[function(require,module,exports){
  4369. /******************************************************************************
  4370. * Created 2008-08-19.
  4371. *
  4372. * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
  4373. *
  4374. * Copyright (C) 2008
  4375. * Wyatt Baldwin <self@wyattbaldwin.com>
  4376. * All rights reserved
  4377. *
  4378. * Licensed under the MIT license.
  4379. *
  4380. * http://www.opensource.org/licenses/mit-license.php
  4381. *
  4382. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  4383. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  4384. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  4385. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  4386. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  4387. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  4388. * THE SOFTWARE.
  4389. *****************************************************************************/
  4390. var dijkstra = {
  4391. single_source_shortest_paths: function(graph, s, d) {
  4392. // Predecessor map for each node that has been encountered.
  4393. // node ID => predecessor node ID
  4394. var predecessors = {};
  4395. // Costs of shortest paths from s to all nodes encountered.
  4396. // node ID => cost
  4397. var costs = {};
  4398. costs[s] = 0;
  4399. // Costs of shortest paths from s to all nodes encountered; differs from
  4400. // `costs` in that it provides easy access to the node that currently has
  4401. // the known shortest path from s.
  4402. // XXX: Do we actually need both `costs` and `open`?
  4403. var open = dijkstra.PriorityQueue.make();
  4404. open.push(s, 0);
  4405. var closest,
  4406. u, v,
  4407. cost_of_s_to_u,
  4408. adjacent_nodes,
  4409. cost_of_e,
  4410. cost_of_s_to_u_plus_cost_of_e,
  4411. cost_of_s_to_v,
  4412. first_visit;
  4413. while (!open.empty()) {
  4414. // In the nodes remaining in graph that have a known cost from s,
  4415. // find the node, u, that currently has the shortest path from s.
  4416. closest = open.pop();
  4417. u = closest.value;
  4418. cost_of_s_to_u = closest.cost;
  4419. // Get nodes adjacent to u...
  4420. adjacent_nodes = graph[u] || {};
  4421. // ...and explore the edges that connect u to those nodes, updating
  4422. // the cost of the shortest paths to any or all of those nodes as
  4423. // necessary. v is the node across the current edge from u.
  4424. for (v in adjacent_nodes) {
  4425. if (adjacent_nodes.hasOwnProperty(v)) {
  4426. // Get the cost of the edge running from u to v.
  4427. cost_of_e = adjacent_nodes[v];
  4428. // Cost of s to u plus the cost of u to v across e--this is *a*
  4429. // cost from s to v that may or may not be less than the current
  4430. // known cost to v.
  4431. cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
  4432. // If we haven't visited v yet OR if the current known cost from s to
  4433. // v is greater than the new cost we just found (cost of s to u plus
  4434. // cost of u to v across e), update v's cost in the cost list and
  4435. // update v's predecessor in the predecessor list (it's now u).
  4436. cost_of_s_to_v = costs[v];
  4437. first_visit = (typeof costs[v] === 'undefined');
  4438. if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
  4439. costs[v] = cost_of_s_to_u_plus_cost_of_e;
  4440. open.push(v, cost_of_s_to_u_plus_cost_of_e);
  4441. predecessors[v] = u;
  4442. }
  4443. }
  4444. }
  4445. }
  4446. if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
  4447. var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
  4448. throw new Error(msg);
  4449. }
  4450. return predecessors;
  4451. },
  4452. extract_shortest_path_from_predecessor_list: function(predecessors, d) {
  4453. var nodes = [];
  4454. var u = d;
  4455. var predecessor;
  4456. while (u) {
  4457. nodes.push(u);
  4458. predecessor = predecessors[u];
  4459. u = predecessors[u];
  4460. }
  4461. nodes.reverse();
  4462. return nodes;
  4463. },
  4464. find_path: function(graph, s, d) {
  4465. var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
  4466. return dijkstra.extract_shortest_path_from_predecessor_list(
  4467. predecessors, d);
  4468. },
  4469. /**
  4470. * A very naive priority queue implementation.
  4471. */
  4472. PriorityQueue: {
  4473. make: function (opts) {
  4474. var T = dijkstra.PriorityQueue,
  4475. t = {},
  4476. key;
  4477. opts = opts || {};
  4478. for (key in T) {
  4479. if (T.hasOwnProperty(key)) {
  4480. t[key] = T[key];
  4481. }
  4482. }
  4483. t.queue = [];
  4484. t.sorter = opts.sorter || T.default_sorter;
  4485. return t;
  4486. },
  4487. default_sorter: function (a, b) {
  4488. return a.cost - b.cost;
  4489. },
  4490. /**
  4491. * Add a new item to the queue and ensure the highest priority element
  4492. * is at the front of the queue.
  4493. */
  4494. push: function (value, cost) {
  4495. var item = {value: value, cost: cost};
  4496. this.queue.push(item);
  4497. this.queue.sort(this.sorter);
  4498. },
  4499. /**
  4500. * Return the highest priority element in the queue.
  4501. */
  4502. pop: function () {
  4503. return this.queue.shift();
  4504. },
  4505. empty: function () {
  4506. return this.queue.length === 0;
  4507. }
  4508. }
  4509. };
  4510. // node.js module exports
  4511. if (typeof module !== 'undefined') {
  4512. module.exports = dijkstra;
  4513. }
  4514. },{}],32:[function(require,module,exports){
  4515. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  4516. var e, m;
  4517. var eLen = (nBytes * 8) - mLen - 1;
  4518. var eMax = (1 << eLen) - 1;
  4519. var eBias = eMax >> 1;
  4520. var nBits = -7;
  4521. var i = isLE ? (nBytes - 1) : 0;
  4522. var d = isLE ? -1 : 1;
  4523. var s = buffer[offset + i];
  4524. i += d;
  4525. e = s & ((1 << (-nBits)) - 1);
  4526. s >>= (-nBits);
  4527. nBits += eLen;
  4528. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4529. m = e & ((1 << (-nBits)) - 1);
  4530. e >>= (-nBits);
  4531. nBits += mLen;
  4532. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4533. if (e === 0) {
  4534. e = 1 - eBias;
  4535. } else if (e === eMax) {
  4536. return m ? NaN : ((s ? -1 : 1) * Infinity)
  4537. } else {
  4538. m = m + Math.pow(2, mLen);
  4539. e = e - eBias;
  4540. }
  4541. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  4542. };
  4543. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  4544. var e, m, c;
  4545. var eLen = (nBytes * 8) - mLen - 1;
  4546. var eMax = (1 << eLen) - 1;
  4547. var eBias = eMax >> 1;
  4548. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
  4549. var i = isLE ? 0 : (nBytes - 1);
  4550. var d = isLE ? 1 : -1;
  4551. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
  4552. value = Math.abs(value);
  4553. if (isNaN(value) || value === Infinity) {
  4554. m = isNaN(value) ? 1 : 0;
  4555. e = eMax;
  4556. } else {
  4557. e = Math.floor(Math.log(value) / Math.LN2);
  4558. if (value * (c = Math.pow(2, -e)) < 1) {
  4559. e--;
  4560. c *= 2;
  4561. }
  4562. if (e + eBias >= 1) {
  4563. value += rt / c;
  4564. } else {
  4565. value += rt * Math.pow(2, 1 - eBias);
  4566. }
  4567. if (value * c >= 2) {
  4568. e++;
  4569. c /= 2;
  4570. }
  4571. if (e + eBias >= eMax) {
  4572. m = 0;
  4573. e = eMax;
  4574. } else if (e + eBias >= 1) {
  4575. m = ((value * c) - 1) * Math.pow(2, mLen);
  4576. e = e + eBias;
  4577. } else {
  4578. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
  4579. e = 0;
  4580. }
  4581. }
  4582. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  4583. e = (e << mLen) | m;
  4584. eLen += mLen;
  4585. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  4586. buffer[offset + i - d] |= s * 128;
  4587. };
  4588. },{}],33:[function(require,module,exports){
  4589. var toString = {}.toString;
  4590. module.exports = Array.isArray || function (arr) {
  4591. return toString.call(arr) == '[object Array]';
  4592. };
  4593. },{}]},{},[24])(24)
  4594. });
  4595. });
  4596. var index = {
  4597. name: 'qrcode',
  4598. props: {
  4599. /**
  4600. * The value of the QR code.
  4601. */
  4602. value: null,
  4603. /**
  4604. * The options for the QR code generator.
  4605. * {@link https://github.com/soldair/node-qrcode#qr-code-options}
  4606. */
  4607. options: Object,
  4608. /**
  4609. * The tag name of the component's root element.
  4610. */
  4611. tag: {
  4612. type: String,
  4613. default: 'canvas'
  4614. }
  4615. },
  4616. render: function render(createElement) {
  4617. return createElement(this.tag, this.$slots.default);
  4618. },
  4619. watch: {
  4620. $props: {
  4621. deep: true,
  4622. immediate: true,
  4623. /**
  4624. * Update the QR code when props changed.
  4625. */
  4626. handler: function handler() {
  4627. if (this.$el) {
  4628. this.generate();
  4629. }
  4630. }
  4631. }
  4632. },
  4633. methods: {
  4634. /**
  4635. * Generate QR code.
  4636. */
  4637. generate: function generate() {
  4638. var _this = this;
  4639. var options = this.options,
  4640. tag = this.tag;
  4641. var value = String(this.value);
  4642. if (tag === 'canvas') {
  4643. qrcode.toCanvas(this.$el, value, options, function (error) {
  4644. /* istanbul ignore if */
  4645. if (error) {
  4646. throw error;
  4647. }
  4648. });
  4649. } else if (tag === 'img') {
  4650. qrcode.toDataURL(value, options, function (error, url) {
  4651. /* istanbul ignore if */
  4652. if (error) {
  4653. throw error;
  4654. }
  4655. _this.$el.src = url;
  4656. });
  4657. } else {
  4658. qrcode.toString(value, options, function (error, string) {
  4659. /* istanbul ignore if */
  4660. if (error) {
  4661. throw error;
  4662. }
  4663. _this.$el.innerHTML = string;
  4664. });
  4665. }
  4666. }
  4667. },
  4668. mounted: function mounted() {
  4669. this.generate();
  4670. }
  4671. };
  4672. export default index;