plist-parse.js 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;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 require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. (function (Buffer){(function (){
  3. /**
  4. * Module dependencies.
  5. */
  6. var DOMParser = require('./xmldom/dom-parser').DOMParser;
  7. /**
  8. * Module exports.
  9. */
  10. exports.parse = parse;
  11. var TEXT_NODE = 3;
  12. var CDATA_NODE = 4;
  13. var COMMENT_NODE = 8;
  14. /**
  15. * We ignore raw text (usually whitespace), <!-- xml comments -->,
  16. * and raw CDATA nodes.
  17. *
  18. * @param {Element} node
  19. * @returns {Boolean}
  20. * @api private
  21. */
  22. function shouldIgnoreNode (node) {
  23. return node.nodeType === TEXT_NODE
  24. || node.nodeType === COMMENT_NODE
  25. || node.nodeType === CDATA_NODE;
  26. }
  27. /**
  28. * Check if the node is empty. Some plist file has such node:
  29. * <key />
  30. * this node shoud be ignored.
  31. *
  32. * @see https://github.com/TooTallNate/plist.js/issues/66
  33. * @param {Element} node
  34. * @returns {Boolean}
  35. * @api private
  36. */
  37. function isEmptyNode(node){
  38. if(!node.childNodes || node.childNodes.length === 0) {
  39. return true;
  40. } else {
  41. return false;
  42. }
  43. }
  44. function invariant(test, message) {
  45. if (!test) {
  46. throw new Error(message);
  47. }
  48. }
  49. /**
  50. * Parses a Plist XML string. Returns an Object.
  51. *
  52. * @param {String} xml - the XML String to decode
  53. * @returns {Mixed} the decoded value from the Plist XML
  54. * @api public
  55. */
  56. function parse (xml) {
  57. var doc = new DOMParser().parseFromString(xml);
  58. invariant(
  59. doc.documentElement.nodeName === 'plist',
  60. 'malformed document. First element should be <plist>'
  61. );
  62. var plist = parsePlistXML(doc.documentElement);
  63. // the root <plist> node gets interpreted as an Array,
  64. // so pull out the inner data first
  65. if (plist.length == 1) plist = plist[0];
  66. return plist;
  67. }
  68. /**
  69. * Convert an XML based plist document into a JSON representation.
  70. *
  71. * @param {Object} xml_node - current XML node in the plist
  72. * @returns {Mixed} built up JSON object
  73. * @api private
  74. */
  75. function parsePlistXML (node) {
  76. var i, new_obj, key, val, new_arr, res, counter, type;
  77. if (!node)
  78. return null;
  79. if (node.nodeName === 'plist') {
  80. new_arr = [];
  81. if (isEmptyNode(node)) {
  82. return new_arr;
  83. }
  84. for (i=0; i < node.childNodes.length; i++) {
  85. if (!shouldIgnoreNode(node.childNodes[i])) {
  86. new_arr.push( parsePlistXML(node.childNodes[i]));
  87. }
  88. }
  89. return new_arr;
  90. } else if (node.nodeName === 'dict') {
  91. new_obj = {};
  92. key = null;
  93. counter = 0;
  94. if (isEmptyNode(node)) {
  95. return new_obj;
  96. }
  97. for (i=0; i < node.childNodes.length; i++) {
  98. if (shouldIgnoreNode(node.childNodes[i])) continue;
  99. if (counter % 2 === 0) {
  100. invariant(
  101. node.childNodes[i].nodeName === 'key',
  102. 'Missing key while parsing <dict/>.'
  103. );
  104. key = parsePlistXML(node.childNodes[i]);
  105. } else {
  106. invariant(
  107. node.childNodes[i].nodeName !== 'key',
  108. 'Unexpected key "'
  109. + parsePlistXML(node.childNodes[i])
  110. + '" while parsing <dict/>.'
  111. );
  112. new_obj[key] = parsePlistXML(node.childNodes[i]);
  113. }
  114. counter += 1;
  115. }
  116. if (counter % 2 === 1) {
  117. new_obj[key] = '';
  118. }
  119. return new_obj;
  120. } else if (node.nodeName === 'array') {
  121. new_arr = [];
  122. if (isEmptyNode(node)) {
  123. return new_arr;
  124. }
  125. for (i=0; i < node.childNodes.length; i++) {
  126. if (!shouldIgnoreNode(node.childNodes[i])) {
  127. res = parsePlistXML(node.childNodes[i]);
  128. if (null != res) new_arr.push(res);
  129. }
  130. }
  131. return new_arr;
  132. } else if (node.nodeName === '#text') {
  133. // TODO: what should we do with text types? (CDATA sections)
  134. } else if (node.nodeName === 'key') {
  135. if (isEmptyNode(node)) {
  136. return '';
  137. }
  138. invariant(
  139. node.childNodes[0].nodeValue !== '__proto__',
  140. '__proto__ keys can lead to prototype pollution. More details on CVE-2022-22912'
  141. );
  142. return node.childNodes[0].nodeValue;
  143. } else if (node.nodeName === 'string') {
  144. res = '';
  145. if (isEmptyNode(node)) {
  146. return res;
  147. }
  148. for (i=0; i < node.childNodes.length; i++) {
  149. var type = node.childNodes[i].nodeType;
  150. if (type === TEXT_NODE || type === CDATA_NODE) {
  151. res += node.childNodes[i].nodeValue;
  152. }
  153. }
  154. return res;
  155. } else if (node.nodeName === 'integer') {
  156. invariant(
  157. !isEmptyNode(node),
  158. 'Cannot parse "" as integer.'
  159. );
  160. return parseInt(node.childNodes[0].nodeValue, 10);
  161. } else if (node.nodeName === 'real') {
  162. invariant(
  163. !isEmptyNode(node),
  164. 'Cannot parse "" as real.'
  165. );
  166. res = '';
  167. for (i=0; i < node.childNodes.length; i++) {
  168. if (node.childNodes[i].nodeType === TEXT_NODE) {
  169. res += node.childNodes[i].nodeValue;
  170. }
  171. }
  172. return parseFloat(res);
  173. } else if (node.nodeName === 'data') {
  174. res = '';
  175. if (isEmptyNode(node)) {
  176. return Buffer.from(res, 'base64');
  177. }
  178. for (i=0; i < node.childNodes.length; i++) {
  179. if (node.childNodes[i].nodeType === TEXT_NODE) {
  180. res += node.childNodes[i].nodeValue.replace(/\s+/g, '');
  181. }
  182. }
  183. return Buffer.from(res, 'base64');
  184. } else if (node.nodeName === 'date') {
  185. invariant(
  186. !isEmptyNode(node),
  187. 'Cannot parse "" as Date.'
  188. )
  189. return new Date(node.childNodes[0].nodeValue);
  190. } else if (node.nodeName === 'null') {
  191. return null;
  192. } else if (node.nodeName === 'true') {
  193. return true;
  194. } else if (node.nodeName === 'false') {
  195. return false;
  196. } else {
  197. throw new Error('Invalid PLIST tag ' + node.nodeName);
  198. }
  199. }
  200. }).call(this)}).call(this,require("buffer").Buffer)
  201. },{"./xmldom/dom-parser":2,"buffer":7}],2:[function(require,module,exports){
  202. function DOMParser(options){
  203. this.options = options ||{locator:{}};
  204. }
  205. DOMParser.prototype.parseFromString = function(source,mimeType){
  206. var options = this.options;
  207. var sax = new XMLReader();
  208. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  209. var errorHandler = options.errorHandler;
  210. var locator = options.locator;
  211. var defaultNSMap = options.xmlns||{};
  212. var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
  213. var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
  214. if(locator){
  215. domBuilder.setDocumentLocator(locator)
  216. }
  217. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  218. sax.domBuilder = options.domBuilder || domBuilder;
  219. if(isHTML){
  220. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  221. }
  222. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  223. if(source && typeof source === 'string'){
  224. sax.parse(source,defaultNSMap,entityMap);
  225. }else{
  226. sax.errorHandler.error("invalid doc source");
  227. }
  228. return domBuilder.doc;
  229. }
  230. function buildErrorHandler(errorImpl,domBuilder,locator){
  231. if(!errorImpl){
  232. if(domBuilder instanceof DOMHandler){
  233. return domBuilder;
  234. }
  235. errorImpl = domBuilder ;
  236. }
  237. var errorHandler = {}
  238. var isCallback = errorImpl instanceof Function;
  239. locator = locator||{}
  240. function build(key){
  241. var fn = errorImpl[key];
  242. if(!fn && isCallback){
  243. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  244. }
  245. errorHandler[key] = fn && function(msg){
  246. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  247. }||function(){};
  248. }
  249. build('warning');
  250. build('error');
  251. build('fatalError');
  252. return errorHandler;
  253. }
  254. //console.log('#\n\n\n\n\n\n\n####')
  255. /**
  256. * +ContentHandler+ErrorHandler
  257. * +LexicalHandler+EntityResolver2
  258. * -DeclHandler-DTDHandler
  259. *
  260. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  261. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  262. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  263. */
  264. function DOMHandler() {
  265. this.cdata = false;
  266. }
  267. function position(locator,node){
  268. node.lineNumber = locator.lineNumber;
  269. node.columnNumber = locator.columnNumber;
  270. }
  271. /**
  272. * @see org.xml.sax.ContentHandler#startDocument
  273. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  274. */
  275. DOMHandler.prototype = {
  276. startDocument : function() {
  277. this.doc = new DOMImplementation().createDocument(null, null, null);
  278. if (this.locator) {
  279. this.doc.documentURI = this.locator.systemId;
  280. }
  281. },
  282. startElement:function(namespaceURI, localName, qName, attrs) {
  283. var doc = this.doc;
  284. var el = doc.createElementNS(namespaceURI, qName||localName);
  285. var len = attrs.length;
  286. appendElement(this, el);
  287. this.currentElement = el;
  288. this.locator && position(this.locator,el)
  289. for (var i = 0 ; i < len; i++) {
  290. var namespaceURI = attrs.getURI(i);
  291. var value = attrs.getValue(i);
  292. var qName = attrs.getQName(i);
  293. var attr = doc.createAttributeNS(namespaceURI, qName);
  294. this.locator &&position(attrs.getLocator(i),attr);
  295. attr.value = attr.nodeValue = value;
  296. el.setAttributeNode(attr)
  297. }
  298. },
  299. endElement:function(namespaceURI, localName, qName) {
  300. var current = this.currentElement
  301. var tagName = current.tagName;
  302. this.currentElement = current.parentNode;
  303. },
  304. startPrefixMapping:function(prefix, uri) {
  305. },
  306. endPrefixMapping:function(prefix) {
  307. },
  308. processingInstruction:function(target, data) {
  309. var ins = this.doc.createProcessingInstruction(target, data);
  310. this.locator && position(this.locator,ins)
  311. appendElement(this, ins);
  312. },
  313. ignorableWhitespace:function(ch, start, length) {
  314. },
  315. characters:function(chars, start, length) {
  316. chars = _toString.apply(this,arguments)
  317. //console.log(chars)
  318. if(chars){
  319. if (this.cdata) {
  320. var charNode = this.doc.createCDATASection(chars);
  321. } else {
  322. var charNode = this.doc.createTextNode(chars);
  323. }
  324. if(this.currentElement){
  325. this.currentElement.appendChild(charNode);
  326. }else if(/^\s*$/.test(chars)){
  327. this.doc.appendChild(charNode);
  328. //process xml
  329. }
  330. this.locator && position(this.locator,charNode)
  331. }
  332. },
  333. skippedEntity:function(name) {
  334. },
  335. endDocument:function() {
  336. this.doc.normalize();
  337. },
  338. setDocumentLocator:function (locator) {
  339. if(this.locator = locator){// && !('lineNumber' in locator)){
  340. locator.lineNumber = 0;
  341. }
  342. },
  343. //LexicalHandler
  344. comment:function(chars, start, length) {
  345. chars = _toString.apply(this,arguments)
  346. var comm = this.doc.createComment(chars);
  347. this.locator && position(this.locator,comm)
  348. appendElement(this, comm);
  349. },
  350. startCDATA:function() {
  351. //used in characters() methods
  352. this.cdata = true;
  353. },
  354. endCDATA:function() {
  355. this.cdata = false;
  356. },
  357. startDTD:function(name, publicId, systemId) {
  358. var impl = this.doc.implementation;
  359. if (impl && impl.createDocumentType) {
  360. var dt = impl.createDocumentType(name, publicId, systemId);
  361. this.locator && position(this.locator,dt)
  362. appendElement(this, dt);
  363. }
  364. },
  365. /**
  366. * @see org.xml.sax.ErrorHandler
  367. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  368. */
  369. warning:function(error) {
  370. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  371. },
  372. error:function(error) {
  373. console.error('[xmldom error]\t'+error,_locator(this.locator));
  374. },
  375. fatalError:function(error) {
  376. throw new ParseError(error, this.locator);
  377. }
  378. }
  379. function _locator(l){
  380. if(l){
  381. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  382. }
  383. }
  384. function _toString(chars,start,length){
  385. if(typeof chars == 'string'){
  386. return chars.substr(start,length)
  387. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  388. if(chars.length >= start+length || start){
  389. return new java.lang.String(chars,start,length)+'';
  390. }
  391. return chars;
  392. }
  393. }
  394. /*
  395. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  396. * used method of org.xml.sax.ext.LexicalHandler:
  397. * #comment(chars, start, length)
  398. * #startCDATA()
  399. * #endCDATA()
  400. * #startDTD(name, publicId, systemId)
  401. *
  402. *
  403. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  404. * #endDTD()
  405. * #startEntity(name)
  406. * #endEntity(name)
  407. *
  408. *
  409. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  410. * IGNORED method of org.xml.sax.ext.DeclHandler
  411. * #attributeDecl(eName, aName, type, mode, value)
  412. * #elementDecl(name, model)
  413. * #externalEntityDecl(name, publicId, systemId)
  414. * #internalEntityDecl(name, value)
  415. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  416. * IGNORED method of org.xml.sax.EntityResolver2
  417. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  418. * #resolveEntity(publicId, systemId)
  419. * #getExternalSubset(name, baseURI)
  420. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  421. * IGNORED method of org.xml.sax.DTDHandler
  422. * #notationDecl(name, publicId, systemId) {};
  423. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  424. */
  425. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  426. DOMHandler.prototype[key] = function(){return null}
  427. })
  428. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  429. function appendElement (hander,node) {
  430. if (!hander.currentElement) {
  431. hander.doc.appendChild(node);
  432. } else {
  433. hander.currentElement.appendChild(node);
  434. }
  435. }//appendChild and setAttributeNS are preformance key
  436. //if(typeof require == 'function'){
  437. var htmlEntity = require('./entities');
  438. var sax = require('./sax');
  439. var XMLReader = sax.XMLReader;
  440. var ParseError = sax.ParseError;
  441. var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
  442. exports.XMLSerializer = require('./dom').XMLSerializer ;
  443. exports.DOMParser = DOMParser;
  444. exports.__DOMHandler = DOMHandler;
  445. //}
  446. },{"./dom":3,"./entities":4,"./sax":5}],3:[function(require,module,exports){
  447. function copy(src,dest){
  448. for(var p in src){
  449. dest[p] = src[p];
  450. }
  451. }
  452. /**
  453. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  454. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  455. */
  456. function _extends(Class,Super){
  457. var pt = Class.prototype;
  458. if(!(pt instanceof Super)){
  459. function t(){};
  460. t.prototype = Super.prototype;
  461. t = new t();
  462. copy(pt,t);
  463. Class.prototype = pt = t;
  464. }
  465. if(pt.constructor != Class){
  466. if(typeof Class != 'function'){
  467. console.error("unknow Class:"+Class)
  468. }
  469. pt.constructor = Class
  470. }
  471. }
  472. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  473. // Node Types
  474. var NodeType = {}
  475. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  476. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  477. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  478. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  479. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  480. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  481. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  482. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  483. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  484. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  485. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  486. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  487. // ExceptionCode
  488. var ExceptionCode = {}
  489. var ExceptionMessage = {};
  490. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  491. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  492. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  493. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  494. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  495. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  496. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  497. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  498. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  499. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  500. //level2
  501. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  502. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  503. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  504. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  505. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  506. /**
  507. * DOM Level 2
  508. * Object DOMException
  509. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  510. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  511. */
  512. function DOMException(code, message) {
  513. if(message instanceof Error){
  514. var error = message;
  515. }else{
  516. error = this;
  517. Error.call(this, ExceptionMessage[code]);
  518. this.message = ExceptionMessage[code];
  519. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  520. }
  521. error.code = code;
  522. if(message) this.message = this.message + ": " + message;
  523. return error;
  524. };
  525. DOMException.prototype = Error.prototype;
  526. copy(ExceptionCode,DOMException)
  527. /**
  528. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  529. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  530. * The items in the NodeList are accessible via an integral index, starting from 0.
  531. */
  532. function NodeList() {
  533. };
  534. NodeList.prototype = {
  535. /**
  536. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  537. * @standard level1
  538. */
  539. length:0,
  540. /**
  541. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  542. * @standard level1
  543. * @param index unsigned long
  544. * Index into the collection.
  545. * @return Node
  546. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  547. */
  548. item: function(index) {
  549. return this[index] || null;
  550. },
  551. toString:function(isHTML,nodeFilter){
  552. for(var buf = [], i = 0;i<this.length;i++){
  553. serializeToString(this[i],buf,isHTML,nodeFilter);
  554. }
  555. return buf.join('');
  556. }
  557. };
  558. function LiveNodeList(node,refresh){
  559. this._node = node;
  560. this._refresh = refresh
  561. _updateLiveList(this);
  562. }
  563. function _updateLiveList(list){
  564. var inc = list._node._inc || list._node.ownerDocument._inc;
  565. if(list._inc != inc){
  566. var ls = list._refresh(list._node);
  567. //console.log(ls.length)
  568. __set__(list,'length',ls.length);
  569. copy(ls,list);
  570. list._inc = inc;
  571. }
  572. }
  573. LiveNodeList.prototype.item = function(i){
  574. _updateLiveList(this);
  575. return this[i];
  576. }
  577. _extends(LiveNodeList,NodeList);
  578. /**
  579. *
  580. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  581. * NamedNodeMap objects in the DOM are live.
  582. * used for attributes or DocumentType entities
  583. */
  584. function NamedNodeMap() {
  585. };
  586. function _findNodeIndex(list,node){
  587. var i = list.length;
  588. while(i--){
  589. if(list[i] === node){return i}
  590. }
  591. }
  592. function _addNamedNode(el,list,newAttr,oldAttr){
  593. if(oldAttr){
  594. list[_findNodeIndex(list,oldAttr)] = newAttr;
  595. }else{
  596. list[list.length++] = newAttr;
  597. }
  598. if(el){
  599. newAttr.ownerElement = el;
  600. var doc = el.ownerDocument;
  601. if(doc){
  602. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  603. _onAddAttribute(doc,el,newAttr);
  604. }
  605. }
  606. }
  607. function _removeNamedNode(el,list,attr){
  608. //console.log('remove attr:'+attr)
  609. var i = _findNodeIndex(list,attr);
  610. if(i>=0){
  611. var lastIndex = list.length-1
  612. while(i<lastIndex){
  613. list[i] = list[++i]
  614. }
  615. list.length = lastIndex;
  616. if(el){
  617. var doc = el.ownerDocument;
  618. if(doc){
  619. _onRemoveAttribute(doc,el,attr);
  620. attr.ownerElement = null;
  621. }
  622. }
  623. }else{
  624. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  625. }
  626. }
  627. NamedNodeMap.prototype = {
  628. length:0,
  629. item:NodeList.prototype.item,
  630. getNamedItem: function(key) {
  631. // if(key.indexOf(':')>0 || key == 'xmlns'){
  632. // return null;
  633. // }
  634. //console.log()
  635. var i = this.length;
  636. while(i--){
  637. var attr = this[i];
  638. //console.log(attr.nodeName,key)
  639. if(attr.nodeName == key){
  640. return attr;
  641. }
  642. }
  643. },
  644. setNamedItem: function(attr) {
  645. var el = attr.ownerElement;
  646. if(el && el!=this._ownerElement){
  647. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  648. }
  649. var oldAttr = this.getNamedItem(attr.nodeName);
  650. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  651. return oldAttr;
  652. },
  653. /* returns Node */
  654. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  655. var el = attr.ownerElement, oldAttr;
  656. if(el && el!=this._ownerElement){
  657. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  658. }
  659. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  660. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  661. return oldAttr;
  662. },
  663. /* returns Node */
  664. removeNamedItem: function(key) {
  665. var attr = this.getNamedItem(key);
  666. _removeNamedNode(this._ownerElement,this,attr);
  667. return attr;
  668. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  669. //for level2
  670. removeNamedItemNS:function(namespaceURI,localName){
  671. var attr = this.getNamedItemNS(namespaceURI,localName);
  672. _removeNamedNode(this._ownerElement,this,attr);
  673. return attr;
  674. },
  675. getNamedItemNS: function(namespaceURI, localName) {
  676. var i = this.length;
  677. while(i--){
  678. var node = this[i];
  679. if(node.localName == localName && node.namespaceURI == namespaceURI){
  680. return node;
  681. }
  682. }
  683. return null;
  684. }
  685. };
  686. /**
  687. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  688. */
  689. function DOMImplementation(/* Object */ features) {
  690. this._features = {};
  691. if (features) {
  692. for (var feature in features) {
  693. this._features = features[feature];
  694. }
  695. }
  696. };
  697. DOMImplementation.prototype = {
  698. hasFeature: function(/* string */ feature, /* string */ version) {
  699. var versions = this._features[feature.toLowerCase()];
  700. if (versions && (!version || version in versions)) {
  701. return true;
  702. } else {
  703. return false;
  704. }
  705. },
  706. // Introduced in DOM Level 2:
  707. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  708. var doc = new Document();
  709. doc.implementation = this;
  710. doc.childNodes = new NodeList();
  711. doc.doctype = doctype;
  712. if(doctype){
  713. doc.appendChild(doctype);
  714. }
  715. if(qualifiedName){
  716. var root = doc.createElementNS(namespaceURI,qualifiedName);
  717. doc.appendChild(root);
  718. }
  719. return doc;
  720. },
  721. // Introduced in DOM Level 2:
  722. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  723. var node = new DocumentType();
  724. node.name = qualifiedName;
  725. node.nodeName = qualifiedName;
  726. node.publicId = publicId;
  727. node.systemId = systemId;
  728. // Introduced in DOM Level 2:
  729. //readonly attribute DOMString internalSubset;
  730. //TODO:..
  731. // readonly attribute NamedNodeMap entities;
  732. // readonly attribute NamedNodeMap notations;
  733. return node;
  734. }
  735. };
  736. /**
  737. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  738. */
  739. function Node() {
  740. };
  741. Node.prototype = {
  742. firstChild : null,
  743. lastChild : null,
  744. previousSibling : null,
  745. nextSibling : null,
  746. attributes : null,
  747. parentNode : null,
  748. childNodes : null,
  749. ownerDocument : null,
  750. nodeValue : null,
  751. namespaceURI : null,
  752. prefix : null,
  753. localName : null,
  754. // Modified in DOM Level 2:
  755. insertBefore:function(newChild, refChild){//raises
  756. return _insertBefore(this,newChild,refChild);
  757. },
  758. replaceChild:function(newChild, oldChild){//raises
  759. this.insertBefore(newChild,oldChild);
  760. if(oldChild){
  761. this.removeChild(oldChild);
  762. }
  763. },
  764. removeChild:function(oldChild){
  765. return _removeChild(this,oldChild);
  766. },
  767. appendChild:function(newChild){
  768. return this.insertBefore(newChild,null);
  769. },
  770. hasChildNodes:function(){
  771. return this.firstChild != null;
  772. },
  773. cloneNode:function(deep){
  774. return cloneNode(this.ownerDocument||this,this,deep);
  775. },
  776. // Modified in DOM Level 2:
  777. normalize:function(){
  778. var child = this.firstChild;
  779. while(child){
  780. var next = child.nextSibling;
  781. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  782. this.removeChild(next);
  783. child.appendData(next.data);
  784. }else{
  785. child.normalize();
  786. child = next;
  787. }
  788. }
  789. },
  790. // Introduced in DOM Level 2:
  791. isSupported:function(feature, version){
  792. return this.ownerDocument.implementation.hasFeature(feature,version);
  793. },
  794. // Introduced in DOM Level 2:
  795. hasAttributes:function(){
  796. return this.attributes.length>0;
  797. },
  798. lookupPrefix:function(namespaceURI){
  799. var el = this;
  800. while(el){
  801. var map = el._nsMap;
  802. //console.dir(map)
  803. if(map){
  804. for(var n in map){
  805. if(map[n] == namespaceURI){
  806. return n;
  807. }
  808. }
  809. }
  810. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  811. }
  812. return null;
  813. },
  814. // Introduced in DOM Level 3:
  815. lookupNamespaceURI:function(prefix){
  816. var el = this;
  817. while(el){
  818. var map = el._nsMap;
  819. //console.dir(map)
  820. if(map){
  821. if(prefix in map){
  822. return map[prefix] ;
  823. }
  824. }
  825. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  826. }
  827. return null;
  828. },
  829. // Introduced in DOM Level 3:
  830. isDefaultNamespace:function(namespaceURI){
  831. var prefix = this.lookupPrefix(namespaceURI);
  832. return prefix == null;
  833. }
  834. };
  835. function _xmlEncoder(c){
  836. return c == '<' && '&lt;' ||
  837. c == '>' && '&gt;' ||
  838. c == '&' && '&amp;' ||
  839. c == '"' && '&quot;' ||
  840. '&#'+c.charCodeAt()+';'
  841. }
  842. copy(NodeType,Node);
  843. copy(NodeType,Node.prototype);
  844. /**
  845. * @param callback return true for continue,false for break
  846. * @return boolean true: break visit;
  847. */
  848. function _visitNode(node,callback){
  849. if(callback(node)){
  850. return true;
  851. }
  852. if(node = node.firstChild){
  853. do{
  854. if(_visitNode(node,callback)){return true}
  855. }while(node=node.nextSibling)
  856. }
  857. }
  858. function Document(){
  859. }
  860. function _onAddAttribute(doc,el,newAttr){
  861. doc && doc._inc++;
  862. var ns = newAttr.namespaceURI ;
  863. if(ns == 'http://www.w3.org/2000/xmlns/'){
  864. //update namespace
  865. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  866. }
  867. }
  868. function _onRemoveAttribute(doc,el,newAttr,remove){
  869. doc && doc._inc++;
  870. var ns = newAttr.namespaceURI ;
  871. if(ns == 'http://www.w3.org/2000/xmlns/'){
  872. //update namespace
  873. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  874. }
  875. }
  876. function _onUpdateChild(doc,el,newChild){
  877. if(doc && doc._inc){
  878. doc._inc++;
  879. //update childNodes
  880. var cs = el.childNodes;
  881. if(newChild){
  882. cs[cs.length++] = newChild;
  883. }else{
  884. //console.log(1)
  885. var child = el.firstChild;
  886. var i = 0;
  887. while(child){
  888. cs[i++] = child;
  889. child =child.nextSibling;
  890. }
  891. cs.length = i;
  892. }
  893. }
  894. }
  895. /**
  896. * attributes;
  897. * children;
  898. *
  899. * writeable properties:
  900. * nodeValue,Attr:value,CharacterData:data
  901. * prefix
  902. */
  903. function _removeChild(parentNode,child){
  904. var previous = child.previousSibling;
  905. var next = child.nextSibling;
  906. if(previous){
  907. previous.nextSibling = next;
  908. }else{
  909. parentNode.firstChild = next
  910. }
  911. if(next){
  912. next.previousSibling = previous;
  913. }else{
  914. parentNode.lastChild = previous;
  915. }
  916. _onUpdateChild(parentNode.ownerDocument,parentNode);
  917. return child;
  918. }
  919. /**
  920. * preformance key(refChild == null)
  921. */
  922. function _insertBefore(parentNode,newChild,nextChild){
  923. var cp = newChild.parentNode;
  924. if(cp){
  925. cp.removeChild(newChild);//remove and update
  926. }
  927. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  928. var newFirst = newChild.firstChild;
  929. if (newFirst == null) {
  930. return newChild;
  931. }
  932. var newLast = newChild.lastChild;
  933. }else{
  934. newFirst = newLast = newChild;
  935. }
  936. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  937. newFirst.previousSibling = pre;
  938. newLast.nextSibling = nextChild;
  939. if(pre){
  940. pre.nextSibling = newFirst;
  941. }else{
  942. parentNode.firstChild = newFirst;
  943. }
  944. if(nextChild == null){
  945. parentNode.lastChild = newLast;
  946. }else{
  947. nextChild.previousSibling = newLast;
  948. }
  949. do{
  950. newFirst.parentNode = parentNode;
  951. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  952. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  953. //console.log(parentNode.lastChild.nextSibling == null)
  954. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  955. newChild.firstChild = newChild.lastChild = null;
  956. }
  957. return newChild;
  958. }
  959. function _appendSingleChild(parentNode,newChild){
  960. var cp = newChild.parentNode;
  961. if(cp){
  962. var pre = parentNode.lastChild;
  963. cp.removeChild(newChild);//remove and update
  964. var pre = parentNode.lastChild;
  965. }
  966. var pre = parentNode.lastChild;
  967. newChild.parentNode = parentNode;
  968. newChild.previousSibling = pre;
  969. newChild.nextSibling = null;
  970. if(pre){
  971. pre.nextSibling = newChild;
  972. }else{
  973. parentNode.firstChild = newChild;
  974. }
  975. parentNode.lastChild = newChild;
  976. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  977. return newChild;
  978. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  979. }
  980. Document.prototype = {
  981. //implementation : null,
  982. nodeName : '#document',
  983. nodeType : DOCUMENT_NODE,
  984. doctype : null,
  985. documentElement : null,
  986. _inc : 1,
  987. insertBefore : function(newChild, refChild){//raises
  988. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  989. var child = newChild.firstChild;
  990. while(child){
  991. var next = child.nextSibling;
  992. this.insertBefore(child,refChild);
  993. child = next;
  994. }
  995. return newChild;
  996. }
  997. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  998. this.documentElement = newChild;
  999. }
  1000. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  1001. },
  1002. removeChild : function(oldChild){
  1003. if(this.documentElement == oldChild){
  1004. this.documentElement = null;
  1005. }
  1006. return _removeChild(this,oldChild);
  1007. },
  1008. // Introduced in DOM Level 2:
  1009. importNode : function(importedNode,deep){
  1010. return importNode(this,importedNode,deep);
  1011. },
  1012. // Introduced in DOM Level 2:
  1013. getElementById : function(id){
  1014. var rtv = null;
  1015. _visitNode(this.documentElement,function(node){
  1016. if(node.nodeType == ELEMENT_NODE){
  1017. if(node.getAttribute('id') == id){
  1018. rtv = node;
  1019. return true;
  1020. }
  1021. }
  1022. })
  1023. return rtv;
  1024. },
  1025. getElementsByClassName: function(className) {
  1026. var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
  1027. return new LiveNodeList(this, function(base) {
  1028. var ls = [];
  1029. _visitNode(base.documentElement, function(node) {
  1030. if(node !== base && node.nodeType == ELEMENT_NODE) {
  1031. if(pattern.test(node.getAttribute('class'))) {
  1032. ls.push(node);
  1033. }
  1034. }
  1035. });
  1036. return ls;
  1037. });
  1038. },
  1039. //document factory method:
  1040. createElement : function(tagName){
  1041. var node = new Element();
  1042. node.ownerDocument = this;
  1043. node.nodeName = tagName;
  1044. node.tagName = tagName;
  1045. node.childNodes = new NodeList();
  1046. var attrs = node.attributes = new NamedNodeMap();
  1047. attrs._ownerElement = node;
  1048. return node;
  1049. },
  1050. createDocumentFragment : function(){
  1051. var node = new DocumentFragment();
  1052. node.ownerDocument = this;
  1053. node.childNodes = new NodeList();
  1054. return node;
  1055. },
  1056. createTextNode : function(data){
  1057. var node = new Text();
  1058. node.ownerDocument = this;
  1059. node.appendData(data)
  1060. return node;
  1061. },
  1062. createComment : function(data){
  1063. var node = new Comment();
  1064. node.ownerDocument = this;
  1065. node.appendData(data)
  1066. return node;
  1067. },
  1068. createCDATASection : function(data){
  1069. var node = new CDATASection();
  1070. node.ownerDocument = this;
  1071. node.appendData(data)
  1072. return node;
  1073. },
  1074. createProcessingInstruction : function(target,data){
  1075. var node = new ProcessingInstruction();
  1076. node.ownerDocument = this;
  1077. node.tagName = node.target = target;
  1078. node.nodeValue= node.data = data;
  1079. return node;
  1080. },
  1081. createAttribute : function(name){
  1082. var node = new Attr();
  1083. node.ownerDocument = this;
  1084. node.name = name;
  1085. node.nodeName = name;
  1086. node.localName = name;
  1087. node.specified = true;
  1088. return node;
  1089. },
  1090. createEntityReference : function(name){
  1091. var node = new EntityReference();
  1092. node.ownerDocument = this;
  1093. node.nodeName = name;
  1094. return node;
  1095. },
  1096. // Introduced in DOM Level 2:
  1097. createElementNS : function(namespaceURI,qualifiedName){
  1098. var node = new Element();
  1099. var pl = qualifiedName.split(':');
  1100. var attrs = node.attributes = new NamedNodeMap();
  1101. node.childNodes = new NodeList();
  1102. node.ownerDocument = this;
  1103. node.nodeName = qualifiedName;
  1104. node.tagName = qualifiedName;
  1105. node.namespaceURI = namespaceURI;
  1106. if(pl.length == 2){
  1107. node.prefix = pl[0];
  1108. node.localName = pl[1];
  1109. }else{
  1110. //el.prefix = null;
  1111. node.localName = qualifiedName;
  1112. }
  1113. attrs._ownerElement = node;
  1114. return node;
  1115. },
  1116. // Introduced in DOM Level 2:
  1117. createAttributeNS : function(namespaceURI,qualifiedName){
  1118. var node = new Attr();
  1119. var pl = qualifiedName.split(':');
  1120. node.ownerDocument = this;
  1121. node.nodeName = qualifiedName;
  1122. node.name = qualifiedName;
  1123. node.namespaceURI = namespaceURI;
  1124. node.specified = true;
  1125. if(pl.length == 2){
  1126. node.prefix = pl[0];
  1127. node.localName = pl[1];
  1128. }else{
  1129. //el.prefix = null;
  1130. node.localName = qualifiedName;
  1131. }
  1132. return node;
  1133. }
  1134. };
  1135. _extends(Document,Node);
  1136. function Element() {
  1137. this._nsMap = {};
  1138. };
  1139. Element.prototype = {
  1140. nodeType : ELEMENT_NODE,
  1141. hasAttribute : function(name){
  1142. return this.getAttributeNode(name)!=null;
  1143. },
  1144. getAttribute : function(name){
  1145. var attr = this.getAttributeNode(name);
  1146. return attr && attr.value || '';
  1147. },
  1148. getAttributeNode : function(name){
  1149. return this.attributes.getNamedItem(name);
  1150. },
  1151. setAttribute : function(name, value){
  1152. var attr = this.ownerDocument.createAttribute(name);
  1153. attr.value = attr.nodeValue = "" + value;
  1154. this.setAttributeNode(attr)
  1155. },
  1156. removeAttribute : function(name){
  1157. var attr = this.getAttributeNode(name)
  1158. attr && this.removeAttributeNode(attr);
  1159. },
  1160. //four real opeartion method
  1161. appendChild:function(newChild){
  1162. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  1163. return this.insertBefore(newChild,null);
  1164. }else{
  1165. return _appendSingleChild(this,newChild);
  1166. }
  1167. },
  1168. setAttributeNode : function(newAttr){
  1169. return this.attributes.setNamedItem(newAttr);
  1170. },
  1171. setAttributeNodeNS : function(newAttr){
  1172. return this.attributes.setNamedItemNS(newAttr);
  1173. },
  1174. removeAttributeNode : function(oldAttr){
  1175. //console.log(this == oldAttr.ownerElement)
  1176. return this.attributes.removeNamedItem(oldAttr.nodeName);
  1177. },
  1178. //get real attribute name,and remove it by removeAttributeNode
  1179. removeAttributeNS : function(namespaceURI, localName){
  1180. var old = this.getAttributeNodeNS(namespaceURI, localName);
  1181. old && this.removeAttributeNode(old);
  1182. },
  1183. hasAttributeNS : function(namespaceURI, localName){
  1184. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  1185. },
  1186. getAttributeNS : function(namespaceURI, localName){
  1187. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  1188. return attr && attr.value || '';
  1189. },
  1190. setAttributeNS : function(namespaceURI, qualifiedName, value){
  1191. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  1192. attr.value = attr.nodeValue = "" + value;
  1193. this.setAttributeNode(attr)
  1194. },
  1195. getAttributeNodeNS : function(namespaceURI, localName){
  1196. return this.attributes.getNamedItemNS(namespaceURI, localName);
  1197. },
  1198. getElementsByTagName : function(tagName){
  1199. return new LiveNodeList(this,function(base){
  1200. var ls = [];
  1201. _visitNode(base,function(node){
  1202. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  1203. ls.push(node);
  1204. }
  1205. });
  1206. return ls;
  1207. });
  1208. },
  1209. getElementsByTagNameNS : function(namespaceURI, localName){
  1210. return new LiveNodeList(this,function(base){
  1211. var ls = [];
  1212. _visitNode(base,function(node){
  1213. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  1214. ls.push(node);
  1215. }
  1216. });
  1217. return ls;
  1218. });
  1219. }
  1220. };
  1221. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  1222. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  1223. _extends(Element,Node);
  1224. function Attr() {
  1225. };
  1226. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  1227. _extends(Attr,Node);
  1228. function CharacterData() {
  1229. };
  1230. CharacterData.prototype = {
  1231. data : '',
  1232. substringData : function(offset, count) {
  1233. return this.data.substring(offset, offset+count);
  1234. },
  1235. appendData: function(text) {
  1236. text = this.data+text;
  1237. this.nodeValue = this.data = text;
  1238. this.length = text.length;
  1239. },
  1240. insertData: function(offset,text) {
  1241. this.replaceData(offset,0,text);
  1242. },
  1243. appendChild:function(newChild){
  1244. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  1245. },
  1246. deleteData: function(offset, count) {
  1247. this.replaceData(offset,count,"");
  1248. },
  1249. replaceData: function(offset, count, text) {
  1250. var start = this.data.substring(0,offset);
  1251. var end = this.data.substring(offset+count);
  1252. text = start + text + end;
  1253. this.nodeValue = this.data = text;
  1254. this.length = text.length;
  1255. }
  1256. }
  1257. _extends(CharacterData,Node);
  1258. function Text() {
  1259. };
  1260. Text.prototype = {
  1261. nodeName : "#text",
  1262. nodeType : TEXT_NODE,
  1263. splitText : function(offset) {
  1264. var text = this.data;
  1265. var newText = text.substring(offset);
  1266. text = text.substring(0, offset);
  1267. this.data = this.nodeValue = text;
  1268. this.length = text.length;
  1269. var newNode = this.ownerDocument.createTextNode(newText);
  1270. if(this.parentNode){
  1271. this.parentNode.insertBefore(newNode, this.nextSibling);
  1272. }
  1273. return newNode;
  1274. }
  1275. }
  1276. _extends(Text,CharacterData);
  1277. function Comment() {
  1278. };
  1279. Comment.prototype = {
  1280. nodeName : "#comment",
  1281. nodeType : COMMENT_NODE
  1282. }
  1283. _extends(Comment,CharacterData);
  1284. function CDATASection() {
  1285. };
  1286. CDATASection.prototype = {
  1287. nodeName : "#cdata-section",
  1288. nodeType : CDATA_SECTION_NODE
  1289. }
  1290. _extends(CDATASection,CharacterData);
  1291. function DocumentType() {
  1292. };
  1293. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1294. _extends(DocumentType,Node);
  1295. function Notation() {
  1296. };
  1297. Notation.prototype.nodeType = NOTATION_NODE;
  1298. _extends(Notation,Node);
  1299. function Entity() {
  1300. };
  1301. Entity.prototype.nodeType = ENTITY_NODE;
  1302. _extends(Entity,Node);
  1303. function EntityReference() {
  1304. };
  1305. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1306. _extends(EntityReference,Node);
  1307. function DocumentFragment() {
  1308. };
  1309. DocumentFragment.prototype.nodeName = "#document-fragment";
  1310. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1311. _extends(DocumentFragment,Node);
  1312. function ProcessingInstruction() {
  1313. }
  1314. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1315. _extends(ProcessingInstruction,Node);
  1316. function XMLSerializer(){}
  1317. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  1318. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  1319. }
  1320. Node.prototype.toString = nodeSerializeToString;
  1321. function nodeSerializeToString(isHtml,nodeFilter){
  1322. var buf = [];
  1323. var refNode = this.nodeType == 9 && this.documentElement || this;
  1324. var prefix = refNode.prefix;
  1325. var uri = refNode.namespaceURI;
  1326. if(uri && prefix == null){
  1327. //console.log(prefix)
  1328. var prefix = refNode.lookupPrefix(uri);
  1329. if(prefix == null){
  1330. //isHTML = true;
  1331. var visibleNamespaces=[
  1332. {namespace:uri,prefix:null}
  1333. //{namespace:uri,prefix:''}
  1334. ]
  1335. }
  1336. }
  1337. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  1338. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1339. return buf.join('');
  1340. }
  1341. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  1342. var prefix = node.prefix||'';
  1343. var uri = node.namespaceURI;
  1344. if (!prefix && !uri){
  1345. return false;
  1346. }
  1347. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  1348. || uri == 'http://www.w3.org/2000/xmlns/'){
  1349. return false;
  1350. }
  1351. var i = visibleNamespaces.length
  1352. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  1353. while (i--) {
  1354. var ns = visibleNamespaces[i];
  1355. // get namespace prefix
  1356. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  1357. if (ns.prefix == prefix){
  1358. return ns.namespace != uri;
  1359. }
  1360. }
  1361. //console.log(isHTML,uri,prefix=='')
  1362. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  1363. // return false;
  1364. //}
  1365. //node.flag = '11111'
  1366. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  1367. return true;
  1368. }
  1369. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  1370. if(nodeFilter){
  1371. node = nodeFilter(node);
  1372. if(node){
  1373. if(typeof node == 'string'){
  1374. buf.push(node);
  1375. return;
  1376. }
  1377. }else{
  1378. return;
  1379. }
  1380. //buf.sort.apply(attrs, attributeSorter);
  1381. }
  1382. switch(node.nodeType){
  1383. case ELEMENT_NODE:
  1384. if (!visibleNamespaces) visibleNamespaces = [];
  1385. var startVisibleNamespaces = visibleNamespaces.length;
  1386. var attrs = node.attributes;
  1387. var len = attrs.length;
  1388. var child = node.firstChild;
  1389. var nodeName = node.tagName;
  1390. isHTML = (htmlns === node.namespaceURI) ||isHTML
  1391. buf.push('<',nodeName);
  1392. for(var i=0;i<len;i++){
  1393. // add namespaces for attributes
  1394. var attr = attrs.item(i);
  1395. if (attr.prefix == 'xmlns') {
  1396. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1397. }else if(attr.nodeName == 'xmlns'){
  1398. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1399. }
  1400. }
  1401. for(var i=0;i<len;i++){
  1402. var attr = attrs.item(i);
  1403. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  1404. var prefix = attr.prefix||'';
  1405. var uri = attr.namespaceURI;
  1406. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1407. buf.push(ns, '="' , uri , '"');
  1408. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1409. }
  1410. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  1411. }
  1412. // add namespace for current node
  1413. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  1414. var prefix = node.prefix||'';
  1415. var uri = node.namespaceURI;
  1416. if (uri) {
  1417. // Avoid empty namespace value like xmlns:ds=""
  1418. // Empty namespace URL will we produce an invalid XML document
  1419. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1420. buf.push(ns, '="' , uri , '"');
  1421. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1422. }
  1423. }
  1424. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  1425. buf.push('>');
  1426. //if is cdata child node
  1427. if(isHTML && /^script$/i.test(nodeName)){
  1428. while(child){
  1429. if(child.data){
  1430. buf.push(child.data);
  1431. }else{
  1432. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1433. }
  1434. child = child.nextSibling;
  1435. }
  1436. }else
  1437. {
  1438. while(child){
  1439. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1440. child = child.nextSibling;
  1441. }
  1442. }
  1443. buf.push('</',nodeName,'>');
  1444. }else{
  1445. buf.push('/>');
  1446. }
  1447. // remove added visible namespaces
  1448. //visibleNamespaces.length = startVisibleNamespaces;
  1449. return;
  1450. case DOCUMENT_NODE:
  1451. case DOCUMENT_FRAGMENT_NODE:
  1452. var child = node.firstChild;
  1453. while(child){
  1454. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1455. child = child.nextSibling;
  1456. }
  1457. return;
  1458. case ATTRIBUTE_NODE:
  1459. /**
  1460. * Well-formedness constraint: No < in Attribute Values
  1461. * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
  1462. * @see https://www.w3.org/TR/xml/#CleanAttrVals
  1463. * @see https://www.w3.org/TR/xml/#NT-AttValue
  1464. */
  1465. return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
  1466. case TEXT_NODE:
  1467. /**
  1468. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  1469. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  1470. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  1471. * `&amp;` and `&lt;` respectively.
  1472. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  1473. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  1474. * when that string is not marking the end of a CDATA section.
  1475. *
  1476. * In the content of elements, character data is any string of characters
  1477. * which does not contain the start-delimiter of any markup
  1478. * and does not include the CDATA-section-close delimiter, `]]>`.
  1479. *
  1480. * @see https://www.w3.org/TR/xml/#NT-CharData
  1481. */
  1482. return buf.push(node.data
  1483. .replace(/[<&]/g,_xmlEncoder)
  1484. .replace(/]]>/g, ']]&gt;')
  1485. );
  1486. case CDATA_SECTION_NODE:
  1487. return buf.push( '<![CDATA[',node.data,']]>');
  1488. case COMMENT_NODE:
  1489. return buf.push( "<!--",node.data,"-->");
  1490. case DOCUMENT_TYPE_NODE:
  1491. var pubid = node.publicId;
  1492. var sysid = node.systemId;
  1493. buf.push('<!DOCTYPE ',node.name);
  1494. if(pubid){
  1495. buf.push(' PUBLIC ', pubid);
  1496. if (sysid && sysid!='.') {
  1497. buf.push(' ', sysid);
  1498. }
  1499. buf.push('>');
  1500. }else if(sysid && sysid!='.'){
  1501. buf.push(' SYSTEM ', sysid, '>');
  1502. }else{
  1503. var sub = node.internalSubset;
  1504. if(sub){
  1505. buf.push(" [",sub,"]");
  1506. }
  1507. buf.push(">");
  1508. }
  1509. return;
  1510. case PROCESSING_INSTRUCTION_NODE:
  1511. return buf.push( "<?",node.target," ",node.data,"?>");
  1512. case ENTITY_REFERENCE_NODE:
  1513. return buf.push( '&',node.nodeName,';');
  1514. //case ENTITY_NODE:
  1515. //case NOTATION_NODE:
  1516. default:
  1517. buf.push('??',node.nodeName);
  1518. }
  1519. }
  1520. function importNode(doc,node,deep){
  1521. var node2;
  1522. switch (node.nodeType) {
  1523. case ELEMENT_NODE:
  1524. node2 = node.cloneNode(false);
  1525. node2.ownerDocument = doc;
  1526. //var attrs = node2.attributes;
  1527. //var len = attrs.length;
  1528. //for(var i=0;i<len;i++){
  1529. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1530. //}
  1531. case DOCUMENT_FRAGMENT_NODE:
  1532. break;
  1533. case ATTRIBUTE_NODE:
  1534. deep = true;
  1535. break;
  1536. //case ENTITY_REFERENCE_NODE:
  1537. //case PROCESSING_INSTRUCTION_NODE:
  1538. ////case TEXT_NODE:
  1539. //case CDATA_SECTION_NODE:
  1540. //case COMMENT_NODE:
  1541. // deep = false;
  1542. // break;
  1543. //case DOCUMENT_NODE:
  1544. //case DOCUMENT_TYPE_NODE:
  1545. //cannot be imported.
  1546. //case ENTITY_NODE:
  1547. //case NOTATION_NODE:
  1548. //can not hit in level3
  1549. //default:throw e;
  1550. }
  1551. if(!node2){
  1552. node2 = node.cloneNode(false);//false
  1553. }
  1554. node2.ownerDocument = doc;
  1555. node2.parentNode = null;
  1556. if(deep){
  1557. var child = node.firstChild;
  1558. while(child){
  1559. node2.appendChild(importNode(doc,child,deep));
  1560. child = child.nextSibling;
  1561. }
  1562. }
  1563. return node2;
  1564. }
  1565. //
  1566. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1567. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1568. function cloneNode(doc,node,deep){
  1569. var node2 = new node.constructor();
  1570. for(var n in node){
  1571. var v = node[n];
  1572. if(typeof v != 'object' ){
  1573. if(v != node2[n]){
  1574. node2[n] = v;
  1575. }
  1576. }
  1577. }
  1578. if(node.childNodes){
  1579. node2.childNodes = new NodeList();
  1580. }
  1581. node2.ownerDocument = doc;
  1582. switch (node2.nodeType) {
  1583. case ELEMENT_NODE:
  1584. var attrs = node.attributes;
  1585. var attrs2 = node2.attributes = new NamedNodeMap();
  1586. var len = attrs.length
  1587. attrs2._ownerElement = node2;
  1588. for(var i=0;i<len;i++){
  1589. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  1590. }
  1591. break;;
  1592. case ATTRIBUTE_NODE:
  1593. deep = true;
  1594. }
  1595. if(deep){
  1596. var child = node.firstChild;
  1597. while(child){
  1598. node2.appendChild(cloneNode(doc,child,deep));
  1599. child = child.nextSibling;
  1600. }
  1601. }
  1602. return node2;
  1603. }
  1604. function __set__(object,key,value){
  1605. object[key] = value
  1606. }
  1607. //do dynamic
  1608. try{
  1609. if(Object.defineProperty){
  1610. Object.defineProperty(LiveNodeList.prototype,'length',{
  1611. get:function(){
  1612. _updateLiveList(this);
  1613. return this.$$length;
  1614. }
  1615. });
  1616. Object.defineProperty(Node.prototype,'textContent',{
  1617. get:function(){
  1618. return getTextContent(this);
  1619. },
  1620. set:function(data){
  1621. switch(this.nodeType){
  1622. case ELEMENT_NODE:
  1623. case DOCUMENT_FRAGMENT_NODE:
  1624. while(this.firstChild){
  1625. this.removeChild(this.firstChild);
  1626. }
  1627. if(data || String(data)){
  1628. this.appendChild(this.ownerDocument.createTextNode(data));
  1629. }
  1630. break;
  1631. default:
  1632. //TODO:
  1633. this.data = data;
  1634. this.value = data;
  1635. this.nodeValue = data;
  1636. }
  1637. }
  1638. })
  1639. function getTextContent(node){
  1640. switch(node.nodeType){
  1641. case ELEMENT_NODE:
  1642. case DOCUMENT_FRAGMENT_NODE:
  1643. var buf = [];
  1644. node = node.firstChild;
  1645. while(node){
  1646. if(node.nodeType!==7 && node.nodeType !==8){
  1647. buf.push(getTextContent(node));
  1648. }
  1649. node = node.nextSibling;
  1650. }
  1651. return buf.join('');
  1652. default:
  1653. return node.nodeValue;
  1654. }
  1655. }
  1656. __set__ = function(object,key,value){
  1657. //console.log(value)
  1658. object['$$'+key] = value
  1659. }
  1660. }
  1661. }catch(e){//ie8
  1662. }
  1663. //if(typeof require == 'function'){
  1664. exports.Node = Node;
  1665. exports.DOMException = DOMException;
  1666. exports.DOMImplementation = DOMImplementation;
  1667. exports.XMLSerializer = XMLSerializer;
  1668. //}
  1669. },{}],4:[function(require,module,exports){
  1670. exports.entityMap = {
  1671. lt: '<',
  1672. gt: '>',
  1673. amp: '&',
  1674. quot: '"',
  1675. apos: "'",
  1676. Agrave: "À",
  1677. Aacute: "Á",
  1678. Acirc: "Â",
  1679. Atilde: "Ã",
  1680. Auml: "Ä",
  1681. Aring: "Å",
  1682. AElig: "Æ",
  1683. Ccedil: "Ç",
  1684. Egrave: "È",
  1685. Eacute: "É",
  1686. Ecirc: "Ê",
  1687. Euml: "Ë",
  1688. Igrave: "Ì",
  1689. Iacute: "Í",
  1690. Icirc: "Î",
  1691. Iuml: "Ï",
  1692. ETH: "Ð",
  1693. Ntilde: "Ñ",
  1694. Ograve: "Ò",
  1695. Oacute: "Ó",
  1696. Ocirc: "Ô",
  1697. Otilde: "Õ",
  1698. Ouml: "Ö",
  1699. Oslash: "Ø",
  1700. Ugrave: "Ù",
  1701. Uacute: "Ú",
  1702. Ucirc: "Û",
  1703. Uuml: "Ü",
  1704. Yacute: "Ý",
  1705. THORN: "Þ",
  1706. szlig: "ß",
  1707. agrave: "à",
  1708. aacute: "á",
  1709. acirc: "â",
  1710. atilde: "ã",
  1711. auml: "ä",
  1712. aring: "å",
  1713. aelig: "æ",
  1714. ccedil: "ç",
  1715. egrave: "è",
  1716. eacute: "é",
  1717. ecirc: "ê",
  1718. euml: "ë",
  1719. igrave: "ì",
  1720. iacute: "í",
  1721. icirc: "î",
  1722. iuml: "ï",
  1723. eth: "ð",
  1724. ntilde: "ñ",
  1725. ograve: "ò",
  1726. oacute: "ó",
  1727. ocirc: "ô",
  1728. otilde: "õ",
  1729. ouml: "ö",
  1730. oslash: "ø",
  1731. ugrave: "ù",
  1732. uacute: "ú",
  1733. ucirc: "û",
  1734. uuml: "ü",
  1735. yacute: "ý",
  1736. thorn: "þ",
  1737. yuml: "ÿ",
  1738. nbsp: "\u00a0",
  1739. iexcl: "¡",
  1740. cent: "¢",
  1741. pound: "£",
  1742. curren: "¤",
  1743. yen: "¥",
  1744. brvbar: "¦",
  1745. sect: "§",
  1746. uml: "¨",
  1747. copy: "©",
  1748. ordf: "ª",
  1749. laquo: "«",
  1750. not: "¬",
  1751. shy: "­­",
  1752. reg: "®",
  1753. macr: "¯",
  1754. deg: "°",
  1755. plusmn: "±",
  1756. sup2: "²",
  1757. sup3: "³",
  1758. acute: "´",
  1759. micro: "µ",
  1760. para: "¶",
  1761. middot: "·",
  1762. cedil: "¸",
  1763. sup1: "¹",
  1764. ordm: "º",
  1765. raquo: "»",
  1766. frac14: "¼",
  1767. frac12: "½",
  1768. frac34: "¾",
  1769. iquest: "¿",
  1770. times: "×",
  1771. divide: "÷",
  1772. forall: "∀",
  1773. part: "∂",
  1774. exist: "∃",
  1775. empty: "∅",
  1776. nabla: "∇",
  1777. isin: "∈",
  1778. notin: "∉",
  1779. ni: "∋",
  1780. prod: "∏",
  1781. sum: "∑",
  1782. minus: "−",
  1783. lowast: "∗",
  1784. radic: "√",
  1785. prop: "∝",
  1786. infin: "∞",
  1787. ang: "∠",
  1788. and: "∧",
  1789. or: "∨",
  1790. cap: "∩",
  1791. cup: "∪",
  1792. 'int': "∫",
  1793. there4: "∴",
  1794. sim: "∼",
  1795. cong: "≅",
  1796. asymp: "≈",
  1797. ne: "≠",
  1798. equiv: "≡",
  1799. le: "≤",
  1800. ge: "≥",
  1801. sub: "⊂",
  1802. sup: "⊃",
  1803. nsub: "⊄",
  1804. sube: "⊆",
  1805. supe: "⊇",
  1806. oplus: "⊕",
  1807. otimes: "⊗",
  1808. perp: "⊥",
  1809. sdot: "⋅",
  1810. Alpha: "Α",
  1811. Beta: "Β",
  1812. Gamma: "Γ",
  1813. Delta: "Δ",
  1814. Epsilon: "Ε",
  1815. Zeta: "Ζ",
  1816. Eta: "Η",
  1817. Theta: "Θ",
  1818. Iota: "Ι",
  1819. Kappa: "Κ",
  1820. Lambda: "Λ",
  1821. Mu: "Μ",
  1822. Nu: "Ν",
  1823. Xi: "Ξ",
  1824. Omicron: "Ο",
  1825. Pi: "Π",
  1826. Rho: "Ρ",
  1827. Sigma: "Σ",
  1828. Tau: "Τ",
  1829. Upsilon: "Υ",
  1830. Phi: "Φ",
  1831. Chi: "Χ",
  1832. Psi: "Ψ",
  1833. Omega: "Ω",
  1834. alpha: "α",
  1835. beta: "β",
  1836. gamma: "γ",
  1837. delta: "δ",
  1838. epsilon: "ε",
  1839. zeta: "ζ",
  1840. eta: "η",
  1841. theta: "θ",
  1842. iota: "ι",
  1843. kappa: "κ",
  1844. lambda: "λ",
  1845. mu: "μ",
  1846. nu: "ν",
  1847. xi: "ξ",
  1848. omicron: "ο",
  1849. pi: "π",
  1850. rho: "ρ",
  1851. sigmaf: "ς",
  1852. sigma: "σ",
  1853. tau: "τ",
  1854. upsilon: "υ",
  1855. phi: "φ",
  1856. chi: "χ",
  1857. psi: "ψ",
  1858. omega: "ω",
  1859. thetasym: "ϑ",
  1860. upsih: "ϒ",
  1861. piv: "ϖ",
  1862. OElig: "Œ",
  1863. oelig: "œ",
  1864. Scaron: "Š",
  1865. scaron: "š",
  1866. Yuml: "Ÿ",
  1867. fnof: "ƒ",
  1868. circ: "ˆ",
  1869. tilde: "˜",
  1870. ensp: " ",
  1871. emsp: " ",
  1872. thinsp: " ",
  1873. zwnj: "‌",
  1874. zwj: "‍",
  1875. lrm: "‎",
  1876. rlm: "‏",
  1877. ndash: "–",
  1878. mdash: "—",
  1879. lsquo: "‘",
  1880. rsquo: "’",
  1881. sbquo: "‚",
  1882. ldquo: "“",
  1883. rdquo: "”",
  1884. bdquo: "„",
  1885. dagger: "†",
  1886. Dagger: "‡",
  1887. bull: "•",
  1888. hellip: "…",
  1889. permil: "‰",
  1890. prime: "′",
  1891. Prime: "″",
  1892. lsaquo: "‹",
  1893. rsaquo: "›",
  1894. oline: "‾",
  1895. euro: "€",
  1896. trade: "™",
  1897. larr: "←",
  1898. uarr: "↑",
  1899. rarr: "→",
  1900. darr: "↓",
  1901. harr: "↔",
  1902. crarr: "↵",
  1903. lceil: "⌈",
  1904. rceil: "⌉",
  1905. lfloor: "⌊",
  1906. rfloor: "⌋",
  1907. loz: "◊",
  1908. spades: "♠",
  1909. clubs: "♣",
  1910. hearts: "♥",
  1911. diams: "♦"
  1912. };
  1913. },{}],5:[function(require,module,exports){
  1914. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  1915. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  1916. //[5] Name ::= NameStartChar (NameChar)*
  1917. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  1918. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  1919. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  1920. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  1921. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  1922. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  1923. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  1924. var S_TAG = 0;//tag name offerring
  1925. var S_ATTR = 1;//attr name offerring
  1926. var S_ATTR_SPACE=2;//attr name end and space offer
  1927. var S_EQ = 3;//=space?
  1928. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  1929. var S_ATTR_END = 5;//attr value end and no space(quot end)
  1930. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  1931. var S_TAG_CLOSE = 7;//closed el<el />
  1932. /**
  1933. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  1934. *
  1935. * @param {string} message
  1936. * @param {any?} locator Optional, can provide details about the location in the source
  1937. * @constructor
  1938. */
  1939. function ParseError(message, locator) {
  1940. this.message = message
  1941. this.locator = locator
  1942. if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
  1943. }
  1944. ParseError.prototype = new Error();
  1945. ParseError.prototype.name = ParseError.name
  1946. function XMLReader(){
  1947. }
  1948. XMLReader.prototype = {
  1949. parse:function(source,defaultNSMap,entityMap){
  1950. var domBuilder = this.domBuilder;
  1951. domBuilder.startDocument();
  1952. _copy(defaultNSMap ,defaultNSMap = {})
  1953. parse(source,defaultNSMap,entityMap,
  1954. domBuilder,this.errorHandler);
  1955. domBuilder.endDocument();
  1956. }
  1957. }
  1958. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  1959. function fixedFromCharCode(code) {
  1960. // String.prototype.fromCharCode does not supports
  1961. // > 2 bytes unicode chars directly
  1962. if (code > 0xffff) {
  1963. code -= 0x10000;
  1964. var surrogate1 = 0xd800 + (code >> 10)
  1965. , surrogate2 = 0xdc00 + (code & 0x3ff);
  1966. return String.fromCharCode(surrogate1, surrogate2);
  1967. } else {
  1968. return String.fromCharCode(code);
  1969. }
  1970. }
  1971. function entityReplacer(a){
  1972. var k = a.slice(1,-1);
  1973. if(k in entityMap){
  1974. return entityMap[k];
  1975. }else if(k.charAt(0) === '#'){
  1976. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  1977. }else{
  1978. errorHandler.error('entity not found:'+a);
  1979. return a;
  1980. }
  1981. }
  1982. function appendText(end){//has some bugs
  1983. if(end>start){
  1984. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  1985. locator&&position(start);
  1986. domBuilder.characters(xt,0,end-start);
  1987. start = end
  1988. }
  1989. }
  1990. function position(p,m){
  1991. while(p>=lineEnd && (m = linePattern.exec(source))){
  1992. lineStart = m.index;
  1993. lineEnd = lineStart + m[0].length;
  1994. locator.lineNumber++;
  1995. //console.log('line++:',locator,startPos,endPos)
  1996. }
  1997. locator.columnNumber = p-lineStart+1;
  1998. }
  1999. var lineStart = 0;
  2000. var lineEnd = 0;
  2001. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  2002. var locator = domBuilder.locator;
  2003. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  2004. var closeMap = {};
  2005. var start = 0;
  2006. while(true){
  2007. try{
  2008. var tagStart = source.indexOf('<',start);
  2009. if(tagStart<0){
  2010. if(!source.substr(start).match(/^\s*$/)){
  2011. var doc = domBuilder.doc;
  2012. var text = doc.createTextNode(source.substr(start));
  2013. doc.appendChild(text);
  2014. domBuilder.currentElement = text;
  2015. }
  2016. return;
  2017. }
  2018. if(tagStart>start){
  2019. appendText(tagStart);
  2020. }
  2021. switch(source.charAt(tagStart+1)){
  2022. case '/':
  2023. var end = source.indexOf('>',tagStart+3);
  2024. var tagName = source.substring(tagStart+2,end);
  2025. var config = parseStack.pop();
  2026. if(end<0){
  2027. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  2028. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  2029. end = tagStart+1+tagName.length;
  2030. }else if(tagName.match(/\s</)){
  2031. tagName = tagName.replace(/[\s<].*/,'');
  2032. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  2033. end = tagStart+1+tagName.length;
  2034. }
  2035. var localNSMap = config.localNSMap;
  2036. var endMatch = config.tagName == tagName;
  2037. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  2038. if(endIgnoreCaseMach){
  2039. domBuilder.endElement(config.uri,config.localName,tagName);
  2040. if(localNSMap){
  2041. for(var prefix in localNSMap){
  2042. domBuilder.endPrefixMapping(prefix) ;
  2043. }
  2044. }
  2045. if(!endMatch){
  2046. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
  2047. }
  2048. }else{
  2049. parseStack.push(config)
  2050. }
  2051. end++;
  2052. break;
  2053. // end elment
  2054. case '?':// <?...?>
  2055. locator&&position(tagStart);
  2056. end = parseInstruction(source,tagStart,domBuilder);
  2057. break;
  2058. case '!':// <!doctype,<![CDATA,<!--
  2059. locator&&position(tagStart);
  2060. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  2061. break;
  2062. default:
  2063. locator&&position(tagStart);
  2064. var el = new ElementAttributes();
  2065. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  2066. //elStartEnd
  2067. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  2068. var len = el.length;
  2069. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  2070. el.closed = true;
  2071. if(!entityMap.nbsp){
  2072. errorHandler.warning('unclosed xml attribute');
  2073. }
  2074. }
  2075. if(locator && len){
  2076. var locator2 = copyLocator(locator,{});
  2077. //try{//attribute position fixed
  2078. for(var i = 0;i<len;i++){
  2079. var a = el[i];
  2080. position(a.offset);
  2081. a.locator = copyLocator(locator,{});
  2082. }
  2083. domBuilder.locator = locator2
  2084. if(appendElement(el,domBuilder,currentNSMap)){
  2085. parseStack.push(el)
  2086. }
  2087. domBuilder.locator = locator;
  2088. }else{
  2089. if(appendElement(el,domBuilder,currentNSMap)){
  2090. parseStack.push(el)
  2091. }
  2092. }
  2093. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  2094. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  2095. }else{
  2096. end++;
  2097. }
  2098. }
  2099. }catch(e){
  2100. if (e instanceof ParseError) {
  2101. throw e;
  2102. }
  2103. errorHandler.error('element parse error: '+e)
  2104. end = -1;
  2105. }
  2106. if(end>start){
  2107. start = end;
  2108. }else{
  2109. //TODO: 这里有可能sax回退,有位置错误风险
  2110. appendText(Math.max(tagStart,start)+1);
  2111. }
  2112. }
  2113. }
  2114. function copyLocator(f,t){
  2115. t.lineNumber = f.lineNumber;
  2116. t.columnNumber = f.columnNumber;
  2117. return t;
  2118. }
  2119. /**
  2120. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  2121. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  2122. */
  2123. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  2124. /**
  2125. * @param {string} qname
  2126. * @param {string} value
  2127. * @param {number} startIndex
  2128. */
  2129. function addAttribute(qname, value, startIndex) {
  2130. if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
  2131. el.addValue(qname, value, startIndex)
  2132. }
  2133. var attrName;
  2134. var value;
  2135. var p = ++start;
  2136. var s = S_TAG;//status
  2137. while(true){
  2138. var c = source.charAt(p);
  2139. switch(c){
  2140. case '=':
  2141. if(s === S_ATTR){//attrName
  2142. attrName = source.slice(start,p);
  2143. s = S_EQ;
  2144. }else if(s === S_ATTR_SPACE){
  2145. s = S_EQ;
  2146. }else{
  2147. //fatalError: equal must after attrName or space after attrName
  2148. throw new Error('attribute equal must after attrName'); // No known test case
  2149. }
  2150. break;
  2151. case '\'':
  2152. case '"':
  2153. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  2154. ){//equal
  2155. if(s === S_ATTR){
  2156. errorHandler.warning('attribute value must after "="')
  2157. attrName = source.slice(start,p)
  2158. }
  2159. start = p+1;
  2160. p = source.indexOf(c,start)
  2161. if(p>0){
  2162. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  2163. addAttribute(attrName, value, start-1);
  2164. s = S_ATTR_END;
  2165. }else{
  2166. //fatalError: no end quot match
  2167. throw new Error('attribute value no end \''+c+'\' match');
  2168. }
  2169. }else if(s == S_ATTR_NOQUOT_VALUE){
  2170. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  2171. //console.log(attrName,value,start,p)
  2172. addAttribute(attrName, value, start);
  2173. //console.dir(el)
  2174. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  2175. start = p+1;
  2176. s = S_ATTR_END
  2177. }else{
  2178. //fatalError: no equal before
  2179. throw new Error('attribute value must after "="'); // No known test case
  2180. }
  2181. break;
  2182. case '/':
  2183. switch(s){
  2184. case S_TAG:
  2185. el.setTagName(source.slice(start,p));
  2186. case S_ATTR_END:
  2187. case S_TAG_SPACE:
  2188. case S_TAG_CLOSE:
  2189. s =S_TAG_CLOSE;
  2190. el.closed = true;
  2191. case S_ATTR_NOQUOT_VALUE:
  2192. case S_ATTR:
  2193. case S_ATTR_SPACE:
  2194. break;
  2195. //case S_EQ:
  2196. default:
  2197. throw new Error("attribute invalid close char('/')") // No known test case
  2198. }
  2199. break;
  2200. case ''://end document
  2201. errorHandler.error('unexpected end of input');
  2202. if(s == S_TAG){
  2203. el.setTagName(source.slice(start,p));
  2204. }
  2205. return p;
  2206. case '>':
  2207. switch(s){
  2208. case S_TAG:
  2209. el.setTagName(source.slice(start,p));
  2210. case S_ATTR_END:
  2211. case S_TAG_SPACE:
  2212. case S_TAG_CLOSE:
  2213. break;//normal
  2214. case S_ATTR_NOQUOT_VALUE://Compatible state
  2215. case S_ATTR:
  2216. value = source.slice(start,p);
  2217. if(value.slice(-1) === '/'){
  2218. el.closed = true;
  2219. value = value.slice(0,-1)
  2220. }
  2221. case S_ATTR_SPACE:
  2222. if(s === S_ATTR_SPACE){
  2223. value = attrName;
  2224. }
  2225. if(s == S_ATTR_NOQUOT_VALUE){
  2226. errorHandler.warning('attribute "'+value+'" missed quot(")!');
  2227. addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start)
  2228. }else{
  2229. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  2230. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  2231. }
  2232. addAttribute(value, value, start)
  2233. }
  2234. break;
  2235. case S_EQ:
  2236. throw new Error('attribute value missed!!');
  2237. }
  2238. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  2239. return p;
  2240. /*xml space '\x20' | #x9 | #xD | #xA; */
  2241. case '\u0080':
  2242. c = ' ';
  2243. default:
  2244. if(c<= ' '){//space
  2245. switch(s){
  2246. case S_TAG:
  2247. el.setTagName(source.slice(start,p));//tagName
  2248. s = S_TAG_SPACE;
  2249. break;
  2250. case S_ATTR:
  2251. attrName = source.slice(start,p)
  2252. s = S_ATTR_SPACE;
  2253. break;
  2254. case S_ATTR_NOQUOT_VALUE:
  2255. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  2256. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  2257. addAttribute(attrName, value, start)
  2258. case S_ATTR_END:
  2259. s = S_TAG_SPACE;
  2260. break;
  2261. //case S_TAG_SPACE:
  2262. //case S_EQ:
  2263. //case S_ATTR_SPACE:
  2264. // void();break;
  2265. //case S_TAG_CLOSE:
  2266. //ignore warning
  2267. }
  2268. }else{//not space
  2269. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  2270. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  2271. switch(s){
  2272. //case S_TAG:void();break;
  2273. //case S_ATTR:void();break;
  2274. //case S_ATTR_NOQUOT_VALUE:void();break;
  2275. case S_ATTR_SPACE:
  2276. var tagName = el.tagName;
  2277. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  2278. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  2279. }
  2280. addAttribute(attrName, attrName, start);
  2281. start = p;
  2282. s = S_ATTR;
  2283. break;
  2284. case S_ATTR_END:
  2285. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  2286. case S_TAG_SPACE:
  2287. s = S_ATTR;
  2288. start = p;
  2289. break;
  2290. case S_EQ:
  2291. s = S_ATTR_NOQUOT_VALUE;
  2292. start = p;
  2293. break;
  2294. case S_TAG_CLOSE:
  2295. throw new Error("elements closed character '/' and '>' must be connected to");
  2296. }
  2297. }
  2298. }//end outer switch
  2299. //console.log('p++',p)
  2300. p++;
  2301. }
  2302. }
  2303. /**
  2304. * @return true if has new namespace define
  2305. */
  2306. function appendElement(el,domBuilder,currentNSMap){
  2307. var tagName = el.tagName;
  2308. var localNSMap = null;
  2309. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  2310. var i = el.length;
  2311. while(i--){
  2312. var a = el[i];
  2313. var qName = a.qName;
  2314. var value = a.value;
  2315. var nsp = qName.indexOf(':');
  2316. if(nsp>0){
  2317. var prefix = a.prefix = qName.slice(0,nsp);
  2318. var localName = qName.slice(nsp+1);
  2319. var nsPrefix = prefix === 'xmlns' && localName
  2320. }else{
  2321. localName = qName;
  2322. prefix = null
  2323. nsPrefix = qName === 'xmlns' && ''
  2324. }
  2325. //can not set prefix,because prefix !== ''
  2326. a.localName = localName ;
  2327. //prefix == null for no ns prefix attribute
  2328. if(nsPrefix !== false){//hack!!
  2329. if(localNSMap == null){
  2330. localNSMap = {}
  2331. //console.log(currentNSMap,0)
  2332. _copy(currentNSMap,currentNSMap={})
  2333. //console.log(currentNSMap,1)
  2334. }
  2335. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  2336. a.uri = 'http://www.w3.org/2000/xmlns/'
  2337. domBuilder.startPrefixMapping(nsPrefix, value)
  2338. }
  2339. }
  2340. var i = el.length;
  2341. while(i--){
  2342. a = el[i];
  2343. var prefix = a.prefix;
  2344. if(prefix){//no prefix attribute has no namespace
  2345. if(prefix === 'xml'){
  2346. a.uri = 'http://www.w3.org/XML/1998/namespace';
  2347. }if(prefix !== 'xmlns'){
  2348. a.uri = currentNSMap[prefix || '']
  2349. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  2350. }
  2351. }
  2352. }
  2353. var nsp = tagName.indexOf(':');
  2354. if(nsp>0){
  2355. prefix = el.prefix = tagName.slice(0,nsp);
  2356. localName = el.localName = tagName.slice(nsp+1);
  2357. }else{
  2358. prefix = null;//important!!
  2359. localName = el.localName = tagName;
  2360. }
  2361. //no prefix element has default namespace
  2362. var ns = el.uri = currentNSMap[prefix || ''];
  2363. domBuilder.startElement(ns,localName,tagName,el);
  2364. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  2365. //localNSMap = null
  2366. if(el.closed){
  2367. domBuilder.endElement(ns,localName,tagName);
  2368. if(localNSMap){
  2369. for(prefix in localNSMap){
  2370. domBuilder.endPrefixMapping(prefix)
  2371. }
  2372. }
  2373. }else{
  2374. el.currentNSMap = currentNSMap;
  2375. el.localNSMap = localNSMap;
  2376. //parseStack.push(el);
  2377. return true;
  2378. }
  2379. }
  2380. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  2381. if(/^(?:script|textarea)$/i.test(tagName)){
  2382. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  2383. var text = source.substring(elStartEnd+1,elEndStart);
  2384. if(/[&<]/.test(text)){
  2385. if(/^script$/i.test(tagName)){
  2386. //if(!/\]\]>/.test(text)){
  2387. //lexHandler.startCDATA();
  2388. domBuilder.characters(text,0,text.length);
  2389. //lexHandler.endCDATA();
  2390. return elEndStart;
  2391. //}
  2392. }//}else{//text area
  2393. text = text.replace(/&#?\w+;/g,entityReplacer);
  2394. domBuilder.characters(text,0,text.length);
  2395. return elEndStart;
  2396. //}
  2397. }
  2398. }
  2399. return elStartEnd+1;
  2400. }
  2401. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  2402. //if(tagName in closeMap){
  2403. var pos = closeMap[tagName];
  2404. if(pos == null){
  2405. //console.log(tagName)
  2406. pos = source.lastIndexOf('</'+tagName+'>')
  2407. if(pos<elStartEnd){//忘记闭合
  2408. pos = source.lastIndexOf('</'+tagName)
  2409. }
  2410. closeMap[tagName] =pos
  2411. }
  2412. return pos<elStartEnd;
  2413. //}
  2414. }
  2415. function _copy(source,target){
  2416. for(var n in source){target[n] = source[n]}
  2417. }
  2418. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  2419. var next= source.charAt(start+2)
  2420. switch(next){
  2421. case '-':
  2422. if(source.charAt(start + 3) === '-'){
  2423. var end = source.indexOf('-->',start+4);
  2424. //append comment source.substring(4,end)//<!--
  2425. if(end>start){
  2426. domBuilder.comment(source,start+4,end-start-4);
  2427. return end+3;
  2428. }else{
  2429. errorHandler.error("Unclosed comment");
  2430. return -1;
  2431. }
  2432. }else{
  2433. //error
  2434. return -1;
  2435. }
  2436. default:
  2437. if(source.substr(start+3,6) == 'CDATA['){
  2438. var end = source.indexOf(']]>',start+9);
  2439. domBuilder.startCDATA();
  2440. domBuilder.characters(source,start+9,end-start-9);
  2441. domBuilder.endCDATA()
  2442. return end+3;
  2443. }
  2444. //<!DOCTYPE
  2445. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  2446. var matchs = split(source,start);
  2447. var len = matchs.length;
  2448. if(len>1 && /!doctype/i.test(matchs[0][0])){
  2449. var name = matchs[1][0];
  2450. var pubid = false;
  2451. var sysid = false;
  2452. if(len>3){
  2453. if(/^public$/i.test(matchs[2][0])){
  2454. pubid = matchs[3][0];
  2455. sysid = len>4 && matchs[4][0];
  2456. }else if(/^system$/i.test(matchs[2][0])){
  2457. sysid = matchs[3][0];
  2458. }
  2459. }
  2460. var lastMatch = matchs[len-1]
  2461. domBuilder.startDTD(name, pubid, sysid);
  2462. domBuilder.endDTD();
  2463. return lastMatch.index+lastMatch[0].length
  2464. }
  2465. }
  2466. return -1;
  2467. }
  2468. function parseInstruction(source,start,domBuilder){
  2469. var end = source.indexOf('?>',start);
  2470. if(end){
  2471. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  2472. if(match){
  2473. var len = match[0].length;
  2474. domBuilder.processingInstruction(match[1], match[2]) ;
  2475. return end+2;
  2476. }else{//error
  2477. return -1;
  2478. }
  2479. }
  2480. return -1;
  2481. }
  2482. function ElementAttributes(){
  2483. this.attributeNames = {}
  2484. }
  2485. ElementAttributes.prototype = {
  2486. setTagName:function(tagName){
  2487. if(!tagNamePattern.test(tagName)){
  2488. throw new Error('invalid tagName:'+tagName)
  2489. }
  2490. this.tagName = tagName
  2491. },
  2492. addValue:function(qName, value, offset) {
  2493. if(!tagNamePattern.test(qName)){
  2494. throw new Error('invalid attribute:'+qName)
  2495. }
  2496. this.attributeNames[qName] = this.length;
  2497. this[this.length++] = {qName:qName,value:value,offset:offset}
  2498. },
  2499. length:0,
  2500. getLocalName:function(i){return this[i].localName},
  2501. getLocator:function(i){return this[i].locator},
  2502. getQName:function(i){return this[i].qName},
  2503. getURI:function(i){return this[i].uri},
  2504. getValue:function(i){return this[i].value}
  2505. // ,getIndex:function(uri, localName)){
  2506. // if(localName){
  2507. //
  2508. // }else{
  2509. // var qName = uri
  2510. // }
  2511. // },
  2512. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  2513. // getType:function(uri,localName){}
  2514. // getType:function(i){},
  2515. }
  2516. function split(source,start){
  2517. var match;
  2518. var buf = [];
  2519. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  2520. reg.lastIndex = start;
  2521. reg.exec(source);//skip <
  2522. while(match = reg.exec(source)){
  2523. buf.push(match);
  2524. if(match[1])return buf;
  2525. }
  2526. }
  2527. exports.XMLReader = XMLReader;
  2528. exports.ParseError = ParseError;
  2529. },{}],6:[function(require,module,exports){
  2530. 'use strict'
  2531. exports.byteLength = byteLength
  2532. exports.toByteArray = toByteArray
  2533. exports.fromByteArray = fromByteArray
  2534. var lookup = []
  2535. var revLookup = []
  2536. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  2537. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  2538. for (var i = 0, len = code.length; i < len; ++i) {
  2539. lookup[i] = code[i]
  2540. revLookup[code.charCodeAt(i)] = i
  2541. }
  2542. // Support decoding URL-safe base64 strings, as Node.js does.
  2543. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  2544. revLookup['-'.charCodeAt(0)] = 62
  2545. revLookup['_'.charCodeAt(0)] = 63
  2546. function getLens (b64) {
  2547. var len = b64.length
  2548. if (len % 4 > 0) {
  2549. throw new Error('Invalid string. Length must be a multiple of 4')
  2550. }
  2551. // Trim off extra bytes after placeholder bytes are found
  2552. // See: https://github.com/beatgammit/base64-js/issues/42
  2553. var validLen = b64.indexOf('=')
  2554. if (validLen === -1) validLen = len
  2555. var placeHoldersLen = validLen === len
  2556. ? 0
  2557. : 4 - (validLen % 4)
  2558. return [validLen, placeHoldersLen]
  2559. }
  2560. // base64 is 4/3 + up to two characters of the original data
  2561. function byteLength (b64) {
  2562. var lens = getLens(b64)
  2563. var validLen = lens[0]
  2564. var placeHoldersLen = lens[1]
  2565. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2566. }
  2567. function _byteLength (b64, validLen, placeHoldersLen) {
  2568. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  2569. }
  2570. function toByteArray (b64) {
  2571. var tmp
  2572. var lens = getLens(b64)
  2573. var validLen = lens[0]
  2574. var placeHoldersLen = lens[1]
  2575. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  2576. var curByte = 0
  2577. // if there are placeholders, only get up to the last complete 4 chars
  2578. var len = placeHoldersLen > 0
  2579. ? validLen - 4
  2580. : validLen
  2581. var i
  2582. for (i = 0; i < len; i += 4) {
  2583. tmp =
  2584. (revLookup[b64.charCodeAt(i)] << 18) |
  2585. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  2586. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  2587. revLookup[b64.charCodeAt(i + 3)]
  2588. arr[curByte++] = (tmp >> 16) & 0xFF
  2589. arr[curByte++] = (tmp >> 8) & 0xFF
  2590. arr[curByte++] = tmp & 0xFF
  2591. }
  2592. if (placeHoldersLen === 2) {
  2593. tmp =
  2594. (revLookup[b64.charCodeAt(i)] << 2) |
  2595. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  2596. arr[curByte++] = tmp & 0xFF
  2597. }
  2598. if (placeHoldersLen === 1) {
  2599. tmp =
  2600. (revLookup[b64.charCodeAt(i)] << 10) |
  2601. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  2602. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  2603. arr[curByte++] = (tmp >> 8) & 0xFF
  2604. arr[curByte++] = tmp & 0xFF
  2605. }
  2606. return arr
  2607. }
  2608. function tripletToBase64 (num) {
  2609. return lookup[num >> 18 & 0x3F] +
  2610. lookup[num >> 12 & 0x3F] +
  2611. lookup[num >> 6 & 0x3F] +
  2612. lookup[num & 0x3F]
  2613. }
  2614. function encodeChunk (uint8, start, end) {
  2615. var tmp
  2616. var output = []
  2617. for (var i = start; i < end; i += 3) {
  2618. tmp =
  2619. ((uint8[i] << 16) & 0xFF0000) +
  2620. ((uint8[i + 1] << 8) & 0xFF00) +
  2621. (uint8[i + 2] & 0xFF)
  2622. output.push(tripletToBase64(tmp))
  2623. }
  2624. return output.join('')
  2625. }
  2626. function fromByteArray (uint8) {
  2627. var tmp
  2628. var len = uint8.length
  2629. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  2630. var parts = []
  2631. var maxChunkLength = 16383 // must be multiple of 3
  2632. // go through the array every three bytes, we'll deal with trailing stuff later
  2633. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  2634. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  2635. }
  2636. // pad the end with zeros, but make sure to not forget the extra bytes
  2637. if (extraBytes === 1) {
  2638. tmp = uint8[len - 1]
  2639. parts.push(
  2640. lookup[tmp >> 2] +
  2641. lookup[(tmp << 4) & 0x3F] +
  2642. '=='
  2643. )
  2644. } else if (extraBytes === 2) {
  2645. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  2646. parts.push(
  2647. lookup[tmp >> 10] +
  2648. lookup[(tmp >> 4) & 0x3F] +
  2649. lookup[(tmp << 2) & 0x3F] +
  2650. '='
  2651. )
  2652. }
  2653. return parts.join('')
  2654. }
  2655. },{}],7:[function(require,module,exports){
  2656. (function (Buffer){(function (){
  2657. /*!
  2658. * The buffer module from node.js, for the browser.
  2659. *
  2660. * @author Feross Aboukhadijeh <https://feross.org>
  2661. * @license MIT
  2662. */
  2663. /* eslint-disable no-proto */
  2664. 'use strict'
  2665. var base64 = require('base64-js')
  2666. var ieee754 = require('ieee754')
  2667. exports.Buffer = Buffer
  2668. exports.SlowBuffer = SlowBuffer
  2669. exports.INSPECT_MAX_BYTES = 50
  2670. var K_MAX_LENGTH = 0x7fffffff
  2671. exports.kMaxLength = K_MAX_LENGTH
  2672. /**
  2673. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2674. * === true Use Uint8Array implementation (fastest)
  2675. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2676. * implementation (most compatible, even IE6)
  2677. *
  2678. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2679. * Opera 11.6+, iOS 4.2+.
  2680. *
  2681. * We report that the browser does not support typed arrays if the are not subclassable
  2682. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2683. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2684. * for __proto__ and has a buggy typed array implementation.
  2685. */
  2686. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2687. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2688. typeof console.error === 'function') {
  2689. console.error(
  2690. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2691. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2692. )
  2693. }
  2694. function typedArraySupport () {
  2695. // Can typed array instances can be augmented?
  2696. try {
  2697. var arr = new Uint8Array(1)
  2698. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2699. return arr.foo() === 42
  2700. } catch (e) {
  2701. return false
  2702. }
  2703. }
  2704. Object.defineProperty(Buffer.prototype, 'parent', {
  2705. enumerable: true,
  2706. get: function () {
  2707. if (!Buffer.isBuffer(this)) return undefined
  2708. return this.buffer
  2709. }
  2710. })
  2711. Object.defineProperty(Buffer.prototype, 'offset', {
  2712. enumerable: true,
  2713. get: function () {
  2714. if (!Buffer.isBuffer(this)) return undefined
  2715. return this.byteOffset
  2716. }
  2717. })
  2718. function createBuffer (length) {
  2719. if (length > K_MAX_LENGTH) {
  2720. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2721. }
  2722. // Return an augmented `Uint8Array` instance
  2723. var buf = new Uint8Array(length)
  2724. buf.__proto__ = Buffer.prototype
  2725. return buf
  2726. }
  2727. /**
  2728. * The Buffer constructor returns instances of `Uint8Array` that have their
  2729. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2730. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2731. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2732. * returns a single octet.
  2733. *
  2734. * The `Uint8Array` prototype remains unmodified.
  2735. */
  2736. function Buffer (arg, encodingOrOffset, length) {
  2737. // Common case.
  2738. if (typeof arg === 'number') {
  2739. if (typeof encodingOrOffset === 'string') {
  2740. throw new TypeError(
  2741. 'The "string" argument must be of type string. Received type number'
  2742. )
  2743. }
  2744. return allocUnsafe(arg)
  2745. }
  2746. return from(arg, encodingOrOffset, length)
  2747. }
  2748. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2749. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2750. Buffer[Symbol.species] === Buffer) {
  2751. Object.defineProperty(Buffer, Symbol.species, {
  2752. value: null,
  2753. configurable: true,
  2754. enumerable: false,
  2755. writable: false
  2756. })
  2757. }
  2758. Buffer.poolSize = 8192 // not used by this implementation
  2759. function from (value, encodingOrOffset, length) {
  2760. if (typeof value === 'string') {
  2761. return fromString(value, encodingOrOffset)
  2762. }
  2763. if (ArrayBuffer.isView(value)) {
  2764. return fromArrayLike(value)
  2765. }
  2766. if (value == null) {
  2767. throw TypeError(
  2768. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2769. 'or Array-like Object. Received type ' + (typeof value)
  2770. )
  2771. }
  2772. if (isInstance(value, ArrayBuffer) ||
  2773. (value && isInstance(value.buffer, ArrayBuffer))) {
  2774. return fromArrayBuffer(value, encodingOrOffset, length)
  2775. }
  2776. if (typeof value === 'number') {
  2777. throw new TypeError(
  2778. 'The "value" argument must not be of type number. Received type number'
  2779. )
  2780. }
  2781. var valueOf = value.valueOf && value.valueOf()
  2782. if (valueOf != null && valueOf !== value) {
  2783. return Buffer.from(valueOf, encodingOrOffset, length)
  2784. }
  2785. var b = fromObject(value)
  2786. if (b) return b
  2787. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2788. typeof value[Symbol.toPrimitive] === 'function') {
  2789. return Buffer.from(
  2790. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2791. )
  2792. }
  2793. throw new TypeError(
  2794. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2795. 'or Array-like Object. Received type ' + (typeof value)
  2796. )
  2797. }
  2798. /**
  2799. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2800. * if value is a number.
  2801. * Buffer.from(str[, encoding])
  2802. * Buffer.from(array)
  2803. * Buffer.from(buffer)
  2804. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2805. **/
  2806. Buffer.from = function (value, encodingOrOffset, length) {
  2807. return from(value, encodingOrOffset, length)
  2808. }
  2809. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2810. // https://github.com/feross/buffer/pull/148
  2811. Buffer.prototype.__proto__ = Uint8Array.prototype
  2812. Buffer.__proto__ = Uint8Array
  2813. function assertSize (size) {
  2814. if (typeof size !== 'number') {
  2815. throw new TypeError('"size" argument must be of type number')
  2816. } else if (size < 0) {
  2817. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2818. }
  2819. }
  2820. function alloc (size, fill, encoding) {
  2821. assertSize(size)
  2822. if (size <= 0) {
  2823. return createBuffer(size)
  2824. }
  2825. if (fill !== undefined) {
  2826. // Only pay attention to encoding if it's a string. This
  2827. // prevents accidentally sending in a number that would
  2828. // be interpretted as a start offset.
  2829. return typeof encoding === 'string'
  2830. ? createBuffer(size).fill(fill, encoding)
  2831. : createBuffer(size).fill(fill)
  2832. }
  2833. return createBuffer(size)
  2834. }
  2835. /**
  2836. * Creates a new filled Buffer instance.
  2837. * alloc(size[, fill[, encoding]])
  2838. **/
  2839. Buffer.alloc = function (size, fill, encoding) {
  2840. return alloc(size, fill, encoding)
  2841. }
  2842. function allocUnsafe (size) {
  2843. assertSize(size)
  2844. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2845. }
  2846. /**
  2847. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2848. * */
  2849. Buffer.allocUnsafe = function (size) {
  2850. return allocUnsafe(size)
  2851. }
  2852. /**
  2853. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2854. */
  2855. Buffer.allocUnsafeSlow = function (size) {
  2856. return allocUnsafe(size)
  2857. }
  2858. function fromString (string, encoding) {
  2859. if (typeof encoding !== 'string' || encoding === '') {
  2860. encoding = 'utf8'
  2861. }
  2862. if (!Buffer.isEncoding(encoding)) {
  2863. throw new TypeError('Unknown encoding: ' + encoding)
  2864. }
  2865. var length = byteLength(string, encoding) | 0
  2866. var buf = createBuffer(length)
  2867. var actual = buf.write(string, encoding)
  2868. if (actual !== length) {
  2869. // Writing a hex string, for example, that contains invalid characters will
  2870. // cause everything after the first invalid character to be ignored. (e.g.
  2871. // 'abxxcd' will be treated as 'ab')
  2872. buf = buf.slice(0, actual)
  2873. }
  2874. return buf
  2875. }
  2876. function fromArrayLike (array) {
  2877. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2878. var buf = createBuffer(length)
  2879. for (var i = 0; i < length; i += 1) {
  2880. buf[i] = array[i] & 255
  2881. }
  2882. return buf
  2883. }
  2884. function fromArrayBuffer (array, byteOffset, length) {
  2885. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2886. throw new RangeError('"offset" is outside of buffer bounds')
  2887. }
  2888. if (array.byteLength < byteOffset + (length || 0)) {
  2889. throw new RangeError('"length" is outside of buffer bounds')
  2890. }
  2891. var buf
  2892. if (byteOffset === undefined && length === undefined) {
  2893. buf = new Uint8Array(array)
  2894. } else if (length === undefined) {
  2895. buf = new Uint8Array(array, byteOffset)
  2896. } else {
  2897. buf = new Uint8Array(array, byteOffset, length)
  2898. }
  2899. // Return an augmented `Uint8Array` instance
  2900. buf.__proto__ = Buffer.prototype
  2901. return buf
  2902. }
  2903. function fromObject (obj) {
  2904. if (Buffer.isBuffer(obj)) {
  2905. var len = checked(obj.length) | 0
  2906. var buf = createBuffer(len)
  2907. if (buf.length === 0) {
  2908. return buf
  2909. }
  2910. obj.copy(buf, 0, 0, len)
  2911. return buf
  2912. }
  2913. if (obj.length !== undefined) {
  2914. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2915. return createBuffer(0)
  2916. }
  2917. return fromArrayLike(obj)
  2918. }
  2919. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2920. return fromArrayLike(obj.data)
  2921. }
  2922. }
  2923. function checked (length) {
  2924. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2925. // length is NaN (which is otherwise coerced to zero.)
  2926. if (length >= K_MAX_LENGTH) {
  2927. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2928. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2929. }
  2930. return length | 0
  2931. }
  2932. function SlowBuffer (length) {
  2933. if (+length != length) { // eslint-disable-line eqeqeq
  2934. length = 0
  2935. }
  2936. return Buffer.alloc(+length)
  2937. }
  2938. Buffer.isBuffer = function isBuffer (b) {
  2939. return b != null && b._isBuffer === true &&
  2940. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2941. }
  2942. Buffer.compare = function compare (a, b) {
  2943. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2944. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2945. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2946. throw new TypeError(
  2947. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2948. )
  2949. }
  2950. if (a === b) return 0
  2951. var x = a.length
  2952. var y = b.length
  2953. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2954. if (a[i] !== b[i]) {
  2955. x = a[i]
  2956. y = b[i]
  2957. break
  2958. }
  2959. }
  2960. if (x < y) return -1
  2961. if (y < x) return 1
  2962. return 0
  2963. }
  2964. Buffer.isEncoding = function isEncoding (encoding) {
  2965. switch (String(encoding).toLowerCase()) {
  2966. case 'hex':
  2967. case 'utf8':
  2968. case 'utf-8':
  2969. case 'ascii':
  2970. case 'latin1':
  2971. case 'binary':
  2972. case 'base64':
  2973. case 'ucs2':
  2974. case 'ucs-2':
  2975. case 'utf16le':
  2976. case 'utf-16le':
  2977. return true
  2978. default:
  2979. return false
  2980. }
  2981. }
  2982. Buffer.concat = function concat (list, length) {
  2983. if (!Array.isArray(list)) {
  2984. throw new TypeError('"list" argument must be an Array of Buffers')
  2985. }
  2986. if (list.length === 0) {
  2987. return Buffer.alloc(0)
  2988. }
  2989. var i
  2990. if (length === undefined) {
  2991. length = 0
  2992. for (i = 0; i < list.length; ++i) {
  2993. length += list[i].length
  2994. }
  2995. }
  2996. var buffer = Buffer.allocUnsafe(length)
  2997. var pos = 0
  2998. for (i = 0; i < list.length; ++i) {
  2999. var buf = list[i]
  3000. if (isInstance(buf, Uint8Array)) {
  3001. buf = Buffer.from(buf)
  3002. }
  3003. if (!Buffer.isBuffer(buf)) {
  3004. throw new TypeError('"list" argument must be an Array of Buffers')
  3005. }
  3006. buf.copy(buffer, pos)
  3007. pos += buf.length
  3008. }
  3009. return buffer
  3010. }
  3011. function byteLength (string, encoding) {
  3012. if (Buffer.isBuffer(string)) {
  3013. return string.length
  3014. }
  3015. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  3016. return string.byteLength
  3017. }
  3018. if (typeof string !== 'string') {
  3019. throw new TypeError(
  3020. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  3021. 'Received type ' + typeof string
  3022. )
  3023. }
  3024. var len = string.length
  3025. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  3026. if (!mustMatch && len === 0) return 0
  3027. // Use a for loop to avoid recursion
  3028. var loweredCase = false
  3029. for (;;) {
  3030. switch (encoding) {
  3031. case 'ascii':
  3032. case 'latin1':
  3033. case 'binary':
  3034. return len
  3035. case 'utf8':
  3036. case 'utf-8':
  3037. return utf8ToBytes(string).length
  3038. case 'ucs2':
  3039. case 'ucs-2':
  3040. case 'utf16le':
  3041. case 'utf-16le':
  3042. return len * 2
  3043. case 'hex':
  3044. return len >>> 1
  3045. case 'base64':
  3046. return base64ToBytes(string).length
  3047. default:
  3048. if (loweredCase) {
  3049. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  3050. }
  3051. encoding = ('' + encoding).toLowerCase()
  3052. loweredCase = true
  3053. }
  3054. }
  3055. }
  3056. Buffer.byteLength = byteLength
  3057. function slowToString (encoding, start, end) {
  3058. var loweredCase = false
  3059. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  3060. // property of a typed array.
  3061. // This behaves neither like String nor Uint8Array in that we set start/end
  3062. // to their upper/lower bounds if the value passed is out of range.
  3063. // undefined is handled specially as per ECMA-262 6th Edition,
  3064. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  3065. if (start === undefined || start < 0) {
  3066. start = 0
  3067. }
  3068. // Return early if start > this.length. Done here to prevent potential uint32
  3069. // coercion fail below.
  3070. if (start > this.length) {
  3071. return ''
  3072. }
  3073. if (end === undefined || end > this.length) {
  3074. end = this.length
  3075. }
  3076. if (end <= 0) {
  3077. return ''
  3078. }
  3079. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  3080. end >>>= 0
  3081. start >>>= 0
  3082. if (end <= start) {
  3083. return ''
  3084. }
  3085. if (!encoding) encoding = 'utf8'
  3086. while (true) {
  3087. switch (encoding) {
  3088. case 'hex':
  3089. return hexSlice(this, start, end)
  3090. case 'utf8':
  3091. case 'utf-8':
  3092. return utf8Slice(this, start, end)
  3093. case 'ascii':
  3094. return asciiSlice(this, start, end)
  3095. case 'latin1':
  3096. case 'binary':
  3097. return latin1Slice(this, start, end)
  3098. case 'base64':
  3099. return base64Slice(this, start, end)
  3100. case 'ucs2':
  3101. case 'ucs-2':
  3102. case 'utf16le':
  3103. case 'utf-16le':
  3104. return utf16leSlice(this, start, end)
  3105. default:
  3106. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3107. encoding = (encoding + '').toLowerCase()
  3108. loweredCase = true
  3109. }
  3110. }
  3111. }
  3112. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  3113. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  3114. // reliably in a browserify context because there could be multiple different
  3115. // copies of the 'buffer' package in use. This method works even for Buffer
  3116. // instances that were created from another copy of the `buffer` package.
  3117. // See: https://github.com/feross/buffer/issues/154
  3118. Buffer.prototype._isBuffer = true
  3119. function swap (b, n, m) {
  3120. var i = b[n]
  3121. b[n] = b[m]
  3122. b[m] = i
  3123. }
  3124. Buffer.prototype.swap16 = function swap16 () {
  3125. var len = this.length
  3126. if (len % 2 !== 0) {
  3127. throw new RangeError('Buffer size must be a multiple of 16-bits')
  3128. }
  3129. for (var i = 0; i < len; i += 2) {
  3130. swap(this, i, i + 1)
  3131. }
  3132. return this
  3133. }
  3134. Buffer.prototype.swap32 = function swap32 () {
  3135. var len = this.length
  3136. if (len % 4 !== 0) {
  3137. throw new RangeError('Buffer size must be a multiple of 32-bits')
  3138. }
  3139. for (var i = 0; i < len; i += 4) {
  3140. swap(this, i, i + 3)
  3141. swap(this, i + 1, i + 2)
  3142. }
  3143. return this
  3144. }
  3145. Buffer.prototype.swap64 = function swap64 () {
  3146. var len = this.length
  3147. if (len % 8 !== 0) {
  3148. throw new RangeError('Buffer size must be a multiple of 64-bits')
  3149. }
  3150. for (var i = 0; i < len; i += 8) {
  3151. swap(this, i, i + 7)
  3152. swap(this, i + 1, i + 6)
  3153. swap(this, i + 2, i + 5)
  3154. swap(this, i + 3, i + 4)
  3155. }
  3156. return this
  3157. }
  3158. Buffer.prototype.toString = function toString () {
  3159. var length = this.length
  3160. if (length === 0) return ''
  3161. if (arguments.length === 0) return utf8Slice(this, 0, length)
  3162. return slowToString.apply(this, arguments)
  3163. }
  3164. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  3165. Buffer.prototype.equals = function equals (b) {
  3166. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  3167. if (this === b) return true
  3168. return Buffer.compare(this, b) === 0
  3169. }
  3170. Buffer.prototype.inspect = function inspect () {
  3171. var str = ''
  3172. var max = exports.INSPECT_MAX_BYTES
  3173. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  3174. if (this.length > max) str += ' ... '
  3175. return '<Buffer ' + str + '>'
  3176. }
  3177. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  3178. if (isInstance(target, Uint8Array)) {
  3179. target = Buffer.from(target, target.offset, target.byteLength)
  3180. }
  3181. if (!Buffer.isBuffer(target)) {
  3182. throw new TypeError(
  3183. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  3184. 'Received type ' + (typeof target)
  3185. )
  3186. }
  3187. if (start === undefined) {
  3188. start = 0
  3189. }
  3190. if (end === undefined) {
  3191. end = target ? target.length : 0
  3192. }
  3193. if (thisStart === undefined) {
  3194. thisStart = 0
  3195. }
  3196. if (thisEnd === undefined) {
  3197. thisEnd = this.length
  3198. }
  3199. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  3200. throw new RangeError('out of range index')
  3201. }
  3202. if (thisStart >= thisEnd && start >= end) {
  3203. return 0
  3204. }
  3205. if (thisStart >= thisEnd) {
  3206. return -1
  3207. }
  3208. if (start >= end) {
  3209. return 1
  3210. }
  3211. start >>>= 0
  3212. end >>>= 0
  3213. thisStart >>>= 0
  3214. thisEnd >>>= 0
  3215. if (this === target) return 0
  3216. var x = thisEnd - thisStart
  3217. var y = end - start
  3218. var len = Math.min(x, y)
  3219. var thisCopy = this.slice(thisStart, thisEnd)
  3220. var targetCopy = target.slice(start, end)
  3221. for (var i = 0; i < len; ++i) {
  3222. if (thisCopy[i] !== targetCopy[i]) {
  3223. x = thisCopy[i]
  3224. y = targetCopy[i]
  3225. break
  3226. }
  3227. }
  3228. if (x < y) return -1
  3229. if (y < x) return 1
  3230. return 0
  3231. }
  3232. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  3233. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  3234. //
  3235. // Arguments:
  3236. // - buffer - a Buffer to search
  3237. // - val - a string, Buffer, or number
  3238. // - byteOffset - an index into `buffer`; will be clamped to an int32
  3239. // - encoding - an optional encoding, relevant is val is a string
  3240. // - dir - true for indexOf, false for lastIndexOf
  3241. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  3242. // Empty buffer means no match
  3243. if (buffer.length === 0) return -1
  3244. // Normalize byteOffset
  3245. if (typeof byteOffset === 'string') {
  3246. encoding = byteOffset
  3247. byteOffset = 0
  3248. } else if (byteOffset > 0x7fffffff) {
  3249. byteOffset = 0x7fffffff
  3250. } else if (byteOffset < -0x80000000) {
  3251. byteOffset = -0x80000000
  3252. }
  3253. byteOffset = +byteOffset // Coerce to Number.
  3254. if (numberIsNaN(byteOffset)) {
  3255. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  3256. byteOffset = dir ? 0 : (buffer.length - 1)
  3257. }
  3258. // Normalize byteOffset: negative offsets start from the end of the buffer
  3259. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  3260. if (byteOffset >= buffer.length) {
  3261. if (dir) return -1
  3262. else byteOffset = buffer.length - 1
  3263. } else if (byteOffset < 0) {
  3264. if (dir) byteOffset = 0
  3265. else return -1
  3266. }
  3267. // Normalize val
  3268. if (typeof val === 'string') {
  3269. val = Buffer.from(val, encoding)
  3270. }
  3271. // Finally, search either indexOf (if dir is true) or lastIndexOf
  3272. if (Buffer.isBuffer(val)) {
  3273. // Special case: looking for empty string/buffer always fails
  3274. if (val.length === 0) {
  3275. return -1
  3276. }
  3277. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  3278. } else if (typeof val === 'number') {
  3279. val = val & 0xFF // Search for a byte value [0-255]
  3280. if (typeof Uint8Array.prototype.indexOf === 'function') {
  3281. if (dir) {
  3282. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  3283. } else {
  3284. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  3285. }
  3286. }
  3287. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  3288. }
  3289. throw new TypeError('val must be string, number or Buffer')
  3290. }
  3291. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  3292. var indexSize = 1
  3293. var arrLength = arr.length
  3294. var valLength = val.length
  3295. if (encoding !== undefined) {
  3296. encoding = String(encoding).toLowerCase()
  3297. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  3298. encoding === 'utf16le' || encoding === 'utf-16le') {
  3299. if (arr.length < 2 || val.length < 2) {
  3300. return -1
  3301. }
  3302. indexSize = 2
  3303. arrLength /= 2
  3304. valLength /= 2
  3305. byteOffset /= 2
  3306. }
  3307. }
  3308. function read (buf, i) {
  3309. if (indexSize === 1) {
  3310. return buf[i]
  3311. } else {
  3312. return buf.readUInt16BE(i * indexSize)
  3313. }
  3314. }
  3315. var i
  3316. if (dir) {
  3317. var foundIndex = -1
  3318. for (i = byteOffset; i < arrLength; i++) {
  3319. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  3320. if (foundIndex === -1) foundIndex = i
  3321. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  3322. } else {
  3323. if (foundIndex !== -1) i -= i - foundIndex
  3324. foundIndex = -1
  3325. }
  3326. }
  3327. } else {
  3328. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  3329. for (i = byteOffset; i >= 0; i--) {
  3330. var found = true
  3331. for (var j = 0; j < valLength; j++) {
  3332. if (read(arr, i + j) !== read(val, j)) {
  3333. found = false
  3334. break
  3335. }
  3336. }
  3337. if (found) return i
  3338. }
  3339. }
  3340. return -1
  3341. }
  3342. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  3343. return this.indexOf(val, byteOffset, encoding) !== -1
  3344. }
  3345. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  3346. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  3347. }
  3348. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  3349. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  3350. }
  3351. function hexWrite (buf, string, offset, length) {
  3352. offset = Number(offset) || 0
  3353. var remaining = buf.length - offset
  3354. if (!length) {
  3355. length = remaining
  3356. } else {
  3357. length = Number(length)
  3358. if (length > remaining) {
  3359. length = remaining
  3360. }
  3361. }
  3362. var strLen = string.length
  3363. if (length > strLen / 2) {
  3364. length = strLen / 2
  3365. }
  3366. for (var i = 0; i < length; ++i) {
  3367. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3368. if (numberIsNaN(parsed)) return i
  3369. buf[offset + i] = parsed
  3370. }
  3371. return i
  3372. }
  3373. function utf8Write (buf, string, offset, length) {
  3374. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3375. }
  3376. function asciiWrite (buf, string, offset, length) {
  3377. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3378. }
  3379. function latin1Write (buf, string, offset, length) {
  3380. return asciiWrite(buf, string, offset, length)
  3381. }
  3382. function base64Write (buf, string, offset, length) {
  3383. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3384. }
  3385. function ucs2Write (buf, string, offset, length) {
  3386. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3387. }
  3388. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3389. // Buffer#write(string)
  3390. if (offset === undefined) {
  3391. encoding = 'utf8'
  3392. length = this.length
  3393. offset = 0
  3394. // Buffer#write(string, encoding)
  3395. } else if (length === undefined && typeof offset === 'string') {
  3396. encoding = offset
  3397. length = this.length
  3398. offset = 0
  3399. // Buffer#write(string, offset[, length][, encoding])
  3400. } else if (isFinite(offset)) {
  3401. offset = offset >>> 0
  3402. if (isFinite(length)) {
  3403. length = length >>> 0
  3404. if (encoding === undefined) encoding = 'utf8'
  3405. } else {
  3406. encoding = length
  3407. length = undefined
  3408. }
  3409. } else {
  3410. throw new Error(
  3411. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3412. )
  3413. }
  3414. var remaining = this.length - offset
  3415. if (length === undefined || length > remaining) length = remaining
  3416. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3417. throw new RangeError('Attempt to write outside buffer bounds')
  3418. }
  3419. if (!encoding) encoding = 'utf8'
  3420. var loweredCase = false
  3421. for (;;) {
  3422. switch (encoding) {
  3423. case 'hex':
  3424. return hexWrite(this, string, offset, length)
  3425. case 'utf8':
  3426. case 'utf-8':
  3427. return utf8Write(this, string, offset, length)
  3428. case 'ascii':
  3429. return asciiWrite(this, string, offset, length)
  3430. case 'latin1':
  3431. case 'binary':
  3432. return latin1Write(this, string, offset, length)
  3433. case 'base64':
  3434. // Warning: maxLength not taken into account in base64Write
  3435. return base64Write(this, string, offset, length)
  3436. case 'ucs2':
  3437. case 'ucs-2':
  3438. case 'utf16le':
  3439. case 'utf-16le':
  3440. return ucs2Write(this, string, offset, length)
  3441. default:
  3442. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3443. encoding = ('' + encoding).toLowerCase()
  3444. loweredCase = true
  3445. }
  3446. }
  3447. }
  3448. Buffer.prototype.toJSON = function toJSON () {
  3449. return {
  3450. type: 'Buffer',
  3451. data: Array.prototype.slice.call(this._arr || this, 0)
  3452. }
  3453. }
  3454. function base64Slice (buf, start, end) {
  3455. if (start === 0 && end === buf.length) {
  3456. return base64.fromByteArray(buf)
  3457. } else {
  3458. return base64.fromByteArray(buf.slice(start, end))
  3459. }
  3460. }
  3461. function utf8Slice (buf, start, end) {
  3462. end = Math.min(buf.length, end)
  3463. var res = []
  3464. var i = start
  3465. while (i < end) {
  3466. var firstByte = buf[i]
  3467. var codePoint = null
  3468. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3469. : (firstByte > 0xDF) ? 3
  3470. : (firstByte > 0xBF) ? 2
  3471. : 1
  3472. if (i + bytesPerSequence <= end) {
  3473. var secondByte, thirdByte, fourthByte, tempCodePoint
  3474. switch (bytesPerSequence) {
  3475. case 1:
  3476. if (firstByte < 0x80) {
  3477. codePoint = firstByte
  3478. }
  3479. break
  3480. case 2:
  3481. secondByte = buf[i + 1]
  3482. if ((secondByte & 0xC0) === 0x80) {
  3483. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3484. if (tempCodePoint > 0x7F) {
  3485. codePoint = tempCodePoint
  3486. }
  3487. }
  3488. break
  3489. case 3:
  3490. secondByte = buf[i + 1]
  3491. thirdByte = buf[i + 2]
  3492. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3493. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  3494. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3495. codePoint = tempCodePoint
  3496. }
  3497. }
  3498. break
  3499. case 4:
  3500. secondByte = buf[i + 1]
  3501. thirdByte = buf[i + 2]
  3502. fourthByte = buf[i + 3]
  3503. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3504. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  3505. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3506. codePoint = tempCodePoint
  3507. }
  3508. }
  3509. }
  3510. }
  3511. if (codePoint === null) {
  3512. // we did not generate a valid codePoint so insert a
  3513. // replacement char (U+FFFD) and advance only 1 byte
  3514. codePoint = 0xFFFD
  3515. bytesPerSequence = 1
  3516. } else if (codePoint > 0xFFFF) {
  3517. // encode to utf16 (surrogate pair dance)
  3518. codePoint -= 0x10000
  3519. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3520. codePoint = 0xDC00 | codePoint & 0x3FF
  3521. }
  3522. res.push(codePoint)
  3523. i += bytesPerSequence
  3524. }
  3525. return decodeCodePointsArray(res)
  3526. }
  3527. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3528. // the lowest limit is Chrome, with 0x10000 args.
  3529. // We go 1 magnitude less, for safety
  3530. var MAX_ARGUMENTS_LENGTH = 0x1000
  3531. function decodeCodePointsArray (codePoints) {
  3532. var len = codePoints.length
  3533. if (len <= MAX_ARGUMENTS_LENGTH) {
  3534. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3535. }
  3536. // Decode in chunks to avoid "call stack size exceeded".
  3537. var res = ''
  3538. var i = 0
  3539. while (i < len) {
  3540. res += String.fromCharCode.apply(
  3541. String,
  3542. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3543. )
  3544. }
  3545. return res
  3546. }
  3547. function asciiSlice (buf, start, end) {
  3548. var ret = ''
  3549. end = Math.min(buf.length, end)
  3550. for (var i = start; i < end; ++i) {
  3551. ret += String.fromCharCode(buf[i] & 0x7F)
  3552. }
  3553. return ret
  3554. }
  3555. function latin1Slice (buf, start, end) {
  3556. var ret = ''
  3557. end = Math.min(buf.length, end)
  3558. for (var i = start; i < end; ++i) {
  3559. ret += String.fromCharCode(buf[i])
  3560. }
  3561. return ret
  3562. }
  3563. function hexSlice (buf, start, end) {
  3564. var len = buf.length
  3565. if (!start || start < 0) start = 0
  3566. if (!end || end < 0 || end > len) end = len
  3567. var out = ''
  3568. for (var i = start; i < end; ++i) {
  3569. out += toHex(buf[i])
  3570. }
  3571. return out
  3572. }
  3573. function utf16leSlice (buf, start, end) {
  3574. var bytes = buf.slice(start, end)
  3575. var res = ''
  3576. for (var i = 0; i < bytes.length; i += 2) {
  3577. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3578. }
  3579. return res
  3580. }
  3581. Buffer.prototype.slice = function slice (start, end) {
  3582. var len = this.length
  3583. start = ~~start
  3584. end = end === undefined ? len : ~~end
  3585. if (start < 0) {
  3586. start += len
  3587. if (start < 0) start = 0
  3588. } else if (start > len) {
  3589. start = len
  3590. }
  3591. if (end < 0) {
  3592. end += len
  3593. if (end < 0) end = 0
  3594. } else if (end > len) {
  3595. end = len
  3596. }
  3597. if (end < start) end = start
  3598. var newBuf = this.subarray(start, end)
  3599. // Return an augmented `Uint8Array` instance
  3600. newBuf.__proto__ = Buffer.prototype
  3601. return newBuf
  3602. }
  3603. /*
  3604. * Need to make sure that buffer isn't trying to write out of bounds.
  3605. */
  3606. function checkOffset (offset, ext, length) {
  3607. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3608. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3609. }
  3610. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3611. offset = offset >>> 0
  3612. byteLength = byteLength >>> 0
  3613. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3614. var val = this[offset]
  3615. var mul = 1
  3616. var i = 0
  3617. while (++i < byteLength && (mul *= 0x100)) {
  3618. val += this[offset + i] * mul
  3619. }
  3620. return val
  3621. }
  3622. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3623. offset = offset >>> 0
  3624. byteLength = byteLength >>> 0
  3625. if (!noAssert) {
  3626. checkOffset(offset, byteLength, this.length)
  3627. }
  3628. var val = this[offset + --byteLength]
  3629. var mul = 1
  3630. while (byteLength > 0 && (mul *= 0x100)) {
  3631. val += this[offset + --byteLength] * mul
  3632. }
  3633. return val
  3634. }
  3635. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3636. offset = offset >>> 0
  3637. if (!noAssert) checkOffset(offset, 1, this.length)
  3638. return this[offset]
  3639. }
  3640. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3641. offset = offset >>> 0
  3642. if (!noAssert) checkOffset(offset, 2, this.length)
  3643. return this[offset] | (this[offset + 1] << 8)
  3644. }
  3645. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3646. offset = offset >>> 0
  3647. if (!noAssert) checkOffset(offset, 2, this.length)
  3648. return (this[offset] << 8) | this[offset + 1]
  3649. }
  3650. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3651. offset = offset >>> 0
  3652. if (!noAssert) checkOffset(offset, 4, this.length)
  3653. return ((this[offset]) |
  3654. (this[offset + 1] << 8) |
  3655. (this[offset + 2] << 16)) +
  3656. (this[offset + 3] * 0x1000000)
  3657. }
  3658. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3659. offset = offset >>> 0
  3660. if (!noAssert) checkOffset(offset, 4, this.length)
  3661. return (this[offset] * 0x1000000) +
  3662. ((this[offset + 1] << 16) |
  3663. (this[offset + 2] << 8) |
  3664. this[offset + 3])
  3665. }
  3666. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3667. offset = offset >>> 0
  3668. byteLength = byteLength >>> 0
  3669. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3670. var val = this[offset]
  3671. var mul = 1
  3672. var i = 0
  3673. while (++i < byteLength && (mul *= 0x100)) {
  3674. val += this[offset + i] * mul
  3675. }
  3676. mul *= 0x80
  3677. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3678. return val
  3679. }
  3680. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3681. offset = offset >>> 0
  3682. byteLength = byteLength >>> 0
  3683. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3684. var i = byteLength
  3685. var mul = 1
  3686. var val = this[offset + --i]
  3687. while (i > 0 && (mul *= 0x100)) {
  3688. val += this[offset + --i] * mul
  3689. }
  3690. mul *= 0x80
  3691. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3692. return val
  3693. }
  3694. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3695. offset = offset >>> 0
  3696. if (!noAssert) checkOffset(offset, 1, this.length)
  3697. if (!(this[offset] & 0x80)) return (this[offset])
  3698. return ((0xff - this[offset] + 1) * -1)
  3699. }
  3700. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3701. offset = offset >>> 0
  3702. if (!noAssert) checkOffset(offset, 2, this.length)
  3703. var val = this[offset] | (this[offset + 1] << 8)
  3704. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3705. }
  3706. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3707. offset = offset >>> 0
  3708. if (!noAssert) checkOffset(offset, 2, this.length)
  3709. var val = this[offset + 1] | (this[offset] << 8)
  3710. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3711. }
  3712. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3713. offset = offset >>> 0
  3714. if (!noAssert) checkOffset(offset, 4, this.length)
  3715. return (this[offset]) |
  3716. (this[offset + 1] << 8) |
  3717. (this[offset + 2] << 16) |
  3718. (this[offset + 3] << 24)
  3719. }
  3720. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3721. offset = offset >>> 0
  3722. if (!noAssert) checkOffset(offset, 4, this.length)
  3723. return (this[offset] << 24) |
  3724. (this[offset + 1] << 16) |
  3725. (this[offset + 2] << 8) |
  3726. (this[offset + 3])
  3727. }
  3728. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3729. offset = offset >>> 0
  3730. if (!noAssert) checkOffset(offset, 4, this.length)
  3731. return ieee754.read(this, offset, true, 23, 4)
  3732. }
  3733. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3734. offset = offset >>> 0
  3735. if (!noAssert) checkOffset(offset, 4, this.length)
  3736. return ieee754.read(this, offset, false, 23, 4)
  3737. }
  3738. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3739. offset = offset >>> 0
  3740. if (!noAssert) checkOffset(offset, 8, this.length)
  3741. return ieee754.read(this, offset, true, 52, 8)
  3742. }
  3743. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3744. offset = offset >>> 0
  3745. if (!noAssert) checkOffset(offset, 8, this.length)
  3746. return ieee754.read(this, offset, false, 52, 8)
  3747. }
  3748. function checkInt (buf, value, offset, ext, max, min) {
  3749. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3750. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3751. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3752. }
  3753. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3754. value = +value
  3755. offset = offset >>> 0
  3756. byteLength = byteLength >>> 0
  3757. if (!noAssert) {
  3758. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3759. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3760. }
  3761. var mul = 1
  3762. var i = 0
  3763. this[offset] = value & 0xFF
  3764. while (++i < byteLength && (mul *= 0x100)) {
  3765. this[offset + i] = (value / mul) & 0xFF
  3766. }
  3767. return offset + byteLength
  3768. }
  3769. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3770. value = +value
  3771. offset = offset >>> 0
  3772. byteLength = byteLength >>> 0
  3773. if (!noAssert) {
  3774. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3775. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3776. }
  3777. var i = byteLength - 1
  3778. var mul = 1
  3779. this[offset + i] = value & 0xFF
  3780. while (--i >= 0 && (mul *= 0x100)) {
  3781. this[offset + i] = (value / mul) & 0xFF
  3782. }
  3783. return offset + byteLength
  3784. }
  3785. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3786. value = +value
  3787. offset = offset >>> 0
  3788. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3789. this[offset] = (value & 0xff)
  3790. return offset + 1
  3791. }
  3792. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3793. value = +value
  3794. offset = offset >>> 0
  3795. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3796. this[offset] = (value & 0xff)
  3797. this[offset + 1] = (value >>> 8)
  3798. return offset + 2
  3799. }
  3800. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3801. value = +value
  3802. offset = offset >>> 0
  3803. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3804. this[offset] = (value >>> 8)
  3805. this[offset + 1] = (value & 0xff)
  3806. return offset + 2
  3807. }
  3808. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3809. value = +value
  3810. offset = offset >>> 0
  3811. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3812. this[offset + 3] = (value >>> 24)
  3813. this[offset + 2] = (value >>> 16)
  3814. this[offset + 1] = (value >>> 8)
  3815. this[offset] = (value & 0xff)
  3816. return offset + 4
  3817. }
  3818. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3819. value = +value
  3820. offset = offset >>> 0
  3821. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3822. this[offset] = (value >>> 24)
  3823. this[offset + 1] = (value >>> 16)
  3824. this[offset + 2] = (value >>> 8)
  3825. this[offset + 3] = (value & 0xff)
  3826. return offset + 4
  3827. }
  3828. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3829. value = +value
  3830. offset = offset >>> 0
  3831. if (!noAssert) {
  3832. var limit = Math.pow(2, (8 * byteLength) - 1)
  3833. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3834. }
  3835. var i = 0
  3836. var mul = 1
  3837. var sub = 0
  3838. this[offset] = value & 0xFF
  3839. while (++i < byteLength && (mul *= 0x100)) {
  3840. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3841. sub = 1
  3842. }
  3843. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3844. }
  3845. return offset + byteLength
  3846. }
  3847. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3848. value = +value
  3849. offset = offset >>> 0
  3850. if (!noAssert) {
  3851. var limit = Math.pow(2, (8 * byteLength) - 1)
  3852. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3853. }
  3854. var i = byteLength - 1
  3855. var mul = 1
  3856. var sub = 0
  3857. this[offset + i] = value & 0xFF
  3858. while (--i >= 0 && (mul *= 0x100)) {
  3859. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3860. sub = 1
  3861. }
  3862. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3863. }
  3864. return offset + byteLength
  3865. }
  3866. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3867. value = +value
  3868. offset = offset >>> 0
  3869. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3870. if (value < 0) value = 0xff + value + 1
  3871. this[offset] = (value & 0xff)
  3872. return offset + 1
  3873. }
  3874. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3875. value = +value
  3876. offset = offset >>> 0
  3877. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3878. this[offset] = (value & 0xff)
  3879. this[offset + 1] = (value >>> 8)
  3880. return offset + 2
  3881. }
  3882. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3883. value = +value
  3884. offset = offset >>> 0
  3885. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3886. this[offset] = (value >>> 8)
  3887. this[offset + 1] = (value & 0xff)
  3888. return offset + 2
  3889. }
  3890. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3891. value = +value
  3892. offset = offset >>> 0
  3893. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3894. this[offset] = (value & 0xff)
  3895. this[offset + 1] = (value >>> 8)
  3896. this[offset + 2] = (value >>> 16)
  3897. this[offset + 3] = (value >>> 24)
  3898. return offset + 4
  3899. }
  3900. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3901. value = +value
  3902. offset = offset >>> 0
  3903. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3904. if (value < 0) value = 0xffffffff + value + 1
  3905. this[offset] = (value >>> 24)
  3906. this[offset + 1] = (value >>> 16)
  3907. this[offset + 2] = (value >>> 8)
  3908. this[offset + 3] = (value & 0xff)
  3909. return offset + 4
  3910. }
  3911. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3912. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3913. if (offset < 0) throw new RangeError('Index out of range')
  3914. }
  3915. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3916. value = +value
  3917. offset = offset >>> 0
  3918. if (!noAssert) {
  3919. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3920. }
  3921. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3922. return offset + 4
  3923. }
  3924. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3925. return writeFloat(this, value, offset, true, noAssert)
  3926. }
  3927. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3928. return writeFloat(this, value, offset, false, noAssert)
  3929. }
  3930. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3931. value = +value
  3932. offset = offset >>> 0
  3933. if (!noAssert) {
  3934. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3935. }
  3936. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3937. return offset + 8
  3938. }
  3939. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3940. return writeDouble(this, value, offset, true, noAssert)
  3941. }
  3942. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3943. return writeDouble(this, value, offset, false, noAssert)
  3944. }
  3945. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3946. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3947. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3948. if (!start) start = 0
  3949. if (!end && end !== 0) end = this.length
  3950. if (targetStart >= target.length) targetStart = target.length
  3951. if (!targetStart) targetStart = 0
  3952. if (end > 0 && end < start) end = start
  3953. // Copy 0 bytes; we're done
  3954. if (end === start) return 0
  3955. if (target.length === 0 || this.length === 0) return 0
  3956. // Fatal error conditions
  3957. if (targetStart < 0) {
  3958. throw new RangeError('targetStart out of bounds')
  3959. }
  3960. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3961. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3962. // Are we oob?
  3963. if (end > this.length) end = this.length
  3964. if (target.length - targetStart < end - start) {
  3965. end = target.length - targetStart + start
  3966. }
  3967. var len = end - start
  3968. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3969. // Use built-in when available, missing from IE11
  3970. this.copyWithin(targetStart, start, end)
  3971. } else if (this === target && start < targetStart && targetStart < end) {
  3972. // descending copy from end
  3973. for (var i = len - 1; i >= 0; --i) {
  3974. target[i + targetStart] = this[i + start]
  3975. }
  3976. } else {
  3977. Uint8Array.prototype.set.call(
  3978. target,
  3979. this.subarray(start, end),
  3980. targetStart
  3981. )
  3982. }
  3983. return len
  3984. }
  3985. // Usage:
  3986. // buffer.fill(number[, offset[, end]])
  3987. // buffer.fill(buffer[, offset[, end]])
  3988. // buffer.fill(string[, offset[, end]][, encoding])
  3989. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3990. // Handle string cases:
  3991. if (typeof val === 'string') {
  3992. if (typeof start === 'string') {
  3993. encoding = start
  3994. start = 0
  3995. end = this.length
  3996. } else if (typeof end === 'string') {
  3997. encoding = end
  3998. end = this.length
  3999. }
  4000. if (encoding !== undefined && typeof encoding !== 'string') {
  4001. throw new TypeError('encoding must be a string')
  4002. }
  4003. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  4004. throw new TypeError('Unknown encoding: ' + encoding)
  4005. }
  4006. if (val.length === 1) {
  4007. var code = val.charCodeAt(0)
  4008. if ((encoding === 'utf8' && code < 128) ||
  4009. encoding === 'latin1') {
  4010. // Fast path: If `val` fits into a single byte, use that numeric value.
  4011. val = code
  4012. }
  4013. }
  4014. } else if (typeof val === 'number') {
  4015. val = val & 255
  4016. }
  4017. // Invalid ranges are not set to a default, so can range check early.
  4018. if (start < 0 || this.length < start || this.length < end) {
  4019. throw new RangeError('Out of range index')
  4020. }
  4021. if (end <= start) {
  4022. return this
  4023. }
  4024. start = start >>> 0
  4025. end = end === undefined ? this.length : end >>> 0
  4026. if (!val) val = 0
  4027. var i
  4028. if (typeof val === 'number') {
  4029. for (i = start; i < end; ++i) {
  4030. this[i] = val
  4031. }
  4032. } else {
  4033. var bytes = Buffer.isBuffer(val)
  4034. ? val
  4035. : Buffer.from(val, encoding)
  4036. var len = bytes.length
  4037. if (len === 0) {
  4038. throw new TypeError('The value "' + val +
  4039. '" is invalid for argument "value"')
  4040. }
  4041. for (i = 0; i < end - start; ++i) {
  4042. this[i + start] = bytes[i % len]
  4043. }
  4044. }
  4045. return this
  4046. }
  4047. // HELPER FUNCTIONS
  4048. // ================
  4049. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  4050. function base64clean (str) {
  4051. // Node takes equal signs as end of the Base64 encoding
  4052. str = str.split('=')[0]
  4053. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  4054. str = str.trim().replace(INVALID_BASE64_RE, '')
  4055. // Node converts strings with length < 2 to ''
  4056. if (str.length < 2) return ''
  4057. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  4058. while (str.length % 4 !== 0) {
  4059. str = str + '='
  4060. }
  4061. return str
  4062. }
  4063. function toHex (n) {
  4064. if (n < 16) return '0' + n.toString(16)
  4065. return n.toString(16)
  4066. }
  4067. function utf8ToBytes (string, units) {
  4068. units = units || Infinity
  4069. var codePoint
  4070. var length = string.length
  4071. var leadSurrogate = null
  4072. var bytes = []
  4073. for (var i = 0; i < length; ++i) {
  4074. codePoint = string.charCodeAt(i)
  4075. // is surrogate component
  4076. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  4077. // last char was a lead
  4078. if (!leadSurrogate) {
  4079. // no lead yet
  4080. if (codePoint > 0xDBFF) {
  4081. // unexpected trail
  4082. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4083. continue
  4084. } else if (i + 1 === length) {
  4085. // unpaired lead
  4086. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4087. continue
  4088. }
  4089. // valid lead
  4090. leadSurrogate = codePoint
  4091. continue
  4092. }
  4093. // 2 leads in a row
  4094. if (codePoint < 0xDC00) {
  4095. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4096. leadSurrogate = codePoint
  4097. continue
  4098. }
  4099. // valid surrogate pair
  4100. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  4101. } else if (leadSurrogate) {
  4102. // valid bmp char, but last char was a lead
  4103. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  4104. }
  4105. leadSurrogate = null
  4106. // encode utf8
  4107. if (codePoint < 0x80) {
  4108. if ((units -= 1) < 0) break
  4109. bytes.push(codePoint)
  4110. } else if (codePoint < 0x800) {
  4111. if ((units -= 2) < 0) break
  4112. bytes.push(
  4113. codePoint >> 0x6 | 0xC0,
  4114. codePoint & 0x3F | 0x80
  4115. )
  4116. } else if (codePoint < 0x10000) {
  4117. if ((units -= 3) < 0) break
  4118. bytes.push(
  4119. codePoint >> 0xC | 0xE0,
  4120. codePoint >> 0x6 & 0x3F | 0x80,
  4121. codePoint & 0x3F | 0x80
  4122. )
  4123. } else if (codePoint < 0x110000) {
  4124. if ((units -= 4) < 0) break
  4125. bytes.push(
  4126. codePoint >> 0x12 | 0xF0,
  4127. codePoint >> 0xC & 0x3F | 0x80,
  4128. codePoint >> 0x6 & 0x3F | 0x80,
  4129. codePoint & 0x3F | 0x80
  4130. )
  4131. } else {
  4132. throw new Error('Invalid code point')
  4133. }
  4134. }
  4135. return bytes
  4136. }
  4137. function asciiToBytes (str) {
  4138. var byteArray = []
  4139. for (var i = 0; i < str.length; ++i) {
  4140. // Node's code seems to be doing this and not & 0x7F..
  4141. byteArray.push(str.charCodeAt(i) & 0xFF)
  4142. }
  4143. return byteArray
  4144. }
  4145. function utf16leToBytes (str, units) {
  4146. var c, hi, lo
  4147. var byteArray = []
  4148. for (var i = 0; i < str.length; ++i) {
  4149. if ((units -= 2) < 0) break
  4150. c = str.charCodeAt(i)
  4151. hi = c >> 8
  4152. lo = c % 256
  4153. byteArray.push(lo)
  4154. byteArray.push(hi)
  4155. }
  4156. return byteArray
  4157. }
  4158. function base64ToBytes (str) {
  4159. return base64.toByteArray(base64clean(str))
  4160. }
  4161. function blitBuffer (src, dst, offset, length) {
  4162. for (var i = 0; i < length; ++i) {
  4163. if ((i + offset >= dst.length) || (i >= src.length)) break
  4164. dst[i + offset] = src[i]
  4165. }
  4166. return i
  4167. }
  4168. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  4169. // the `instanceof` check but they should be treated as of that type.
  4170. // See: https://github.com/feross/buffer/issues/166
  4171. function isInstance (obj, type) {
  4172. return obj instanceof type ||
  4173. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  4174. obj.constructor.name === type.name)
  4175. }
  4176. function numberIsNaN (obj) {
  4177. // For IE11 support
  4178. return obj !== obj // eslint-disable-line no-self-compare
  4179. }
  4180. }).call(this)}).call(this,require("buffer").Buffer)
  4181. },{"base64-js":6,"buffer":7,"ieee754":8}],8:[function(require,module,exports){
  4182. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  4183. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  4184. var e, m
  4185. var eLen = (nBytes * 8) - mLen - 1
  4186. var eMax = (1 << eLen) - 1
  4187. var eBias = eMax >> 1
  4188. var nBits = -7
  4189. var i = isLE ? (nBytes - 1) : 0
  4190. var d = isLE ? -1 : 1
  4191. var s = buffer[offset + i]
  4192. i += d
  4193. e = s & ((1 << (-nBits)) - 1)
  4194. s >>= (-nBits)
  4195. nBits += eLen
  4196. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4197. m = e & ((1 << (-nBits)) - 1)
  4198. e >>= (-nBits)
  4199. nBits += mLen
  4200. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  4201. if (e === 0) {
  4202. e = 1 - eBias
  4203. } else if (e === eMax) {
  4204. return m ? NaN : ((s ? -1 : 1) * Infinity)
  4205. } else {
  4206. m = m + Math.pow(2, mLen)
  4207. e = e - eBias
  4208. }
  4209. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  4210. }
  4211. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  4212. var e, m, c
  4213. var eLen = (nBytes * 8) - mLen - 1
  4214. var eMax = (1 << eLen) - 1
  4215. var eBias = eMax >> 1
  4216. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  4217. var i = isLE ? 0 : (nBytes - 1)
  4218. var d = isLE ? 1 : -1
  4219. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  4220. value = Math.abs(value)
  4221. if (isNaN(value) || value === Infinity) {
  4222. m = isNaN(value) ? 1 : 0
  4223. e = eMax
  4224. } else {
  4225. e = Math.floor(Math.log(value) / Math.LN2)
  4226. if (value * (c = Math.pow(2, -e)) < 1) {
  4227. e--
  4228. c *= 2
  4229. }
  4230. if (e + eBias >= 1) {
  4231. value += rt / c
  4232. } else {
  4233. value += rt * Math.pow(2, 1 - eBias)
  4234. }
  4235. if (value * c >= 2) {
  4236. e++
  4237. c /= 2
  4238. }
  4239. if (e + eBias >= eMax) {
  4240. m = 0
  4241. e = eMax
  4242. } else if (e + eBias >= 1) {
  4243. m = ((value * c) - 1) * Math.pow(2, mLen)
  4244. e = e + eBias
  4245. } else {
  4246. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  4247. e = 0
  4248. }
  4249. }
  4250. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  4251. e = (e << mLen) | m
  4252. eLen += mLen
  4253. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  4254. buffer[offset + i - d] |= s * 128
  4255. }
  4256. },{}]},{},[1])(1)
  4257. });