vue-qrcode.common.js 149 KB

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