vue-qrcode.js 153 KB

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