protobuf.js 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222
  1. /*
  2. Copyright 2013 Daniel Wirtz <dcode@dcode.io>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /**
  14. * @license protobuf.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
  15. * Released under the Apache License, Version 2.0
  16. * see: https://github.com/dcodeIO/protobuf.js for details
  17. */
  18. (function(global, factory) {
  19. /* AMD */ if (typeof define === 'function' && define["amd"])
  20. define(["bytebuffer"], factory);
  21. /* CommonJS */ else if (typeof require === "function" && typeof module === "object" && module && module["exports"])
  22. module["exports"] = factory(require("bytebuffer"), true);
  23. /* Global */ else
  24. (global["dcodeIO"] = global["dcodeIO"] || {})["ProtoBuf"] = factory(global["dcodeIO"]["ByteBuffer"]);
  25. })(this, function(ByteBuffer, isCommonJS) {
  26. "use strict";
  27. /**
  28. * The ProtoBuf namespace.
  29. * @exports ProtoBuf
  30. * @namespace
  31. * @expose
  32. */
  33. var ProtoBuf = {};
  34. /**
  35. * @type {!function(new: ByteBuffer, ...[*])}
  36. * @expose
  37. */
  38. ProtoBuf.ByteBuffer = ByteBuffer;
  39. /**
  40. * @type {?function(new: Long, ...[*])}
  41. * @expose
  42. */
  43. ProtoBuf.Long = ByteBuffer.Long || null;
  44. /**
  45. * ProtoBuf.js version.
  46. * @type {string}
  47. * @const
  48. * @expose
  49. */
  50. ProtoBuf.VERSION = "5.0.1";
  51. /**
  52. * Wire types.
  53. * @type {Object.<string,number>}
  54. * @const
  55. * @expose
  56. */
  57. ProtoBuf.WIRE_TYPES = {};
  58. /**
  59. * Varint wire type.
  60. * @type {number}
  61. * @expose
  62. */
  63. ProtoBuf.WIRE_TYPES.VARINT = 0;
  64. /**
  65. * Fixed 64 bits wire type.
  66. * @type {number}
  67. * @const
  68. * @expose
  69. */
  70. ProtoBuf.WIRE_TYPES.BITS64 = 1;
  71. /**
  72. * Length delimited wire type.
  73. * @type {number}
  74. * @const
  75. * @expose
  76. */
  77. ProtoBuf.WIRE_TYPES.LDELIM = 2;
  78. /**
  79. * Start group wire type.
  80. * @type {number}
  81. * @const
  82. * @expose
  83. */
  84. ProtoBuf.WIRE_TYPES.STARTGROUP = 3;
  85. /**
  86. * End group wire type.
  87. * @type {number}
  88. * @const
  89. * @expose
  90. */
  91. ProtoBuf.WIRE_TYPES.ENDGROUP = 4;
  92. /**
  93. * Fixed 32 bits wire type.
  94. * @type {number}
  95. * @const
  96. * @expose
  97. */
  98. ProtoBuf.WIRE_TYPES.BITS32 = 5;
  99. /**
  100. * Packable wire types.
  101. * @type {!Array.<number>}
  102. * @const
  103. * @expose
  104. */
  105. ProtoBuf.PACKABLE_WIRE_TYPES = [
  106. ProtoBuf.WIRE_TYPES.VARINT,
  107. ProtoBuf.WIRE_TYPES.BITS64,
  108. ProtoBuf.WIRE_TYPES.BITS32
  109. ];
  110. /**
  111. * Types.
  112. * @dict
  113. * @type {!Object.<string,{name: string, wireType: number, defaultValue: *}>}
  114. * @const
  115. * @expose
  116. */
  117. ProtoBuf.TYPES = {
  118. // According to the protobuf spec.
  119. "int32": {
  120. name: "int32",
  121. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  122. defaultValue: 0
  123. },
  124. "uint32": {
  125. name: "uint32",
  126. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  127. defaultValue: 0
  128. },
  129. "sint32": {
  130. name: "sint32",
  131. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  132. defaultValue: 0
  133. },
  134. "int64": {
  135. name: "int64",
  136. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  137. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  138. },
  139. "uint64": {
  140. name: "uint64",
  141. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  142. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  143. },
  144. "sint64": {
  145. name: "sint64",
  146. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  147. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  148. },
  149. "bool": {
  150. name: "bool",
  151. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  152. defaultValue: false
  153. },
  154. "double": {
  155. name: "double",
  156. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  157. defaultValue: 0
  158. },
  159. "string": {
  160. name: "string",
  161. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  162. defaultValue: ""
  163. },
  164. "bytes": {
  165. name: "bytes",
  166. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  167. defaultValue: null // overridden in the code, must be a unique instance
  168. },
  169. "fixed32": {
  170. name: "fixed32",
  171. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  172. defaultValue: 0
  173. },
  174. "sfixed32": {
  175. name: "sfixed32",
  176. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  177. defaultValue: 0
  178. },
  179. "fixed64": {
  180. name: "fixed64",
  181. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  182. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.UZERO : undefined
  183. },
  184. "sfixed64": {
  185. name: "sfixed64",
  186. wireType: ProtoBuf.WIRE_TYPES.BITS64,
  187. defaultValue: ProtoBuf.Long ? ProtoBuf.Long.ZERO : undefined
  188. },
  189. "float": {
  190. name: "float",
  191. wireType: ProtoBuf.WIRE_TYPES.BITS32,
  192. defaultValue: 0
  193. },
  194. "enum": {
  195. name: "enum",
  196. wireType: ProtoBuf.WIRE_TYPES.VARINT,
  197. defaultValue: 0
  198. },
  199. "message": {
  200. name: "message",
  201. wireType: ProtoBuf.WIRE_TYPES.LDELIM,
  202. defaultValue: null
  203. },
  204. "group": {
  205. name: "group",
  206. wireType: ProtoBuf.WIRE_TYPES.STARTGROUP,
  207. defaultValue: null
  208. }
  209. };
  210. /**
  211. * Valid map key types.
  212. * @type {!Array.<!Object.<string,{name: string, wireType: number, defaultValue: *}>>}
  213. * @const
  214. * @expose
  215. */
  216. ProtoBuf.MAP_KEY_TYPES = [
  217. ProtoBuf.TYPES["int32"],
  218. ProtoBuf.TYPES["sint32"],
  219. ProtoBuf.TYPES["sfixed32"],
  220. ProtoBuf.TYPES["uint32"],
  221. ProtoBuf.TYPES["fixed32"],
  222. ProtoBuf.TYPES["int64"],
  223. ProtoBuf.TYPES["sint64"],
  224. ProtoBuf.TYPES["sfixed64"],
  225. ProtoBuf.TYPES["uint64"],
  226. ProtoBuf.TYPES["fixed64"],
  227. ProtoBuf.TYPES["bool"],
  228. ProtoBuf.TYPES["string"],
  229. ProtoBuf.TYPES["bytes"]
  230. ];
  231. /**
  232. * Minimum field id.
  233. * @type {number}
  234. * @const
  235. * @expose
  236. */
  237. ProtoBuf.ID_MIN = 1;
  238. /**
  239. * Maximum field id.
  240. * @type {number}
  241. * @const
  242. * @expose
  243. */
  244. ProtoBuf.ID_MAX = 0x1FFFFFFF;
  245. /**
  246. * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`.
  247. * Must be set prior to parsing.
  248. * @type {boolean}
  249. * @expose
  250. */
  251. ProtoBuf.convertFieldsToCamelCase = false;
  252. /**
  253. * By default, messages are populated with (setX, set_x) accessors for each field. This can be disabled by
  254. * setting this to `false` prior to building messages.
  255. * @type {boolean}
  256. * @expose
  257. */
  258. ProtoBuf.populateAccessors = true;
  259. /**
  260. * By default, messages are populated with default values if a field is not present on the wire. To disable
  261. * this behavior, set this setting to `false`.
  262. * @type {boolean}
  263. * @expose
  264. */
  265. ProtoBuf.populateDefaults = true;
  266. /**
  267. * @alias ProtoBuf.Util
  268. * @expose
  269. */
  270. ProtoBuf.Util = (function() {
  271. "use strict";
  272. /**
  273. * ProtoBuf utilities.
  274. * @exports ProtoBuf.Util
  275. * @namespace
  276. */
  277. var Util = {};
  278. /**
  279. * Flag if running in node or not.
  280. * @type {boolean}
  281. * @const
  282. * @expose
  283. */
  284. Util.IS_NODE = !!(
  285. typeof process === 'object' && process+'' === '[object process]' && !process['browser']
  286. );
  287. /**
  288. * Constructs a XMLHttpRequest object.
  289. * @return {XMLHttpRequest}
  290. * @throws {Error} If XMLHttpRequest is not supported
  291. * @expose
  292. */
  293. Util.XHR = function() {
  294. // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html
  295. var XMLHttpFactories = [
  296. function () {return new XMLHttpRequest()},
  297. function () {return new ActiveXObject("Msxml2.XMLHTTP")},
  298. function () {return new ActiveXObject("Msxml3.XMLHTTP")},
  299. function () {return new ActiveXObject("Microsoft.XMLHTTP")}
  300. ];
  301. /** @type {?XMLHttpRequest} */
  302. var xhr = null;
  303. for (var i=0;i<XMLHttpFactories.length;i++) {
  304. try { xhr = XMLHttpFactories[i](); }
  305. catch (e) { continue; }
  306. break;
  307. }
  308. if (!xhr)
  309. throw Error("XMLHttpRequest is not supported");
  310. return xhr;
  311. };
  312. /**
  313. * Fetches a resource.
  314. * @param {string} path Resource path
  315. * @param {function(?string)=} callback Callback receiving the resource's contents. If omitted the resource will
  316. * be fetched synchronously. If the request failed, contents will be null.
  317. * @return {?string|undefined} Resource contents if callback is omitted (null if the request failed), else undefined.
  318. * @expose
  319. */
  320. Util.fetch = function(path, callback) {
  321. if (callback && typeof callback != 'function')
  322. callback = null;
  323. if (Util.IS_NODE) {
  324. var fs = require("fs");
  325. if (callback) {
  326. fs.readFile(path, function(err, data) {
  327. if (err)
  328. callback(null);
  329. else
  330. callback(""+data);
  331. });
  332. } else
  333. try {
  334. return fs.readFileSync(path);
  335. } catch (e) {
  336. return null;
  337. }
  338. } else {
  339. var xhr = Util.XHR();
  340. xhr.open('GET', path, callback ? true : false);
  341. // xhr.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
  342. xhr.setRequestHeader('Accept', 'text/plain');
  343. if (typeof xhr.overrideMimeType === 'function') xhr.overrideMimeType('text/plain');
  344. if (callback) {
  345. xhr.onreadystatechange = function() {
  346. if (xhr.readyState != 4) return;
  347. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  348. callback(xhr.responseText);
  349. else
  350. callback(null);
  351. };
  352. if (xhr.readyState == 4)
  353. return;
  354. xhr.send(null);
  355. } else {
  356. xhr.send(null);
  357. if (/* remote */ xhr.status == 200 || /* local */ (xhr.status == 0 && typeof xhr.responseText === 'string'))
  358. return xhr.responseText;
  359. return null;
  360. }
  361. }
  362. };
  363. /**
  364. * Converts a string to camel case.
  365. * @param {string} str
  366. * @returns {string}
  367. * @expose
  368. */
  369. Util.toCamelCase = function(str) {
  370. return str.replace(/_([a-zA-Z])/g, function ($0, $1) {
  371. return $1.toUpperCase();
  372. });
  373. };
  374. return Util;
  375. })();
  376. /**
  377. * Language expressions.
  378. * @type {!Object.<string,!RegExp>}
  379. * @expose
  380. */
  381. ProtoBuf.Lang = {
  382. // Characters always ending a statement
  383. DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g,
  384. // Field rules
  385. RULE: /^(?:required|optional|repeated|map)$/,
  386. // Field types
  387. TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,
  388. // Names
  389. NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/,
  390. // Type definitions
  391. TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/,
  392. // Type references
  393. TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,
  394. // Fully qualified type references
  395. FQTYPEREF: /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,
  396. // All numbers
  397. NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,
  398. // Decimal numbers
  399. NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/,
  400. // Hexadecimal numbers
  401. NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/,
  402. // Octal numbers
  403. NUMBER_OCT: /^0[0-7]+$/,
  404. // Floating point numbers
  405. NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,
  406. // Booleans
  407. BOOL: /^(?:true|false)$/i,
  408. // Id numbers
  409. ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  410. // Negative id numbers (enum values)
  411. NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,
  412. // Whitespaces
  413. WHITESPACE: /\s/,
  414. // All strings
  415. STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,
  416. // Double quoted strings
  417. STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
  418. // Single quoted strings
  419. STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g
  420. };
  421. /**
  422. * @alias ProtoBuf.DotProto
  423. * @expose
  424. */
  425. ProtoBuf.DotProto = (function(ProtoBuf, Lang) {
  426. "use strict";
  427. /**
  428. * Utilities to parse .proto files.
  429. * @exports ProtoBuf.DotProto
  430. * @namespace
  431. */
  432. var DotProto = {};
  433. /**
  434. * Constructs a new Tokenizer.
  435. * @exports ProtoBuf.DotProto.Tokenizer
  436. * @class prototype tokenizer
  437. * @param {string} proto Proto to tokenize
  438. * @constructor
  439. */
  440. var Tokenizer = function(proto) {
  441. /**
  442. * Source to parse.
  443. * @type {string}
  444. * @expose
  445. */
  446. this.source = proto+"";
  447. /**
  448. * Current index.
  449. * @type {number}
  450. * @expose
  451. */
  452. this.index = 0;
  453. /**
  454. * Current line.
  455. * @type {number}
  456. * @expose
  457. */
  458. this.line = 1;
  459. /**
  460. * Token stack.
  461. * @type {!Array.<string>}
  462. * @expose
  463. */
  464. this.stack = [];
  465. /**
  466. * Opening character of the current string read, if any.
  467. * @type {?string}
  468. * @private
  469. */
  470. this._stringOpen = null;
  471. };
  472. /**
  473. * @alias ProtoBuf.DotProto.Tokenizer.prototype
  474. * @inner
  475. */
  476. var TokenizerPrototype = Tokenizer.prototype;
  477. /**
  478. * Reads a string beginning at the current index.
  479. * @return {string}
  480. * @private
  481. */
  482. TokenizerPrototype._readString = function() {
  483. var re = this._stringOpen === '"'
  484. ? Lang.STRING_DQ
  485. : Lang.STRING_SQ;
  486. re.lastIndex = this.index - 1; // Include the open quote
  487. var match = re.exec(this.source);
  488. if (!match)
  489. throw Error("unterminated string");
  490. this.index = re.lastIndex;
  491. this.stack.push(this._stringOpen);
  492. this._stringOpen = null;
  493. return match[1];
  494. };
  495. /**
  496. * Gets the next token and advances by one.
  497. * @return {?string} Token or `null` on EOF
  498. * @expose
  499. */
  500. TokenizerPrototype.next = function() {
  501. if (this.stack.length > 0)
  502. return this.stack.shift();
  503. if (this.index >= this.source.length)
  504. return null;
  505. if (this._stringOpen !== null)
  506. return this._readString();
  507. var repeat,
  508. prev,
  509. next;
  510. do {
  511. repeat = false;
  512. // Strip white spaces
  513. while (Lang.WHITESPACE.test(next = this.source.charAt(this.index))) {
  514. if (next === '\n')
  515. ++this.line;
  516. if (++this.index === this.source.length)
  517. return null;
  518. }
  519. // Strip comments
  520. if (this.source.charAt(this.index) === '/') {
  521. ++this.index;
  522. if (this.source.charAt(this.index) === '/') { // Line
  523. while (this.source.charAt(++this.index) !== '\n')
  524. if (this.index == this.source.length)
  525. return null;
  526. ++this.index;
  527. ++this.line;
  528. repeat = true;
  529. } else if ((next = this.source.charAt(this.index)) === '*') { /* Block */
  530. do {
  531. if (next === '\n')
  532. ++this.line;
  533. if (++this.index === this.source.length)
  534. return null;
  535. prev = next;
  536. next = this.source.charAt(this.index);
  537. } while (prev !== '*' || next !== '/');
  538. ++this.index;
  539. repeat = true;
  540. } else
  541. return '/';
  542. }
  543. } while (repeat);
  544. if (this.index === this.source.length)
  545. return null;
  546. // Read the next token
  547. var end = this.index;
  548. Lang.DELIM.lastIndex = 0;
  549. var delim = Lang.DELIM.test(this.source.charAt(end++));
  550. if (!delim)
  551. while(end < this.source.length && !Lang.DELIM.test(this.source.charAt(end)))
  552. ++end;
  553. var token = this.source.substring(this.index, this.index = end);
  554. if (token === '"' || token === "'")
  555. this._stringOpen = token;
  556. return token;
  557. };
  558. /**
  559. * Peeks for the next token.
  560. * @return {?string} Token or `null` on EOF
  561. * @expose
  562. */
  563. TokenizerPrototype.peek = function() {
  564. if (this.stack.length === 0) {
  565. var token = this.next();
  566. if (token === null)
  567. return null;
  568. this.stack.push(token);
  569. }
  570. return this.stack[0];
  571. };
  572. /**
  573. * Skips a specific token and throws if it differs.
  574. * @param {string} expected Expected token
  575. * @throws {Error} If the actual token differs
  576. */
  577. TokenizerPrototype.skip = function(expected) {
  578. var actual = this.next();
  579. if (actual !== expected)
  580. throw Error("illegal '"+actual+"', '"+expected+"' expected");
  581. };
  582. /**
  583. * Omits an optional token.
  584. * @param {string} expected Expected optional token
  585. * @returns {boolean} `true` if the token exists
  586. */
  587. TokenizerPrototype.omit = function(expected) {
  588. if (this.peek() === expected) {
  589. this.next();
  590. return true;
  591. }
  592. return false;
  593. };
  594. /**
  595. * Returns a string representation of this object.
  596. * @return {string} String representation as of "Tokenizer(index/length)"
  597. * @expose
  598. */
  599. TokenizerPrototype.toString = function() {
  600. return "Tokenizer ("+this.index+"/"+this.source.length+" at line "+this.line+")";
  601. };
  602. /**
  603. * @alias ProtoBuf.DotProto.Tokenizer
  604. * @expose
  605. */
  606. DotProto.Tokenizer = Tokenizer;
  607. /**
  608. * Constructs a new Parser.
  609. * @exports ProtoBuf.DotProto.Parser
  610. * @class prototype parser
  611. * @param {string} source Source
  612. * @constructor
  613. */
  614. var Parser = function(source) {
  615. /**
  616. * Tokenizer.
  617. * @type {!ProtoBuf.DotProto.Tokenizer}
  618. * @expose
  619. */
  620. this.tn = new Tokenizer(source);
  621. /**
  622. * Whether parsing proto3 or not.
  623. * @type {boolean}
  624. */
  625. this.proto3 = false;
  626. };
  627. /**
  628. * @alias ProtoBuf.DotProto.Parser.prototype
  629. * @inner
  630. */
  631. var ParserPrototype = Parser.prototype;
  632. /**
  633. * Parses the source.
  634. * @returns {!Object}
  635. * @throws {Error} If the source cannot be parsed
  636. * @expose
  637. */
  638. ParserPrototype.parse = function() {
  639. var topLevel = {
  640. "name": "[ROOT]", // temporary
  641. "package": null,
  642. "messages": [],
  643. "enums": [],
  644. "imports": [],
  645. "options": {},
  646. "services": []
  647. // "syntax": undefined
  648. };
  649. var token,
  650. head = true,
  651. weak;
  652. try {
  653. while (token = this.tn.next()) {
  654. switch (token) {
  655. case 'package':
  656. if (!head || topLevel["package"] !== null)
  657. throw Error("unexpected 'package'");
  658. token = this.tn.next();
  659. if (!Lang.TYPEREF.test(token))
  660. throw Error("illegal package name: " + token);
  661. this.tn.skip(";");
  662. topLevel["package"] = token;
  663. break;
  664. case 'import':
  665. if (!head)
  666. throw Error("unexpected 'import'");
  667. token = this.tn.peek();
  668. if (token === "public" || (weak = token === "weak")) // token ignored
  669. this.tn.next();
  670. token = this._readString();
  671. this.tn.skip(";");
  672. if (!weak) // import ignored
  673. topLevel["imports"].push(token);
  674. break;
  675. case 'syntax':
  676. if (!head)
  677. throw Error("unexpected 'syntax'");
  678. this.tn.skip("=");
  679. if ((topLevel["syntax"] = this._readString()) === "proto3")
  680. this.proto3 = true;
  681. this.tn.skip(";");
  682. break;
  683. case 'message':
  684. this._parseMessage(topLevel, null);
  685. head = false;
  686. break;
  687. case 'enum':
  688. this._parseEnum(topLevel);
  689. head = false;
  690. break;
  691. case 'option':
  692. this._parseOption(topLevel);
  693. break;
  694. case 'service':
  695. this._parseService(topLevel);
  696. break;
  697. case 'extend':
  698. this._parseExtend(topLevel);
  699. break;
  700. default:
  701. throw Error("unexpected '" + token + "'");
  702. }
  703. }
  704. } catch (e) {
  705. e.message = "Parse error at line "+this.tn.line+": " + e.message;
  706. throw e;
  707. }
  708. delete topLevel["name"];
  709. return topLevel;
  710. };
  711. /**
  712. * Parses the specified source.
  713. * @returns {!Object}
  714. * @throws {Error} If the source cannot be parsed
  715. * @expose
  716. */
  717. Parser.parse = function(source) {
  718. return new Parser(source).parse();
  719. };
  720. // ----- Conversion ------
  721. /**
  722. * Converts a numerical string to an id.
  723. * @param {string} value
  724. * @param {boolean=} mayBeNegative
  725. * @returns {number}
  726. * @inner
  727. */
  728. function mkId(value, mayBeNegative) {
  729. var id = -1,
  730. sign = 1;
  731. if (value.charAt(0) == '-') {
  732. sign = -1;
  733. value = value.substring(1);
  734. }
  735. if (Lang.NUMBER_DEC.test(value))
  736. id = parseInt(value);
  737. else if (Lang.NUMBER_HEX.test(value))
  738. id = parseInt(value.substring(2), 16);
  739. else if (Lang.NUMBER_OCT.test(value))
  740. id = parseInt(value.substring(1), 8);
  741. else
  742. throw Error("illegal id value: " + (sign < 0 ? '-' : '') + value);
  743. id = (sign*id)|0; // Force to 32bit
  744. if (!mayBeNegative && id < 0)
  745. throw Error("illegal id value: " + (sign < 0 ? '-' : '') + value);
  746. return id;
  747. }
  748. /**
  749. * Converts a numerical string to a number.
  750. * @param {string} val
  751. * @returns {number}
  752. * @inner
  753. */
  754. function mkNumber(val) {
  755. var sign = 1;
  756. if (val.charAt(0) == '-') {
  757. sign = -1;
  758. val = val.substring(1);
  759. }
  760. if (Lang.NUMBER_DEC.test(val))
  761. return sign * parseInt(val, 10);
  762. else if (Lang.NUMBER_HEX.test(val))
  763. return sign * parseInt(val.substring(2), 16);
  764. else if (Lang.NUMBER_OCT.test(val))
  765. return sign * parseInt(val.substring(1), 8);
  766. else if (val === 'inf')
  767. return sign * Infinity;
  768. else if (val === 'nan')
  769. return NaN;
  770. else if (Lang.NUMBER_FLT.test(val))
  771. return sign * parseFloat(val);
  772. throw Error("illegal number value: " + (sign < 0 ? '-' : '') + val);
  773. }
  774. // ----- Reading ------
  775. /**
  776. * Reads a string.
  777. * @returns {string}
  778. * @private
  779. */
  780. ParserPrototype._readString = function() {
  781. var value = "",
  782. token,
  783. delim;
  784. do {
  785. delim = this.tn.next();
  786. if (delim !== "'" && delim !== '"')
  787. throw Error("illegal string delimiter: "+delim);
  788. value += this.tn.next();
  789. this.tn.skip(delim);
  790. token = this.tn.peek();
  791. } while (token === '"' || token === '"'); // multi line?
  792. return value;
  793. };
  794. /**
  795. * Reads a value.
  796. * @param {boolean=} mayBeTypeRef
  797. * @returns {number|boolean|string}
  798. * @private
  799. */
  800. ParserPrototype._readValue = function(mayBeTypeRef) {
  801. var token = this.tn.peek(),
  802. value;
  803. if (token === '"' || token === "'")
  804. return this._readString();
  805. this.tn.next();
  806. if (Lang.NUMBER.test(token))
  807. return mkNumber(token);
  808. if (Lang.BOOL.test(token))
  809. return (token.toLowerCase() === 'true');
  810. if (mayBeTypeRef && Lang.TYPEREF.test(token))
  811. return token;
  812. throw Error("illegal value: "+token);
  813. };
  814. // ----- Parsing constructs -----
  815. /**
  816. * Parses a namespace option.
  817. * @param {!Object} parent Parent definition
  818. * @param {boolean=} isList
  819. * @private
  820. */
  821. ParserPrototype._parseOption = function(parent, isList) {
  822. var token = this.tn.next(),
  823. custom = false;
  824. if (token === '(') {
  825. custom = true;
  826. token = this.tn.next();
  827. }
  828. if (!Lang.TYPEREF.test(token))
  829. // we can allow options of the form google.protobuf.* since they will just get ignored anyways
  830. // if (!/google\.protobuf\./.test(token)) // FIXME: Why should that not be a valid typeref?
  831. throw Error("illegal option name: "+token);
  832. var name = token;
  833. if (custom) { // (my_method_option).foo, (my_method_option), some_method_option, (foo.my_option).bar
  834. this.tn.skip(')');
  835. name = '('+name+')';
  836. token = this.tn.peek();
  837. if (Lang.FQTYPEREF.test(token)) {
  838. name += token;
  839. this.tn.next();
  840. }
  841. }
  842. this.tn.skip('=');
  843. this._parseOptionValue(parent, name);
  844. if (!isList)
  845. this.tn.skip(";");
  846. };
  847. /**
  848. * Sets an option on the specified options object.
  849. * @param {!Object.<string,*>} options
  850. * @param {string} name
  851. * @param {string|number|boolean} value
  852. * @inner
  853. */
  854. function setOption(options, name, value) {
  855. if (typeof options[name] === 'undefined')
  856. options[name] = value;
  857. else {
  858. if (!Array.isArray(options[name]))
  859. options[name] = [ options[name] ];
  860. options[name].push(value);
  861. }
  862. }
  863. /**
  864. * Parses an option value.
  865. * @param {!Object} parent
  866. * @param {string} name
  867. * @private
  868. */
  869. ParserPrototype._parseOptionValue = function(parent, name) {
  870. var token = this.tn.peek();
  871. if (token !== '{') { // Plain value
  872. setOption(parent["options"], name, this._readValue(true));
  873. } else { // Aggregate options
  874. this.tn.skip("{");
  875. while ((token = this.tn.next()) !== '}') {
  876. if (!Lang.NAME.test(token))
  877. throw Error("illegal option name: " + name + "." + token);
  878. if (this.tn.omit(":"))
  879. setOption(parent["options"], name + "." + token, this._readValue(true));
  880. else
  881. this._parseOptionValue(parent, name + "." + token);
  882. }
  883. }
  884. };
  885. /**
  886. * Parses a service definition.
  887. * @param {!Object} parent Parent definition
  888. * @private
  889. */
  890. ParserPrototype._parseService = function(parent) {
  891. var token = this.tn.next();
  892. if (!Lang.NAME.test(token))
  893. throw Error("illegal service name at line "+this.tn.line+": "+token);
  894. var name = token;
  895. var svc = {
  896. "name": name,
  897. "rpc": {},
  898. "options": {}
  899. };
  900. this.tn.skip("{");
  901. while ((token = this.tn.next()) !== '}') {
  902. if (token === "option")
  903. this._parseOption(svc);
  904. else if (token === 'rpc')
  905. this._parseServiceRPC(svc);
  906. else
  907. throw Error("illegal service token: "+token);
  908. }
  909. this.tn.omit(";");
  910. parent["services"].push(svc);
  911. };
  912. /**
  913. * Parses a RPC service definition of the form ['rpc', name, (request), 'returns', (response)].
  914. * @param {!Object} svc Service definition
  915. * @private
  916. */
  917. ParserPrototype._parseServiceRPC = function(svc) {
  918. var type = "rpc",
  919. token = this.tn.next();
  920. if (!Lang.NAME.test(token))
  921. throw Error("illegal rpc service method name: "+token);
  922. var name = token;
  923. var method = {
  924. "request": null,
  925. "response": null,
  926. "request_stream": false,
  927. "response_stream": false,
  928. "options": {}
  929. };
  930. this.tn.skip("(");
  931. token = this.tn.next();
  932. if (token.toLowerCase() === "stream") {
  933. method["request_stream"] = true;
  934. token = this.tn.next();
  935. }
  936. if (!Lang.TYPEREF.test(token))
  937. throw Error("illegal rpc service request type: "+token);
  938. method["request"] = token;
  939. this.tn.skip(")");
  940. token = this.tn.next();
  941. if (token.toLowerCase() !== "returns")
  942. throw Error("illegal rpc service request type delimiter: "+token);
  943. this.tn.skip("(");
  944. token = this.tn.next();
  945. if (token.toLowerCase() === "stream") {
  946. method["response_stream"] = true;
  947. token = this.tn.next();
  948. }
  949. method["response"] = token;
  950. this.tn.skip(")");
  951. token = this.tn.peek();
  952. if (token === '{') {
  953. this.tn.next();
  954. while ((token = this.tn.next()) !== '}') {
  955. if (token === 'option')
  956. this._parseOption(method);
  957. else
  958. throw Error("illegal rpc service token: " + token);
  959. }
  960. this.tn.omit(";");
  961. } else
  962. this.tn.skip(";");
  963. if (typeof svc[type] === 'undefined')
  964. svc[type] = {};
  965. svc[type][name] = method;
  966. };
  967. /**
  968. * Parses a message definition.
  969. * @param {!Object} parent Parent definition
  970. * @param {!Object=} fld Field definition if this is a group
  971. * @returns {!Object}
  972. * @private
  973. */
  974. ParserPrototype._parseMessage = function(parent, fld) {
  975. var isGroup = !!fld,
  976. token = this.tn.next();
  977. var msg = {
  978. "name": "",
  979. "fields": [],
  980. "enums": [],
  981. "messages": [],
  982. "options": {},
  983. "services": [],
  984. "oneofs": {}
  985. // "extensions": undefined
  986. };
  987. if (!Lang.NAME.test(token))
  988. throw Error("illegal "+(isGroup ? "group" : "message")+" name: "+token);
  989. msg["name"] = token;
  990. if (isGroup) {
  991. this.tn.skip("=");
  992. fld["id"] = mkId(this.tn.next());
  993. msg["isGroup"] = true;
  994. }
  995. token = this.tn.peek();
  996. if (token === '[' && fld)
  997. this._parseFieldOptions(fld);
  998. this.tn.skip("{");
  999. while ((token = this.tn.next()) !== '}') {
  1000. if (Lang.RULE.test(token))
  1001. this._parseMessageField(msg, token);
  1002. else if (token === "oneof")
  1003. this._parseMessageOneOf(msg);
  1004. else if (token === "enum")
  1005. this._parseEnum(msg);
  1006. else if (token === "message")
  1007. this._parseMessage(msg);
  1008. else if (token === "option")
  1009. this._parseOption(msg);
  1010. else if (token === "service")
  1011. this._parseService(msg);
  1012. else if (token === "extensions")
  1013. msg["extensions"] = this._parseExtensionRanges();
  1014. else if (token === "reserved")
  1015. this._parseIgnored(); // TODO
  1016. else if (token === "extend")
  1017. this._parseExtend(msg);
  1018. else if (Lang.TYPEREF.test(token)) {
  1019. if (!this.proto3)
  1020. throw Error("illegal field rule: "+token);
  1021. this._parseMessageField(msg, "optional", token);
  1022. } else
  1023. throw Error("illegal message token: "+token);
  1024. }
  1025. this.tn.omit(";");
  1026. parent["messages"].push(msg);
  1027. return msg;
  1028. };
  1029. /**
  1030. * Parses an ignored statement.
  1031. * @private
  1032. */
  1033. ParserPrototype._parseIgnored = function() {
  1034. while (this.tn.peek() !== ';')
  1035. this.tn.next();
  1036. this.tn.skip(";");
  1037. };
  1038. /**
  1039. * Parses a message field.
  1040. * @param {!Object} msg Message definition
  1041. * @param {string} rule Field rule
  1042. * @param {string=} type Field type if already known (never known for maps)
  1043. * @returns {!Object} Field descriptor
  1044. * @private
  1045. */
  1046. ParserPrototype._parseMessageField = function(msg, rule, type) {
  1047. if (!Lang.RULE.test(rule))
  1048. throw Error("illegal message field rule: "+rule);
  1049. var fld = {
  1050. "rule": rule,
  1051. "type": "",
  1052. "name": "",
  1053. "options": {},
  1054. "id": 0
  1055. };
  1056. var token;
  1057. if (rule === "map") {
  1058. if (type)
  1059. throw Error("illegal type: " + type);
  1060. this.tn.skip('<');
  1061. token = this.tn.next();
  1062. if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
  1063. throw Error("illegal message field type: " + token);
  1064. fld["keytype"] = token;
  1065. this.tn.skip(',');
  1066. token = this.tn.next();
  1067. if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
  1068. throw Error("illegal message field: " + token);
  1069. fld["type"] = token;
  1070. this.tn.skip('>');
  1071. token = this.tn.next();
  1072. if (!Lang.NAME.test(token))
  1073. throw Error("illegal message field name: " + token);
  1074. fld["name"] = token;
  1075. this.tn.skip("=");
  1076. fld["id"] = mkId(this.tn.next());
  1077. token = this.tn.peek();
  1078. if (token === '[')
  1079. this._parseFieldOptions(fld);
  1080. this.tn.skip(";");
  1081. } else {
  1082. type = typeof type !== 'undefined' ? type : this.tn.next();
  1083. if (type === "group") {
  1084. // "A [legacy] group simply combines a nested message type and a field into a single declaration. In your
  1085. // code, you can treat this message just as if it had a Result type field called result (the latter name is
  1086. // converted to lower-case so that it does not conflict with the former)."
  1087. var grp = this._parseMessage(msg, fld);
  1088. if (!/^[A-Z]/.test(grp["name"]))
  1089. throw Error('illegal group name: '+grp["name"]);
  1090. fld["type"] = grp["name"];
  1091. fld["name"] = grp["name"].toLowerCase();
  1092. this.tn.omit(";");
  1093. } else {
  1094. if (!Lang.TYPE.test(type) && !Lang.TYPEREF.test(type))
  1095. throw Error("illegal message field type: " + type);
  1096. fld["type"] = type;
  1097. token = this.tn.next();
  1098. if (!Lang.NAME.test(token))
  1099. throw Error("illegal message field name: " + token);
  1100. fld["name"] = token;
  1101. this.tn.skip("=");
  1102. fld["id"] = mkId(this.tn.next());
  1103. token = this.tn.peek();
  1104. if (token === "[")
  1105. this._parseFieldOptions(fld);
  1106. this.tn.skip(";");
  1107. }
  1108. }
  1109. msg["fields"].push(fld);
  1110. return fld;
  1111. };
  1112. /**
  1113. * Parses a message oneof.
  1114. * @param {!Object} msg Message definition
  1115. * @private
  1116. */
  1117. ParserPrototype._parseMessageOneOf = function(msg) {
  1118. var token = this.tn.next();
  1119. if (!Lang.NAME.test(token))
  1120. throw Error("illegal oneof name: "+token);
  1121. var name = token,
  1122. fld;
  1123. var fields = [];
  1124. this.tn.skip("{");
  1125. while ((token = this.tn.next()) !== "}") {
  1126. fld = this._parseMessageField(msg, "optional", token);
  1127. fld["oneof"] = name;
  1128. fields.push(fld["id"]);
  1129. }
  1130. this.tn.omit(";");
  1131. msg["oneofs"][name] = fields;
  1132. };
  1133. /**
  1134. * Parses a set of field option definitions.
  1135. * @param {!Object} fld Field definition
  1136. * @private
  1137. */
  1138. ParserPrototype._parseFieldOptions = function(fld) {
  1139. this.tn.skip("[");
  1140. var token,
  1141. first = true;
  1142. while ((token = this.tn.peek()) !== ']') {
  1143. if (!first)
  1144. this.tn.skip(",");
  1145. this._parseOption(fld, true);
  1146. first = false;
  1147. }
  1148. this.tn.next();
  1149. };
  1150. /**
  1151. * Parses an enum.
  1152. * @param {!Object} msg Message definition
  1153. * @private
  1154. */
  1155. ParserPrototype._parseEnum = function(msg) {
  1156. var enm = {
  1157. "name": "",
  1158. "values": [],
  1159. "options": {}
  1160. };
  1161. var token = this.tn.next();
  1162. if (!Lang.NAME.test(token))
  1163. throw Error("illegal name: "+token);
  1164. enm["name"] = token;
  1165. this.tn.skip("{");
  1166. while ((token = this.tn.next()) !== '}') {
  1167. if (token === "option")
  1168. this._parseOption(enm);
  1169. else {
  1170. if (!Lang.NAME.test(token))
  1171. throw Error("illegal name: "+token);
  1172. this.tn.skip("=");
  1173. var val = {
  1174. "name": token,
  1175. "id": mkId(this.tn.next(), true)
  1176. };
  1177. token = this.tn.peek();
  1178. if (token === "[")
  1179. this._parseFieldOptions({ "options": {} });
  1180. this.tn.skip(";");
  1181. enm["values"].push(val);
  1182. }
  1183. }
  1184. this.tn.omit(";");
  1185. msg["enums"].push(enm);
  1186. };
  1187. /**
  1188. * Parses extension / reserved ranges.
  1189. * @returns {!Array.<!Array.<number>>}
  1190. * @private
  1191. */
  1192. ParserPrototype._parseExtensionRanges = function() {
  1193. var ranges = [];
  1194. var token,
  1195. range,
  1196. value;
  1197. do {
  1198. range = [];
  1199. while (true) {
  1200. token = this.tn.next();
  1201. switch (token) {
  1202. case "min":
  1203. value = ProtoBuf.ID_MIN;
  1204. break;
  1205. case "max":
  1206. value = ProtoBuf.ID_MAX;
  1207. break;
  1208. default:
  1209. value = mkNumber(token);
  1210. break;
  1211. }
  1212. range.push(value);
  1213. if (range.length === 2)
  1214. break;
  1215. if (this.tn.peek() !== "to") {
  1216. range.push(value);
  1217. break;
  1218. }
  1219. this.tn.next();
  1220. }
  1221. ranges.push(range);
  1222. } while (this.tn.omit(","));
  1223. this.tn.skip(";");
  1224. return ranges;
  1225. };
  1226. /**
  1227. * Parses an extend block.
  1228. * @param {!Object} parent Parent object
  1229. * @private
  1230. */
  1231. ParserPrototype._parseExtend = function(parent) {
  1232. var token = this.tn.next();
  1233. if (!Lang.TYPEREF.test(token))
  1234. throw Error("illegal extend reference: "+token);
  1235. var ext = {
  1236. "ref": token,
  1237. "fields": []
  1238. };
  1239. this.tn.skip("{");
  1240. while ((token = this.tn.next()) !== '}') {
  1241. if (Lang.RULE.test(token))
  1242. this._parseMessageField(ext, token);
  1243. else if (Lang.TYPEREF.test(token)) {
  1244. if (!this.proto3)
  1245. throw Error("illegal field rule: "+token);
  1246. this._parseMessageField(ext, "optional", token);
  1247. } else
  1248. throw Error("illegal extend token: "+token);
  1249. }
  1250. this.tn.omit(";");
  1251. parent["messages"].push(ext);
  1252. return ext;
  1253. };
  1254. // ----- General -----
  1255. /**
  1256. * Returns a string representation of this parser.
  1257. * @returns {string}
  1258. */
  1259. ParserPrototype.toString = function() {
  1260. return "Parser at line "+this.tn.line;
  1261. };
  1262. /**
  1263. * @alias ProtoBuf.DotProto.Parser
  1264. * @expose
  1265. */
  1266. DotProto.Parser = Parser;
  1267. return DotProto;
  1268. })(ProtoBuf, ProtoBuf.Lang);
  1269. /**
  1270. * @alias ProtoBuf.Reflect
  1271. * @expose
  1272. */
  1273. ProtoBuf.Reflect = (function(ProtoBuf) {
  1274. "use strict";
  1275. /**
  1276. * Reflection types.
  1277. * @exports ProtoBuf.Reflect
  1278. * @namespace
  1279. */
  1280. var Reflect = {};
  1281. /**
  1282. * Constructs a Reflect base class.
  1283. * @exports ProtoBuf.Reflect.T
  1284. * @constructor
  1285. * @abstract
  1286. * @param {!ProtoBuf.Builder} builder Builder reference
  1287. * @param {?ProtoBuf.Reflect.T} parent Parent object
  1288. * @param {string} name Object name
  1289. */
  1290. var T = function(builder, parent, name) {
  1291. /**
  1292. * Builder reference.
  1293. * @type {!ProtoBuf.Builder}
  1294. * @expose
  1295. */
  1296. this.builder = builder;
  1297. /**
  1298. * Parent object.
  1299. * @type {?ProtoBuf.Reflect.T}
  1300. * @expose
  1301. */
  1302. this.parent = parent;
  1303. /**
  1304. * Object name in namespace.
  1305. * @type {string}
  1306. * @expose
  1307. */
  1308. this.name = name;
  1309. /**
  1310. * Fully qualified class name
  1311. * @type {string}
  1312. * @expose
  1313. */
  1314. this.className;
  1315. };
  1316. /**
  1317. * @alias ProtoBuf.Reflect.T.prototype
  1318. * @inner
  1319. */
  1320. var TPrototype = T.prototype;
  1321. /**
  1322. * Returns the fully qualified name of this object.
  1323. * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
  1324. * @expose
  1325. */
  1326. TPrototype.fqn = function() {
  1327. var name = this.name,
  1328. ptr = this;
  1329. do {
  1330. ptr = ptr.parent;
  1331. if (ptr == null)
  1332. break;
  1333. name = ptr.name+"."+name;
  1334. } while (true);
  1335. return name;
  1336. };
  1337. /**
  1338. * Returns a string representation of this Reflect object (its fully qualified name).
  1339. * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
  1340. * @return String representation
  1341. * @expose
  1342. */
  1343. TPrototype.toString = function(includeClass) {
  1344. return (includeClass ? this.className + " " : "") + this.fqn();
  1345. };
  1346. /**
  1347. * Builds this type.
  1348. * @throws {Error} If this type cannot be built directly
  1349. * @expose
  1350. */
  1351. TPrototype.build = function() {
  1352. throw Error(this.toString(true)+" cannot be built directly");
  1353. };
  1354. /**
  1355. * @alias ProtoBuf.Reflect.T
  1356. * @expose
  1357. */
  1358. Reflect.T = T;
  1359. /**
  1360. * Constructs a new Namespace.
  1361. * @exports ProtoBuf.Reflect.Namespace
  1362. * @param {!ProtoBuf.Builder} builder Builder reference
  1363. * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
  1364. * @param {string} name Namespace name
  1365. * @param {Object.<string,*>=} options Namespace options
  1366. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  1367. * @constructor
  1368. * @extends ProtoBuf.Reflect.T
  1369. */
  1370. var Namespace = function(builder, parent, name, options, syntax) {
  1371. T.call(this, builder, parent, name);
  1372. /**
  1373. * @override
  1374. */
  1375. this.className = "Namespace";
  1376. /**
  1377. * Children inside the namespace.
  1378. * @type {!Array.<ProtoBuf.Reflect.T>}
  1379. */
  1380. this.children = [];
  1381. /**
  1382. * Options.
  1383. * @type {!Object.<string, *>}
  1384. */
  1385. this.options = options || {};
  1386. /**
  1387. * Syntax level (e.g., proto2 or proto3).
  1388. * @type {!string}
  1389. */
  1390. this.syntax = syntax || "proto2";
  1391. };
  1392. /**
  1393. * @alias ProtoBuf.Reflect.Namespace.prototype
  1394. * @inner
  1395. */
  1396. var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
  1397. /**
  1398. * Returns an array of the namespace's children.
  1399. * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
  1400. * @return {Array.<ProtoBuf.Reflect.T>}
  1401. * @expose
  1402. */
  1403. NamespacePrototype.getChildren = function(type) {
  1404. type = type || null;
  1405. if (type == null)
  1406. return this.children.slice();
  1407. var children = [];
  1408. for (var i=0, k=this.children.length; i<k; ++i)
  1409. if (this.children[i] instanceof type)
  1410. children.push(this.children[i]);
  1411. return children;
  1412. };
  1413. /**
  1414. * Adds a child to the namespace.
  1415. * @param {ProtoBuf.Reflect.T} child Child
  1416. * @throws {Error} If the child cannot be added (duplicate)
  1417. * @expose
  1418. */
  1419. NamespacePrototype.addChild = function(child) {
  1420. var other;
  1421. if (other = this.getChild(child.name)) {
  1422. // Try to revert camelcase transformation on collision
  1423. if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
  1424. other.name = other.originalName; // Revert previous first (effectively keeps both originals)
  1425. else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
  1426. child.name = child.originalName;
  1427. else
  1428. throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
  1429. }
  1430. this.children.push(child);
  1431. };
  1432. /**
  1433. * Gets a child by its name or id.
  1434. * @param {string|number} nameOrId Child name or id
  1435. * @return {?ProtoBuf.Reflect.T} The child or null if not found
  1436. * @expose
  1437. */
  1438. NamespacePrototype.getChild = function(nameOrId) {
  1439. var key = typeof nameOrId === 'number' ? 'id' : 'name';
  1440. for (var i=0, k=this.children.length; i<k; ++i)
  1441. if (this.children[i][key] === nameOrId)
  1442. return this.children[i];
  1443. return null;
  1444. };
  1445. /**
  1446. * Resolves a reflect object inside of this namespace.
  1447. * @param {string|!Array.<string>} qn Qualified name to resolve
  1448. * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
  1449. * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
  1450. * @expose
  1451. */
  1452. NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
  1453. var part = typeof qn === 'string' ? qn.split(".") : qn,
  1454. ptr = this,
  1455. i = 0;
  1456. if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
  1457. while (ptr.parent !== null)
  1458. ptr = ptr.parent;
  1459. i++;
  1460. }
  1461. var child;
  1462. do {
  1463. do {
  1464. if (!(ptr instanceof Reflect.Namespace)) {
  1465. ptr = null;
  1466. break;
  1467. }
  1468. child = ptr.getChild(part[i]);
  1469. if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
  1470. ptr = null;
  1471. break;
  1472. }
  1473. ptr = child; i++;
  1474. } while (i < part.length);
  1475. if (ptr != null)
  1476. break; // Found
  1477. // Else search the parent
  1478. if (this.parent !== null)
  1479. return this.parent.resolve(qn, excludeNonNamespace);
  1480. } while (ptr != null);
  1481. return ptr;
  1482. };
  1483. /**
  1484. * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
  1485. * @param {!ProtoBuf.Reflect.T} t Reflection type
  1486. * @returns {string} The shortest qualified name or, if there is none, the fqn
  1487. * @expose
  1488. */
  1489. NamespacePrototype.qn = function(t) {
  1490. var part = [], ptr = t;
  1491. do {
  1492. part.unshift(ptr.name);
  1493. ptr = ptr.parent;
  1494. } while (ptr !== null);
  1495. for (var len=1; len <= part.length; len++) {
  1496. var qn = part.slice(part.length-len);
  1497. if (t === this.resolve(qn, t instanceof Reflect.Namespace))
  1498. return qn.join(".");
  1499. }
  1500. return t.fqn();
  1501. };
  1502. /**
  1503. * Builds the namespace and returns the runtime counterpart.
  1504. * @return {Object.<string,Function|Object>} Runtime namespace
  1505. * @expose
  1506. */
  1507. NamespacePrototype.build = function() {
  1508. /** @dict */
  1509. var ns = {};
  1510. var children = this.children;
  1511. for (var i=0, k=children.length, child; i<k; ++i) {
  1512. child = children[i];
  1513. if (child instanceof Namespace)
  1514. ns[child.name] = child.build();
  1515. }
  1516. if (Object.defineProperty)
  1517. Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
  1518. return ns;
  1519. };
  1520. /**
  1521. * Builds the namespace's '$options' property.
  1522. * @return {Object.<string,*>}
  1523. */
  1524. NamespacePrototype.buildOpt = function() {
  1525. var opt = {},
  1526. keys = Object.keys(this.options);
  1527. for (var i=0, k=keys.length; i<k; ++i) {
  1528. var key = keys[i],
  1529. val = this.options[keys[i]];
  1530. // TODO: Options are not resolved, yet.
  1531. // if (val instanceof Namespace) {
  1532. // opt[key] = val.build();
  1533. // } else {
  1534. opt[key] = val;
  1535. // }
  1536. }
  1537. return opt;
  1538. };
  1539. /**
  1540. * Gets the value assigned to the option with the specified name.
  1541. * @param {string=} name Returns the option value if specified, otherwise all options are returned.
  1542. * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
  1543. */
  1544. NamespacePrototype.getOption = function(name) {
  1545. if (typeof name === 'undefined')
  1546. return this.options;
  1547. return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
  1548. };
  1549. /**
  1550. * @alias ProtoBuf.Reflect.Namespace
  1551. * @expose
  1552. */
  1553. Reflect.Namespace = Namespace;
  1554. /**
  1555. * Constructs a new Element implementation that checks and converts values for a
  1556. * particular field type, as appropriate.
  1557. *
  1558. * An Element represents a single value: either the value of a singular field,
  1559. * or a value contained in one entry of a repeated field or map field. This
  1560. * class does not implement these higher-level concepts; it only encapsulates
  1561. * the low-level typechecking and conversion.
  1562. *
  1563. * @exports ProtoBuf.Reflect.Element
  1564. * @param {{name: string, wireType: number}} type Resolved data type
  1565. * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
  1566. * (e.g. submessage field).
  1567. * @param {boolean} isMapKey Is this element a Map key? The value will be
  1568. * converted to string form if so.
  1569. * @param {string} syntax Syntax level of defining message type, e.g.,
  1570. * proto2 or proto3.
  1571. * @constructor
  1572. */
  1573. var Element = function(type, resolvedType, isMapKey, syntax) {
  1574. /**
  1575. * Element type, as a string (e.g., int32).
  1576. * @type {{name: string, wireType: number}}
  1577. */
  1578. this.type = type;
  1579. /**
  1580. * Element type reference to submessage or enum definition, if needed.
  1581. * @type {ProtoBuf.Reflect.T|null}
  1582. */
  1583. this.resolvedType = resolvedType;
  1584. /**
  1585. * Element is a map key.
  1586. * @type {boolean}
  1587. */
  1588. this.isMapKey = isMapKey;
  1589. /**
  1590. * Syntax level of defining message type, e.g., proto2 or proto3.
  1591. * @type {string}
  1592. */
  1593. this.syntax = syntax;
  1594. if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
  1595. throw Error("Invalid map key type: " + type.name);
  1596. };
  1597. var ElementPrototype = Element.prototype;
  1598. /**
  1599. * Obtains a (new) default value for the specified type.
  1600. * @param type {string|{name: string, wireType: number}} Field type
  1601. * @returns {*} Default value
  1602. * @inner
  1603. */
  1604. function mkDefault(type) {
  1605. if (typeof type === 'string')
  1606. type = ProtoBuf.TYPES[type];
  1607. if (typeof type.defaultValue === 'undefined')
  1608. throw Error("default value for type "+type.name+" is not supported");
  1609. if (type == ProtoBuf.TYPES["bytes"])
  1610. return new ByteBuffer(0);
  1611. return type.defaultValue;
  1612. }
  1613. /**
  1614. * Returns the default value for this field in proto3.
  1615. * @function
  1616. * @param type {string|{name: string, wireType: number}} the field type
  1617. * @returns {*} Default value
  1618. */
  1619. Element.defaultFieldValue = mkDefault;
  1620. /**
  1621. * Makes a Long from a value.
  1622. * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
  1623. * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
  1624. * strings and numbers
  1625. * @returns {!Long}
  1626. * @throws {Error} If the value cannot be converted to a Long
  1627. * @inner
  1628. */
  1629. function mkLong(value, unsigned) {
  1630. if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
  1631. && value.low === value.low && value.high === value.high)
  1632. return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
  1633. if (typeof value === 'string')
  1634. return ProtoBuf.Long.fromString(value, unsigned || false, 10);
  1635. if (typeof value === 'number')
  1636. return ProtoBuf.Long.fromNumber(value, unsigned || false);
  1637. throw Error("not convertible to Long");
  1638. }
  1639. /**
  1640. * Checks if the given value can be set for an element of this type (singular
  1641. * field or one element of a repeated field or map).
  1642. * @param {*} value Value to check
  1643. * @return {*} Verified, maybe adjusted, value
  1644. * @throws {Error} If the value cannot be verified for this element slot
  1645. * @expose
  1646. */
  1647. ElementPrototype.verifyValue = function(value) {
  1648. var self = this;
  1649. function fail(val, msg) {
  1650. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  1651. }
  1652. switch (this.type) {
  1653. // Signed 32bit
  1654. case ProtoBuf.TYPES["int32"]:
  1655. case ProtoBuf.TYPES["sint32"]:
  1656. case ProtoBuf.TYPES["sfixed32"]:
  1657. // Account for !NaN: value === value
  1658. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1659. fail(typeof value, "not an integer");
  1660. return value > 4294967295 ? value | 0 : value;
  1661. // Unsigned 32bit
  1662. case ProtoBuf.TYPES["uint32"]:
  1663. case ProtoBuf.TYPES["fixed32"]:
  1664. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1665. fail(typeof value, "not an integer");
  1666. return value < 0 ? value >>> 0 : value;
  1667. // Signed 64bit
  1668. case ProtoBuf.TYPES["int64"]:
  1669. case ProtoBuf.TYPES["sint64"]:
  1670. case ProtoBuf.TYPES["sfixed64"]: {
  1671. if (ProtoBuf.Long)
  1672. try {
  1673. return mkLong(value, false);
  1674. } catch (e) {
  1675. fail(typeof value, e.message);
  1676. }
  1677. else
  1678. fail(typeof value, "requires Long.js");
  1679. }
  1680. // Unsigned 64bit
  1681. case ProtoBuf.TYPES["uint64"]:
  1682. case ProtoBuf.TYPES["fixed64"]: {
  1683. if (ProtoBuf.Long)
  1684. try {
  1685. return mkLong(value, true);
  1686. } catch (e) {
  1687. fail(typeof value, e.message);
  1688. }
  1689. else
  1690. fail(typeof value, "requires Long.js");
  1691. }
  1692. // Bool
  1693. case ProtoBuf.TYPES["bool"]:
  1694. if (typeof value !== 'boolean')
  1695. fail(typeof value, "not a boolean");
  1696. return value;
  1697. // Float
  1698. case ProtoBuf.TYPES["float"]:
  1699. case ProtoBuf.TYPES["double"]:
  1700. if (typeof value !== 'number')
  1701. fail(typeof value, "not a number");
  1702. return value;
  1703. // Length-delimited string
  1704. case ProtoBuf.TYPES["string"]:
  1705. if (typeof value !== 'string' && !(value && value instanceof String))
  1706. fail(typeof value, "not a string");
  1707. return ""+value; // Convert String object to string
  1708. // Length-delimited bytes
  1709. case ProtoBuf.TYPES["bytes"]:
  1710. if (ByteBuffer.isByteBuffer(value))
  1711. return value;
  1712. return ByteBuffer.wrap(value, "base64");
  1713. // Constant enum value
  1714. case ProtoBuf.TYPES["enum"]: {
  1715. var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
  1716. for (i=0; i<values.length; i++)
  1717. if (values[i].name == value)
  1718. return values[i].id;
  1719. else if (values[i].id == value)
  1720. return values[i].id;
  1721. if (this.syntax === 'proto3') {
  1722. // proto3: just make sure it's an integer.
  1723. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1724. fail(typeof value, "not an integer");
  1725. if (value > 4294967295 || value < 0)
  1726. fail(typeof value, "not in range for uint32")
  1727. return value;
  1728. } else {
  1729. // proto2 requires enum values to be valid.
  1730. fail(value, "not a valid enum value");
  1731. }
  1732. }
  1733. // Embedded message
  1734. case ProtoBuf.TYPES["group"]:
  1735. case ProtoBuf.TYPES["message"]: {
  1736. if (!value || typeof value !== 'object')
  1737. fail(typeof value, "object expected");
  1738. if (value instanceof this.resolvedType.clazz)
  1739. return value;
  1740. if (value instanceof ProtoBuf.Builder.Message) {
  1741. // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
  1742. var obj = {};
  1743. for (var i in value)
  1744. if (value.hasOwnProperty(i))
  1745. obj[i] = value[i];
  1746. value = obj;
  1747. }
  1748. // Else let's try to construct one from a key-value object
  1749. return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
  1750. }
  1751. }
  1752. // We should never end here
  1753. throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
  1754. };
  1755. /**
  1756. * Calculates the byte length of an element on the wire.
  1757. * @param {number} id Field number
  1758. * @param {*} value Field value
  1759. * @returns {number} Byte length
  1760. * @throws {Error} If the value cannot be calculated
  1761. * @expose
  1762. */
  1763. ElementPrototype.calculateLength = function(id, value) {
  1764. if (value === null) return 0; // Nothing to encode
  1765. // Tag has already been written
  1766. var n;
  1767. switch (this.type) {
  1768. case ProtoBuf.TYPES["int32"]:
  1769. return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
  1770. case ProtoBuf.TYPES["uint32"]:
  1771. return ByteBuffer.calculateVarint32(value);
  1772. case ProtoBuf.TYPES["sint32"]:
  1773. return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
  1774. case ProtoBuf.TYPES["fixed32"]:
  1775. case ProtoBuf.TYPES["sfixed32"]:
  1776. case ProtoBuf.TYPES["float"]:
  1777. return 4;
  1778. case ProtoBuf.TYPES["int64"]:
  1779. case ProtoBuf.TYPES["uint64"]:
  1780. return ByteBuffer.calculateVarint64(value);
  1781. case ProtoBuf.TYPES["sint64"]:
  1782. return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
  1783. case ProtoBuf.TYPES["fixed64"]:
  1784. case ProtoBuf.TYPES["sfixed64"]:
  1785. return 8;
  1786. case ProtoBuf.TYPES["bool"]:
  1787. return 1;
  1788. case ProtoBuf.TYPES["enum"]:
  1789. return ByteBuffer.calculateVarint32(value);
  1790. case ProtoBuf.TYPES["double"]:
  1791. return 8;
  1792. case ProtoBuf.TYPES["string"]:
  1793. n = ByteBuffer.calculateUTF8Bytes(value);
  1794. return ByteBuffer.calculateVarint32(n) + n;
  1795. case ProtoBuf.TYPES["bytes"]:
  1796. if (value.remaining() < 0)
  1797. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  1798. return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
  1799. case ProtoBuf.TYPES["message"]:
  1800. n = this.resolvedType.calculate(value);
  1801. return ByteBuffer.calculateVarint32(n) + n;
  1802. case ProtoBuf.TYPES["group"]:
  1803. n = this.resolvedType.calculate(value);
  1804. return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  1805. }
  1806. // We should never end here
  1807. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  1808. };
  1809. /**
  1810. * Encodes a value to the specified buffer. Does not encode the key.
  1811. * @param {number} id Field number
  1812. * @param {*} value Field value
  1813. * @param {ByteBuffer} buffer ByteBuffer to encode to
  1814. * @return {ByteBuffer} The ByteBuffer for chaining
  1815. * @throws {Error} If the value cannot be encoded
  1816. * @expose
  1817. */
  1818. ElementPrototype.encodeValue = function(id, value, buffer) {
  1819. if (value === null) return buffer; // Nothing to encode
  1820. // Tag has already been written
  1821. switch (this.type) {
  1822. // 32bit signed varint
  1823. case ProtoBuf.TYPES["int32"]:
  1824. // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
  1825. // long – it is, effectively, treated like a very large unsigned integer." (see #122)
  1826. if (value < 0)
  1827. buffer.writeVarint64(value);
  1828. else
  1829. buffer.writeVarint32(value);
  1830. break;
  1831. // 32bit unsigned varint
  1832. case ProtoBuf.TYPES["uint32"]:
  1833. buffer.writeVarint32(value);
  1834. break;
  1835. // 32bit varint zig-zag
  1836. case ProtoBuf.TYPES["sint32"]:
  1837. buffer.writeVarint32ZigZag(value);
  1838. break;
  1839. // Fixed unsigned 32bit
  1840. case ProtoBuf.TYPES["fixed32"]:
  1841. buffer.writeUint32(value);
  1842. break;
  1843. // Fixed signed 32bit
  1844. case ProtoBuf.TYPES["sfixed32"]:
  1845. buffer.writeInt32(value);
  1846. break;
  1847. // 64bit varint as-is
  1848. case ProtoBuf.TYPES["int64"]:
  1849. case ProtoBuf.TYPES["uint64"]:
  1850. buffer.writeVarint64(value); // throws
  1851. break;
  1852. // 64bit varint zig-zag
  1853. case ProtoBuf.TYPES["sint64"]:
  1854. buffer.writeVarint64ZigZag(value); // throws
  1855. break;
  1856. // Fixed unsigned 64bit
  1857. case ProtoBuf.TYPES["fixed64"]:
  1858. buffer.writeUint64(value); // throws
  1859. break;
  1860. // Fixed signed 64bit
  1861. case ProtoBuf.TYPES["sfixed64"]:
  1862. buffer.writeInt64(value); // throws
  1863. break;
  1864. // Bool
  1865. case ProtoBuf.TYPES["bool"]:
  1866. if (typeof value === 'string')
  1867. buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
  1868. else
  1869. buffer.writeVarint32(value ? 1 : 0);
  1870. break;
  1871. // Constant enum value
  1872. case ProtoBuf.TYPES["enum"]:
  1873. buffer.writeVarint32(value);
  1874. break;
  1875. // 32bit float
  1876. case ProtoBuf.TYPES["float"]:
  1877. buffer.writeFloat32(value);
  1878. break;
  1879. // 64bit float
  1880. case ProtoBuf.TYPES["double"]:
  1881. buffer.writeFloat64(value);
  1882. break;
  1883. // Length-delimited string
  1884. case ProtoBuf.TYPES["string"]:
  1885. buffer.writeVString(value);
  1886. break;
  1887. // Length-delimited bytes
  1888. case ProtoBuf.TYPES["bytes"]:
  1889. if (value.remaining() < 0)
  1890. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  1891. var prevOffset = value.offset;
  1892. buffer.writeVarint32(value.remaining());
  1893. buffer.append(value);
  1894. value.offset = prevOffset;
  1895. break;
  1896. // Embedded message
  1897. case ProtoBuf.TYPES["message"]:
  1898. var bb = new ByteBuffer().LE();
  1899. this.resolvedType.encode(value, bb);
  1900. buffer.writeVarint32(bb.offset);
  1901. buffer.append(bb.flip());
  1902. break;
  1903. // Legacy group
  1904. case ProtoBuf.TYPES["group"]:
  1905. this.resolvedType.encode(value, buffer);
  1906. buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  1907. break;
  1908. default:
  1909. // We should never end here
  1910. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  1911. }
  1912. return buffer;
  1913. };
  1914. /**
  1915. * Decode one element value from the specified buffer.
  1916. * @param {ByteBuffer} buffer ByteBuffer to decode from
  1917. * @param {number} wireType The field wire type
  1918. * @param {number} id The field number
  1919. * @return {*} Decoded value
  1920. * @throws {Error} If the field cannot be decoded
  1921. * @expose
  1922. */
  1923. ElementPrototype.decode = function(buffer, wireType, id) {
  1924. if (wireType != this.type.wireType)
  1925. throw Error("Unexpected wire type for element");
  1926. var value, nBytes;
  1927. switch (this.type) {
  1928. // 32bit signed varint
  1929. case ProtoBuf.TYPES["int32"]:
  1930. return buffer.readVarint32() | 0;
  1931. // 32bit unsigned varint
  1932. case ProtoBuf.TYPES["uint32"]:
  1933. return buffer.readVarint32() >>> 0;
  1934. // 32bit signed varint zig-zag
  1935. case ProtoBuf.TYPES["sint32"]:
  1936. return buffer.readVarint32ZigZag() | 0;
  1937. // Fixed 32bit unsigned
  1938. case ProtoBuf.TYPES["fixed32"]:
  1939. return buffer.readUint32() >>> 0;
  1940. case ProtoBuf.TYPES["sfixed32"]:
  1941. return buffer.readInt32() | 0;
  1942. // 64bit signed varint
  1943. case ProtoBuf.TYPES["int64"]:
  1944. return buffer.readVarint64();
  1945. // 64bit unsigned varint
  1946. case ProtoBuf.TYPES["uint64"]:
  1947. return buffer.readVarint64().toUnsigned();
  1948. // 64bit signed varint zig-zag
  1949. case ProtoBuf.TYPES["sint64"]:
  1950. return buffer.readVarint64ZigZag();
  1951. // Fixed 64bit unsigned
  1952. case ProtoBuf.TYPES["fixed64"]:
  1953. return buffer.readUint64();
  1954. // Fixed 64bit signed
  1955. case ProtoBuf.TYPES["sfixed64"]:
  1956. return buffer.readInt64();
  1957. // Bool varint
  1958. case ProtoBuf.TYPES["bool"]:
  1959. return !!buffer.readVarint32();
  1960. // Constant enum value (varint)
  1961. case ProtoBuf.TYPES["enum"]:
  1962. // The following Builder.Message#set will already throw
  1963. return buffer.readVarint32();
  1964. // 32bit float
  1965. case ProtoBuf.TYPES["float"]:
  1966. return buffer.readFloat();
  1967. // 64bit float
  1968. case ProtoBuf.TYPES["double"]:
  1969. return buffer.readDouble();
  1970. // Length-delimited string
  1971. case ProtoBuf.TYPES["string"]:
  1972. return buffer.readVString();
  1973. // Length-delimited bytes
  1974. case ProtoBuf.TYPES["bytes"]: {
  1975. nBytes = buffer.readVarint32();
  1976. if (buffer.remaining() < nBytes)
  1977. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  1978. value = buffer.clone(); // Offset already set
  1979. value.limit = value.offset+nBytes;
  1980. buffer.offset += nBytes;
  1981. return value;
  1982. }
  1983. // Length-delimited embedded message
  1984. case ProtoBuf.TYPES["message"]: {
  1985. nBytes = buffer.readVarint32();
  1986. return this.resolvedType.decode(buffer, nBytes);
  1987. }
  1988. // Legacy group
  1989. case ProtoBuf.TYPES["group"]:
  1990. return this.resolvedType.decode(buffer, -1, id);
  1991. }
  1992. // We should never end here
  1993. throw Error("[INTERNAL] Illegal decode type");
  1994. };
  1995. /**
  1996. * Converts a value from a string to the canonical element type.
  1997. *
  1998. * Legal only when isMapKey is true.
  1999. *
  2000. * @param {string} str The string value
  2001. * @returns {*} The value
  2002. */
  2003. ElementPrototype.valueFromString = function(str) {
  2004. if (!this.isMapKey) {
  2005. throw Error("valueFromString() called on non-map-key element");
  2006. }
  2007. switch (this.type) {
  2008. case ProtoBuf.TYPES["int32"]:
  2009. case ProtoBuf.TYPES["sint32"]:
  2010. case ProtoBuf.TYPES["sfixed32"]:
  2011. case ProtoBuf.TYPES["uint32"]:
  2012. case ProtoBuf.TYPES["fixed32"]:
  2013. return this.verifyValue(parseInt(str));
  2014. case ProtoBuf.TYPES["int64"]:
  2015. case ProtoBuf.TYPES["sint64"]:
  2016. case ProtoBuf.TYPES["sfixed64"]:
  2017. case ProtoBuf.TYPES["uint64"]:
  2018. case ProtoBuf.TYPES["fixed64"]:
  2019. // Long-based fields support conversions from string already.
  2020. return this.verifyValue(str);
  2021. case ProtoBuf.TYPES["bool"]:
  2022. return str === "true";
  2023. case ProtoBuf.TYPES["string"]:
  2024. return this.verifyValue(str);
  2025. case ProtoBuf.TYPES["bytes"]:
  2026. return ByteBuffer.fromBinary(str);
  2027. }
  2028. };
  2029. /**
  2030. * Converts a value from the canonical element type to a string.
  2031. *
  2032. * It should be the case that `valueFromString(valueToString(val))` returns
  2033. * a value equivalent to `verifyValue(val)` for every legal value of `val`
  2034. * according to this element type.
  2035. *
  2036. * This may be used when the element must be stored or used as a string,
  2037. * e.g., as a map key on an Object.
  2038. *
  2039. * Legal only when isMapKey is true.
  2040. *
  2041. * @param {*} val The value
  2042. * @returns {string} The string form of the value.
  2043. */
  2044. ElementPrototype.valueToString = function(value) {
  2045. if (!this.isMapKey) {
  2046. throw Error("valueToString() called on non-map-key element");
  2047. }
  2048. if (this.type === ProtoBuf.TYPES["bytes"]) {
  2049. return value.toString("binary");
  2050. } else {
  2051. return value.toString();
  2052. }
  2053. };
  2054. /**
  2055. * @alias ProtoBuf.Reflect.Element
  2056. * @expose
  2057. */
  2058. Reflect.Element = Element;
  2059. /**
  2060. * Constructs a new Message.
  2061. * @exports ProtoBuf.Reflect.Message
  2062. * @param {!ProtoBuf.Builder} builder Builder reference
  2063. * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
  2064. * @param {string} name Message name
  2065. * @param {Object.<string,*>=} options Message options
  2066. * @param {boolean=} isGroup `true` if this is a legacy group
  2067. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  2068. * @constructor
  2069. * @extends ProtoBuf.Reflect.Namespace
  2070. */
  2071. var Message = function(builder, parent, name, options, isGroup, syntax) {
  2072. Namespace.call(this, builder, parent, name, options, syntax);
  2073. /**
  2074. * @override
  2075. */
  2076. this.className = "Message";
  2077. /**
  2078. * Extensions range.
  2079. * @type {!Array.<number>|undefined}
  2080. * @expose
  2081. */
  2082. this.extensions = undefined;
  2083. /**
  2084. * Runtime message class.
  2085. * @type {?function(new:ProtoBuf.Builder.Message)}
  2086. * @expose
  2087. */
  2088. this.clazz = null;
  2089. /**
  2090. * Whether this is a legacy group or not.
  2091. * @type {boolean}
  2092. * @expose
  2093. */
  2094. this.isGroup = !!isGroup;
  2095. // The following cached collections are used to efficiently iterate over or look up fields when decoding.
  2096. /**
  2097. * Cached fields.
  2098. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
  2099. * @private
  2100. */
  2101. this._fields = null;
  2102. /**
  2103. * Cached fields by id.
  2104. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
  2105. * @private
  2106. */
  2107. this._fieldsById = null;
  2108. /**
  2109. * Cached fields by name.
  2110. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
  2111. * @private
  2112. */
  2113. this._fieldsByName = null;
  2114. };
  2115. /**
  2116. * @alias ProtoBuf.Reflect.Message.prototype
  2117. * @inner
  2118. */
  2119. var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
  2120. /**
  2121. * Builds the message and returns the runtime counterpart, which is a fully functional class.
  2122. * @see ProtoBuf.Builder.Message
  2123. * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
  2124. * @return {ProtoBuf.Reflect.Message} Message class
  2125. * @throws {Error} If the message cannot be built
  2126. * @expose
  2127. */
  2128. MessagePrototype.build = function(rebuild) {
  2129. if (this.clazz && !rebuild)
  2130. return this.clazz;
  2131. // Create the runtime Message class in its own scope
  2132. var clazz = (function(ProtoBuf, T) {
  2133. var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
  2134. oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
  2135. /**
  2136. * Constructs a new runtime Message.
  2137. * @name ProtoBuf.Builder.Message
  2138. * @class Barebone of all runtime messages.
  2139. * @param {!Object.<string,*>|string} values Preset values
  2140. * @param {...string} var_args
  2141. * @constructor
  2142. * @throws {Error} If the message cannot be created
  2143. */
  2144. var Message = function(values, var_args) {
  2145. ProtoBuf.Builder.Message.call(this);
  2146. // Create virtual oneof properties
  2147. for (var i=0, k=oneofs.length; i<k; ++i)
  2148. this[oneofs[i].name] = null;
  2149. // Create fields and set default values
  2150. for (i=0, k=fields.length; i<k; ++i) {
  2151. var field = fields[i];
  2152. this[field.name] =
  2153. field.repeated ? [] :
  2154. (field.map ? new ProtoBuf.Map(field) : null);
  2155. if ((field.required || T.syntax === 'proto3') &&
  2156. field.defaultValue !== null)
  2157. this[field.name] = field.defaultValue;
  2158. }
  2159. if (arguments.length > 0) {
  2160. var value;
  2161. // Set field values from a values object
  2162. if (arguments.length === 1 && values !== null && typeof values === 'object' &&
  2163. /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
  2164. /* not a repeated field */ !Array.isArray(values) &&
  2165. /* not a Map */ !(values instanceof ProtoBuf.Map) &&
  2166. /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
  2167. /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
  2168. /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
  2169. this.$set(values);
  2170. } else // Set field values from arguments, in declaration order
  2171. for (i=0, k=arguments.length; i<k; ++i)
  2172. if (typeof (value = arguments[i]) !== 'undefined')
  2173. this.$set(fields[i].name, value); // May throw
  2174. }
  2175. };
  2176. /**
  2177. * @alias ProtoBuf.Builder.Message.prototype
  2178. * @inner
  2179. */
  2180. var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
  2181. /**
  2182. * Adds a value to a repeated field.
  2183. * @name ProtoBuf.Builder.Message#add
  2184. * @function
  2185. * @param {string} key Field name
  2186. * @param {*} value Value to add
  2187. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  2188. * @returns {!ProtoBuf.Builder.Message} this
  2189. * @throws {Error} If the value cannot be added
  2190. * @expose
  2191. */
  2192. MessagePrototype.add = function(key, value, noAssert) {
  2193. var field = T._fieldsByName[key];
  2194. if (!noAssert) {
  2195. if (!field)
  2196. throw Error(this+"#"+key+" is undefined");
  2197. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2198. throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
  2199. if (!field.repeated)
  2200. throw Error(this+"#"+key+" is not a repeated field");
  2201. value = field.verifyValue(value, true);
  2202. }
  2203. if (this[key] === null)
  2204. this[key] = [];
  2205. this[key].push(value);
  2206. return this;
  2207. };
  2208. /**
  2209. * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
  2210. * @name ProtoBuf.Builder.Message#$add
  2211. * @function
  2212. * @param {string} key Field name
  2213. * @param {*} value Value to add
  2214. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  2215. * @returns {!ProtoBuf.Builder.Message} this
  2216. * @throws {Error} If the value cannot be added
  2217. * @expose
  2218. */
  2219. MessagePrototype.$add = MessagePrototype.add;
  2220. /**
  2221. * Sets a field's value.
  2222. * @name ProtoBuf.Builder.Message#set
  2223. * @function
  2224. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  2225. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  2226. * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
  2227. * @returns {!ProtoBuf.Builder.Message} this
  2228. * @throws {Error} If the value cannot be set
  2229. * @expose
  2230. */
  2231. MessagePrototype.set = function(keyOrObj, value, noAssert) {
  2232. if (keyOrObj && typeof keyOrObj === 'object') {
  2233. noAssert = value;
  2234. for (var ikey in keyOrObj)
  2235. if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined')
  2236. this.$set(ikey, value, noAssert);
  2237. return this;
  2238. }
  2239. var field = T._fieldsByName[keyOrObj];
  2240. if (!noAssert) {
  2241. if (!field)
  2242. throw Error(this+"#"+keyOrObj+" is not a field: undefined");
  2243. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2244. throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
  2245. this[field.name] = (value = field.verifyValue(value)); // May throw
  2246. } else
  2247. this[keyOrObj] = value;
  2248. if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  2249. var currentField = this[field.oneof.name]; // Virtual field references currently set field
  2250. if (value !== null) {
  2251. if (currentField !== null && currentField !== field.name)
  2252. this[currentField] = null; // Clear currently set field
  2253. this[field.oneof.name] = field.name; // Point virtual field at this field
  2254. } else if (/* value === null && */currentField === keyOrObj)
  2255. this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
  2256. }
  2257. return this;
  2258. };
  2259. /**
  2260. * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
  2261. * @name ProtoBuf.Builder.Message#$set
  2262. * @function
  2263. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  2264. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  2265. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2266. * @throws {Error} If the value cannot be set
  2267. * @expose
  2268. */
  2269. MessagePrototype.$set = MessagePrototype.set;
  2270. /**
  2271. * Gets a field's value.
  2272. * @name ProtoBuf.Builder.Message#get
  2273. * @function
  2274. * @param {string} key Key
  2275. * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
  2276. * @return {*} Value
  2277. * @throws {Error} If there is no such field
  2278. * @expose
  2279. */
  2280. MessagePrototype.get = function(key, noAssert) {
  2281. if (noAssert)
  2282. return this[key];
  2283. var field = T._fieldsByName[key];
  2284. if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
  2285. throw Error(this+"#"+key+" is not a field: undefined");
  2286. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2287. throw Error(this+"#"+key+" is not a field: "+field.toString(true));
  2288. return this[field.name];
  2289. };
  2290. /**
  2291. * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
  2292. * @name ProtoBuf.Builder.Message#$get
  2293. * @function
  2294. * @param {string} key Key
  2295. * @return {*} Value
  2296. * @throws {Error} If there is no such field
  2297. * @expose
  2298. */
  2299. MessagePrototype.$get = MessagePrototype.get;
  2300. // Getters and setters
  2301. for (var i=0; i<fields.length; i++) {
  2302. var field = fields[i];
  2303. // no setters for extension fields as these are named by their fqn
  2304. if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
  2305. continue;
  2306. if (T.builder.options['populateAccessors'])
  2307. (function(field) {
  2308. // set/get[SomeValue]
  2309. var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
  2310. return match.toUpperCase().replace('_','');
  2311. });
  2312. Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
  2313. // set/get_[some_value] FIXME: Do we really need these?
  2314. var name = field.originalName.replace(/([A-Z])/g, function(match) {
  2315. return "_"+match;
  2316. });
  2317. /**
  2318. * The current field's unbound setter function.
  2319. * @function
  2320. * @param {*} value
  2321. * @param {boolean=} noAssert
  2322. * @returns {!ProtoBuf.Builder.Message}
  2323. * @inner
  2324. */
  2325. var setter = function(value, noAssert) {
  2326. this[field.name] = noAssert ? value : field.verifyValue(value);
  2327. return this;
  2328. };
  2329. /**
  2330. * The current field's unbound getter function.
  2331. * @function
  2332. * @returns {*}
  2333. * @inner
  2334. */
  2335. var getter = function() {
  2336. return this[field.name];
  2337. };
  2338. if (T.getChild("set"+Name) === null)
  2339. /**
  2340. * Sets a value. This method is present for each field, but only if there is no name conflict with
  2341. * another field.
  2342. * @name ProtoBuf.Builder.Message#set[SomeField]
  2343. * @function
  2344. * @param {*} value Value to set
  2345. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2346. * @returns {!ProtoBuf.Builder.Message} this
  2347. * @abstract
  2348. * @throws {Error} If the value cannot be set
  2349. */
  2350. MessagePrototype["set"+Name] = setter;
  2351. if (T.getChild("set_"+name) === null)
  2352. /**
  2353. * Sets a value. This method is present for each field, but only if there is no name conflict with
  2354. * another field.
  2355. * @name ProtoBuf.Builder.Message#set_[some_field]
  2356. * @function
  2357. * @param {*} value Value to set
  2358. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2359. * @returns {!ProtoBuf.Builder.Message} this
  2360. * @abstract
  2361. * @throws {Error} If the value cannot be set
  2362. */
  2363. MessagePrototype["set_"+name] = setter;
  2364. if (T.getChild("get"+Name) === null)
  2365. /**
  2366. * Gets a value. This method is present for each field, but only if there is no name conflict with
  2367. * another field.
  2368. * @name ProtoBuf.Builder.Message#get[SomeField]
  2369. * @function
  2370. * @abstract
  2371. * @return {*} The value
  2372. */
  2373. MessagePrototype["get"+Name] = getter;
  2374. if (T.getChild("get_"+name) === null)
  2375. /**
  2376. * Gets a value. This method is present for each field, but only if there is no name conflict with
  2377. * another field.
  2378. * @name ProtoBuf.Builder.Message#get_[some_field]
  2379. * @function
  2380. * @return {*} The value
  2381. * @abstract
  2382. */
  2383. MessagePrototype["get_"+name] = getter;
  2384. })(field);
  2385. }
  2386. // En-/decoding
  2387. /**
  2388. * Encodes the message.
  2389. * @name ProtoBuf.Builder.Message#$encode
  2390. * @function
  2391. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2392. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2393. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2394. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2395. * returns the encoded ByteBuffer in the `encoded` property on the error.
  2396. * @expose
  2397. * @see ProtoBuf.Builder.Message#encode64
  2398. * @see ProtoBuf.Builder.Message#encodeHex
  2399. * @see ProtoBuf.Builder.Message#encodeAB
  2400. */
  2401. MessagePrototype.encode = function(buffer, noVerify) {
  2402. if (typeof buffer === 'boolean')
  2403. noVerify = buffer,
  2404. buffer = undefined;
  2405. var isNew = false;
  2406. if (!buffer)
  2407. buffer = new ByteBuffer(),
  2408. isNew = true;
  2409. var le = buffer.littleEndian;
  2410. try {
  2411. T.encode(this, buffer.LE(), noVerify);
  2412. return (isNew ? buffer.flip() : buffer).LE(le);
  2413. } catch (e) {
  2414. buffer.LE(le);
  2415. throw(e);
  2416. }
  2417. };
  2418. /**
  2419. * Encodes a message using the specified data payload.
  2420. * @param {!Object.<string,*>} data Data payload
  2421. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2422. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2423. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2424. * @expose
  2425. */
  2426. Message.encode = function(data, buffer, noVerify) {
  2427. return new Message(data).encode(buffer, noVerify);
  2428. };
  2429. /**
  2430. * Calculates the byte length of the message.
  2431. * @name ProtoBuf.Builder.Message#calculate
  2432. * @function
  2433. * @returns {number} Byte length
  2434. * @throws {Error} If the message cannot be calculated or if required fields are missing.
  2435. * @expose
  2436. */
  2437. MessagePrototype.calculate = function() {
  2438. return T.calculate(this);
  2439. };
  2440. /**
  2441. * Encodes the varint32 length-delimited message.
  2442. * @name ProtoBuf.Builder.Message#encodeDelimited
  2443. * @function
  2444. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2445. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2446. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2447. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2448. * returns the encoded ByteBuffer in the `encoded` property on the error.
  2449. * @expose
  2450. */
  2451. MessagePrototype.encodeDelimited = function(buffer, noVerify) {
  2452. var isNew = false;
  2453. if (!buffer)
  2454. buffer = new ByteBuffer(),
  2455. isNew = true;
  2456. var enc = new ByteBuffer().LE();
  2457. T.encode(this, enc, noVerify).flip();
  2458. buffer.writeVarint32(enc.remaining());
  2459. buffer.append(enc);
  2460. return isNew ? buffer.flip() : buffer;
  2461. };
  2462. /**
  2463. * Directly encodes the message to an ArrayBuffer.
  2464. * @name ProtoBuf.Builder.Message#encodeAB
  2465. * @function
  2466. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  2467. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2468. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  2469. * @expose
  2470. */
  2471. MessagePrototype.encodeAB = function() {
  2472. try {
  2473. return this.encode().toArrayBuffer();
  2474. } catch (e) {
  2475. if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
  2476. throw(e);
  2477. }
  2478. };
  2479. /**
  2480. * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
  2481. * @name ProtoBuf.Builder.Message#toArrayBuffer
  2482. * @function
  2483. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  2484. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2485. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  2486. * @expose
  2487. */
  2488. MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
  2489. /**
  2490. * Directly encodes the message to a node Buffer.
  2491. * @name ProtoBuf.Builder.Message#encodeNB
  2492. * @function
  2493. * @return {!Buffer}
  2494. * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
  2495. * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
  2496. * @expose
  2497. */
  2498. MessagePrototype.encodeNB = function() {
  2499. try {
  2500. return this.encode().toBuffer();
  2501. } catch (e) {
  2502. if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
  2503. throw(e);
  2504. }
  2505. };
  2506. /**
  2507. * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
  2508. * @name ProtoBuf.Builder.Message#toBuffer
  2509. * @function
  2510. * @return {!Buffer}
  2511. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2512. * returns the encoded node Buffer in the `encoded` property on the error.
  2513. * @expose
  2514. */
  2515. MessagePrototype.toBuffer = MessagePrototype.encodeNB;
  2516. /**
  2517. * Directly encodes the message to a base64 encoded string.
  2518. * @name ProtoBuf.Builder.Message#encode64
  2519. * @function
  2520. * @return {string} Base64 encoded string
  2521. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  2522. * still returns the encoded base64 string in the `encoded` property on the error.
  2523. * @expose
  2524. */
  2525. MessagePrototype.encode64 = function() {
  2526. try {
  2527. return this.encode().toBase64();
  2528. } catch (e) {
  2529. if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
  2530. throw(e);
  2531. }
  2532. };
  2533. /**
  2534. * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
  2535. * @name ProtoBuf.Builder.Message#toBase64
  2536. * @function
  2537. * @return {string} Base64 encoded string
  2538. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2539. * returns the encoded base64 string in the `encoded` property on the error.
  2540. * @expose
  2541. */
  2542. MessagePrototype.toBase64 = MessagePrototype.encode64;
  2543. /**
  2544. * Directly encodes the message to a hex encoded string.
  2545. * @name ProtoBuf.Builder.Message#encodeHex
  2546. * @function
  2547. * @return {string} Hex encoded string
  2548. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  2549. * still returns the encoded hex string in the `encoded` property on the error.
  2550. * @expose
  2551. */
  2552. MessagePrototype.encodeHex = function() {
  2553. try {
  2554. return this.encode().toHex();
  2555. } catch (e) {
  2556. if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
  2557. throw(e);
  2558. }
  2559. };
  2560. /**
  2561. * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
  2562. * @name ProtoBuf.Builder.Message#toHex
  2563. * @function
  2564. * @return {string} Hex encoded string
  2565. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2566. * returns the encoded hex string in the `encoded` property on the error.
  2567. * @expose
  2568. */
  2569. MessagePrototype.toHex = MessagePrototype.encodeHex;
  2570. /**
  2571. * Clones a message object or field value to a raw object.
  2572. * @param {*} obj Object to clone
  2573. * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
  2574. * @param {boolean} longsAsStrings Whether to encode longs as strings
  2575. * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
  2576. * @returns {*} Cloned object
  2577. * @inner
  2578. */
  2579. function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
  2580. if (obj === null || typeof obj !== 'object') {
  2581. // Convert enum values to their respective names
  2582. if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
  2583. var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
  2584. if (name !== null)
  2585. return name;
  2586. }
  2587. // Pass-through string, number, boolean, null...
  2588. return obj;
  2589. }
  2590. // Convert ByteBuffers to raw buffer or strings
  2591. if (ByteBuffer.isByteBuffer(obj))
  2592. return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
  2593. // Convert Longs to proper objects or strings
  2594. if (ProtoBuf.Long.isLong(obj))
  2595. return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
  2596. var clone;
  2597. // Clone arrays
  2598. if (Array.isArray(obj)) {
  2599. clone = [];
  2600. obj.forEach(function(v, k) {
  2601. clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
  2602. });
  2603. return clone;
  2604. }
  2605. clone = {};
  2606. // Convert maps to objects
  2607. if (obj instanceof ProtoBuf.Map) {
  2608. var it = obj.entries();
  2609. for (var e = it.next(); !e.done; e = it.next())
  2610. clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
  2611. return clone;
  2612. }
  2613. // Everything else is a non-null object
  2614. var type = obj.$type,
  2615. field = undefined;
  2616. for (var i in obj)
  2617. if (obj.hasOwnProperty(i)) {
  2618. if (type && (field = type.getChild(i)))
  2619. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
  2620. else
  2621. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
  2622. }
  2623. return clone;
  2624. }
  2625. /**
  2626. * Returns the message's raw payload.
  2627. * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
  2628. * @param {boolean} longsAsStrings Whether to encode longs as strings
  2629. * @returns {Object.<string,*>} Raw payload
  2630. * @expose
  2631. */
  2632. MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
  2633. return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
  2634. };
  2635. /**
  2636. * Encodes a message to JSON.
  2637. * @returns {string} JSON string
  2638. * @expose
  2639. */
  2640. MessagePrototype.encodeJSON = function() {
  2641. return JSON.stringify(
  2642. cloneRaw(this,
  2643. /* binary-as-base64 */ true,
  2644. /* longs-as-strings */ true,
  2645. this.$type
  2646. )
  2647. );
  2648. };
  2649. /**
  2650. * Decodes a message from the specified buffer or string.
  2651. * @name ProtoBuf.Builder.Message.decode
  2652. * @function
  2653. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  2654. * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
  2655. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  2656. * @return {!ProtoBuf.Builder.Message} Decoded message
  2657. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2658. * returns the decoded message with missing fields in the `decoded` property on the error.
  2659. * @expose
  2660. * @see ProtoBuf.Builder.Message.decode64
  2661. * @see ProtoBuf.Builder.Message.decodeHex
  2662. */
  2663. Message.decode = function(buffer, length, enc) {
  2664. if (typeof length === 'string')
  2665. enc = length,
  2666. length = -1;
  2667. if (typeof buffer === 'string')
  2668. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  2669. buffer = ByteBuffer.isByteBuffer(buffer) ? buffer : ByteBuffer.wrap(buffer); // May throw
  2670. var le = buffer.littleEndian;
  2671. try {
  2672. var msg = T.decode(buffer.LE());
  2673. buffer.LE(le);
  2674. return msg;
  2675. } catch (e) {
  2676. buffer.LE(le);
  2677. throw(e);
  2678. }
  2679. };
  2680. /**
  2681. * Decodes a varint32 length-delimited message from the specified buffer or string.
  2682. * @name ProtoBuf.Builder.Message.decodeDelimited
  2683. * @function
  2684. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  2685. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  2686. * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
  2687. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2688. * returns the decoded message with missing fields in the `decoded` property on the error.
  2689. * @expose
  2690. */
  2691. Message.decodeDelimited = function(buffer, enc) {
  2692. if (typeof buffer === 'string')
  2693. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  2694. buffer = ByteBuffer.isByteBuffer(buffer) ? buffer : ByteBuffer.wrap(buffer); // May throw
  2695. if (buffer.remaining() < 1)
  2696. return null;
  2697. var off = buffer.offset,
  2698. len = buffer.readVarint32();
  2699. if (buffer.remaining() < len) {
  2700. buffer.offset = off;
  2701. return null;
  2702. }
  2703. try {
  2704. var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
  2705. buffer.offset += len;
  2706. return msg;
  2707. } catch (err) {
  2708. buffer.offset += len;
  2709. throw err;
  2710. }
  2711. };
  2712. /**
  2713. * Decodes the message from the specified base64 encoded string.
  2714. * @name ProtoBuf.Builder.Message.decode64
  2715. * @function
  2716. * @param {string} str String to decode from
  2717. * @return {!ProtoBuf.Builder.Message} Decoded message
  2718. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2719. * returns the decoded message with missing fields in the `decoded` property on the error.
  2720. * @expose
  2721. */
  2722. Message.decode64 = function(str) {
  2723. return Message.decode(str, "base64");
  2724. };
  2725. /**
  2726. * Decodes the message from the specified hex encoded string.
  2727. * @name ProtoBuf.Builder.Message.decodeHex
  2728. * @function
  2729. * @param {string} str String to decode from
  2730. * @return {!ProtoBuf.Builder.Message} Decoded message
  2731. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2732. * returns the decoded message with missing fields in the `decoded` property on the error.
  2733. * @expose
  2734. */
  2735. Message.decodeHex = function(str) {
  2736. return Message.decode(str, "hex");
  2737. };
  2738. /**
  2739. * Decodes the message from a JSON string.
  2740. * @name ProtoBuf.Builder.Message.decodeJSON
  2741. * @function
  2742. * @param {string} str String to decode from
  2743. * @return {!ProtoBuf.Builder.Message} Decoded message
  2744. * @throws {Error} If the message cannot be decoded or if required fields are
  2745. * missing.
  2746. * @expose
  2747. */
  2748. Message.decodeJSON = function(str) {
  2749. return new Message(JSON.parse(str));
  2750. };
  2751. // Utility
  2752. /**
  2753. * Returns a string representation of this Message.
  2754. * @name ProtoBuf.Builder.Message#toString
  2755. * @function
  2756. * @return {string} String representation as of ".Fully.Qualified.MessageName"
  2757. * @expose
  2758. */
  2759. MessagePrototype.toString = function() {
  2760. return T.toString();
  2761. };
  2762. // Properties
  2763. /**
  2764. * Message options.
  2765. * @name ProtoBuf.Builder.Message.$options
  2766. * @type {Object.<string,*>}
  2767. * @expose
  2768. */
  2769. var $optionsS; // cc needs this
  2770. /**
  2771. * Message options.
  2772. * @name ProtoBuf.Builder.Message#$options
  2773. * @type {Object.<string,*>}
  2774. * @expose
  2775. */
  2776. var $options;
  2777. /**
  2778. * Reflection type.
  2779. * @name ProtoBuf.Builder.Message.$type
  2780. * @type {!ProtoBuf.Reflect.Message}
  2781. * @expose
  2782. */
  2783. var $typeS;
  2784. /**
  2785. * Reflection type.
  2786. * @name ProtoBuf.Builder.Message#$type
  2787. * @type {!ProtoBuf.Reflect.Message}
  2788. * @expose
  2789. */
  2790. var $type;
  2791. if (Object.defineProperty)
  2792. Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
  2793. Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
  2794. Object.defineProperty(Message, "$type", { "value": T }),
  2795. Object.defineProperty(MessagePrototype, "$type", { "value": T });
  2796. return Message;
  2797. })(ProtoBuf, this);
  2798. // Static enums and prototyped sub-messages / cached collections
  2799. this._fields = [];
  2800. this._fieldsById = {};
  2801. this._fieldsByName = {};
  2802. for (var i=0, k=this.children.length, child; i<k; i++) {
  2803. child = this.children[i];
  2804. if (child instanceof Enum || child instanceof Message || child instanceof Service) {
  2805. if (clazz.hasOwnProperty(child.name))
  2806. throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
  2807. clazz[child.name] = child.build();
  2808. } else if (child instanceof Message.Field)
  2809. child.build(),
  2810. this._fields.push(child),
  2811. this._fieldsById[child.id] = child,
  2812. this._fieldsByName[child.name] = child;
  2813. else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
  2814. throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
  2815. }
  2816. return this.clazz = clazz;
  2817. };
  2818. /**
  2819. * Encodes a runtime message's contents to the specified buffer.
  2820. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  2821. * @param {ByteBuffer} buffer ByteBuffer to write to
  2822. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2823. * @return {ByteBuffer} The ByteBuffer for chaining
  2824. * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
  2825. * @expose
  2826. */
  2827. MessagePrototype.encode = function(message, buffer, noVerify) {
  2828. var fieldMissing = null,
  2829. field;
  2830. for (var i=0, k=this._fields.length, val; i<k; ++i) {
  2831. field = this._fields[i];
  2832. val = message[field.name];
  2833. if (field.required && val === null) {
  2834. if (fieldMissing === null)
  2835. fieldMissing = field;
  2836. } else
  2837. field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
  2838. }
  2839. if (fieldMissing !== null) {
  2840. var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
  2841. err["encoded"] = buffer; // Still expose what we got
  2842. throw(err);
  2843. }
  2844. return buffer;
  2845. };
  2846. /**
  2847. * Calculates a runtime message's byte length.
  2848. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  2849. * @returns {number} Byte length
  2850. * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
  2851. * @expose
  2852. */
  2853. MessagePrototype.calculate = function(message) {
  2854. for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
  2855. field = this._fields[i];
  2856. val = message[field.name];
  2857. if (field.required && val === null)
  2858. throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
  2859. else
  2860. n += field.calculate(val, message);
  2861. }
  2862. return n;
  2863. };
  2864. /**
  2865. * Skips all data until the end of the specified group has been reached.
  2866. * @param {number} expectedId Expected GROUPEND id
  2867. * @param {!ByteBuffer} buf ByteBuffer
  2868. * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
  2869. * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
  2870. * @inner
  2871. */
  2872. function skipTillGroupEnd(expectedId, buf) {
  2873. var tag = buf.readVarint32(), // Throws on OOB
  2874. wireType = tag & 0x07,
  2875. id = tag >>> 3;
  2876. switch (wireType) {
  2877. case ProtoBuf.WIRE_TYPES.VARINT:
  2878. do tag = buf.readUint8();
  2879. while ((tag & 0x80) === 0x80);
  2880. break;
  2881. case ProtoBuf.WIRE_TYPES.BITS64:
  2882. buf.offset += 8;
  2883. break;
  2884. case ProtoBuf.WIRE_TYPES.LDELIM:
  2885. tag = buf.readVarint32(); // reads the varint
  2886. buf.offset += tag; // skips n bytes
  2887. break;
  2888. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2889. skipTillGroupEnd(id, buf);
  2890. break;
  2891. case ProtoBuf.WIRE_TYPES.ENDGROUP:
  2892. if (id === expectedId)
  2893. return false;
  2894. else
  2895. throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
  2896. case ProtoBuf.WIRE_TYPES.BITS32:
  2897. buf.offset += 4;
  2898. break;
  2899. default:
  2900. throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
  2901. }
  2902. return true;
  2903. }
  2904. /**
  2905. * Decodes an encoded message and returns the decoded message.
  2906. * @param {ByteBuffer} buffer ByteBuffer to decode from
  2907. * @param {number=} length Message length. Defaults to decode all remaining data.
  2908. * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
  2909. * @return {ProtoBuf.Builder.Message} Decoded message
  2910. * @throws {Error} If the message cannot be decoded
  2911. * @expose
  2912. */
  2913. MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
  2914. length = typeof length === 'number' ? length : -1;
  2915. var start = buffer.offset,
  2916. msg = new (this.clazz)(),
  2917. tag, wireType, id, field;
  2918. while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
  2919. tag = buffer.readVarint32();
  2920. wireType = tag & 0x07;
  2921. id = tag >>> 3;
  2922. if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
  2923. if (id !== expectedGroupEndId)
  2924. throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
  2925. break;
  2926. }
  2927. if (!(field = this._fieldsById[id])) {
  2928. // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
  2929. switch (wireType) {
  2930. case ProtoBuf.WIRE_TYPES.VARINT:
  2931. buffer.readVarint32();
  2932. break;
  2933. case ProtoBuf.WIRE_TYPES.BITS32:
  2934. buffer.offset += 4;
  2935. break;
  2936. case ProtoBuf.WIRE_TYPES.BITS64:
  2937. buffer.offset += 8;
  2938. break;
  2939. case ProtoBuf.WIRE_TYPES.LDELIM:
  2940. var len = buffer.readVarint32();
  2941. buffer.offset += len;
  2942. break;
  2943. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2944. while (skipTillGroupEnd(id, buffer)) {}
  2945. break;
  2946. default:
  2947. throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
  2948. }
  2949. continue;
  2950. }
  2951. if (field.repeated && !field.options["packed"]) {
  2952. msg[field.name].push(field.decode(wireType, buffer));
  2953. } else if (field.map) {
  2954. var keyval = field.decode(wireType, buffer);
  2955. msg[field.name].set(keyval[0], keyval[1]);
  2956. } else {
  2957. msg[field.name] = field.decode(wireType, buffer);
  2958. if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  2959. var currentField = msg[field.oneof.name]; // Virtual field references currently set field
  2960. if (currentField !== null && currentField !== field.name)
  2961. msg[currentField] = null; // Clear currently set field
  2962. msg[field.oneof.name] = field.name; // Point virtual field at this field
  2963. }
  2964. }
  2965. }
  2966. // Check if all required fields are present and set default values for optional fields that are not
  2967. for (var i=0, k=this._fields.length; i<k; ++i) {
  2968. field = this._fields[i];
  2969. if (msg[field.name] === null) {
  2970. if (this.syntax === "proto3") { // Proto3 sets default values by specification
  2971. msg[field.name] = field.defaultValue;
  2972. } else if (field.required) {
  2973. var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
  2974. err["decoded"] = msg; // Still expose what we got
  2975. throw(err);
  2976. } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
  2977. msg[field.name] = field.defaultValue;
  2978. }
  2979. }
  2980. return msg;
  2981. };
  2982. /**
  2983. * @alias ProtoBuf.Reflect.Message
  2984. * @expose
  2985. */
  2986. Reflect.Message = Message;
  2987. /**
  2988. * Constructs a new Message Field.
  2989. * @exports ProtoBuf.Reflect.Message.Field
  2990. * @param {!ProtoBuf.Builder} builder Builder reference
  2991. * @param {!ProtoBuf.Reflect.Message} message Message reference
  2992. * @param {string} rule Rule, one of requried, optional, repeated
  2993. * @param {string?} keytype Key data type, if any.
  2994. * @param {string} type Data type, e.g. int32
  2995. * @param {string} name Field name
  2996. * @param {number} id Unique field id
  2997. * @param {Object.<string,*>=} options Options
  2998. * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
  2999. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  3000. * @constructor
  3001. * @extends ProtoBuf.Reflect.T
  3002. */
  3003. var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
  3004. T.call(this, builder, message, name);
  3005. /**
  3006. * @override
  3007. */
  3008. this.className = "Message.Field";
  3009. /**
  3010. * Message field required flag.
  3011. * @type {boolean}
  3012. * @expose
  3013. */
  3014. this.required = rule === "required";
  3015. /**
  3016. * Message field repeated flag.
  3017. * @type {boolean}
  3018. * @expose
  3019. */
  3020. this.repeated = rule === "repeated";
  3021. /**
  3022. * Message field map flag.
  3023. * @type {boolean}
  3024. * @expose
  3025. */
  3026. this.map = rule === "map";
  3027. /**
  3028. * Message field key type. Type reference string if unresolved, protobuf
  3029. * type if resolved. Valid only if this.map === true, null otherwise.
  3030. * @type {string|{name: string, wireType: number}|null}
  3031. * @expose
  3032. */
  3033. this.keyType = keytype || null;
  3034. /**
  3035. * Message field type. Type reference string if unresolved, protobuf type if
  3036. * resolved. In a map field, this is the value type.
  3037. * @type {string|{name: string, wireType: number}}
  3038. * @expose
  3039. */
  3040. this.type = type;
  3041. /**
  3042. * Resolved type reference inside the global namespace.
  3043. * @type {ProtoBuf.Reflect.T|null}
  3044. * @expose
  3045. */
  3046. this.resolvedType = null;
  3047. /**
  3048. * Unique message field id.
  3049. * @type {number}
  3050. * @expose
  3051. */
  3052. this.id = id;
  3053. /**
  3054. * Message field options.
  3055. * @type {!Object.<string,*>}
  3056. * @dict
  3057. * @expose
  3058. */
  3059. this.options = options || {};
  3060. /**
  3061. * Default value.
  3062. * @type {*}
  3063. * @expose
  3064. */
  3065. this.defaultValue = null;
  3066. /**
  3067. * Enclosing OneOf.
  3068. * @type {?ProtoBuf.Reflect.Message.OneOf}
  3069. * @expose
  3070. */
  3071. this.oneof = oneof || null;
  3072. /**
  3073. * Syntax level of this definition (e.g., proto3).
  3074. * @type {string}
  3075. * @expose
  3076. */
  3077. this.syntax = syntax || 'proto2';
  3078. /**
  3079. * Original field name.
  3080. * @type {string}
  3081. * @expose
  3082. */
  3083. this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
  3084. /**
  3085. * Element implementation. Created in build() after types are resolved.
  3086. * @type {ProtoBuf.Element}
  3087. * @expose
  3088. */
  3089. this.element = null;
  3090. /**
  3091. * Key element implementation, for map fields. Created in build() after
  3092. * types are resolved.
  3093. * @type {ProtoBuf.Element}
  3094. * @expose
  3095. */
  3096. this.keyElement = null;
  3097. // Convert field names to camel case notation if the override is set
  3098. if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
  3099. this.name = ProtoBuf.Util.toCamelCase(this.name);
  3100. };
  3101. /**
  3102. * @alias ProtoBuf.Reflect.Message.Field.prototype
  3103. * @inner
  3104. */
  3105. var FieldPrototype = Field.prototype = Object.create(T.prototype);
  3106. /**
  3107. * Builds the field.
  3108. * @override
  3109. * @expose
  3110. */
  3111. FieldPrototype.build = function() {
  3112. this.element = new Element(this.type, this.resolvedType, false, this.syntax);
  3113. if (this.map)
  3114. this.keyElement = new Element(this.keyType, undefined, true, this.syntax);
  3115. // In proto3, fields do not have field presence, and every field is set to
  3116. // its type's default value ("", 0, 0.0, or false).
  3117. if (this.syntax === 'proto3' && !this.repeated && !this.map)
  3118. this.defaultValue = Element.defaultFieldValue(this.type);
  3119. // Otherwise, default values are present when explicitly specified
  3120. else if (typeof this.options['default'] !== 'undefined')
  3121. this.defaultValue = this.verifyValue(this.options['default']);
  3122. };
  3123. /**
  3124. * Checks if the given value can be set for this field.
  3125. * @param {*} value Value to check
  3126. * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
  3127. * @return {*} Verified, maybe adjusted, value
  3128. * @throws {Error} If the value cannot be set for this field
  3129. * @expose
  3130. */
  3131. FieldPrototype.verifyValue = function(value, skipRepeated) {
  3132. skipRepeated = skipRepeated || false;
  3133. var self = this;
  3134. function fail(val, msg) {
  3135. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  3136. }
  3137. if (value === null) { // NULL values for optional fields
  3138. if (this.required)
  3139. fail(typeof value, "required");
  3140. if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
  3141. fail(typeof value, "proto3 field without field presence cannot be null");
  3142. return null;
  3143. }
  3144. var i;
  3145. if (this.repeated && !skipRepeated) { // Repeated values as arrays
  3146. if (!Array.isArray(value))
  3147. value = [value];
  3148. var res = [];
  3149. for (i=0; i<value.length; i++)
  3150. res.push(this.element.verifyValue(value[i]));
  3151. return res;
  3152. }
  3153. if (this.map && !skipRepeated) { // Map values as objects
  3154. if (!(value instanceof ProtoBuf.Map)) {
  3155. // If not already a Map, attempt to convert.
  3156. if (!(value instanceof Object)) {
  3157. fail(typeof value,
  3158. "expected ProtoBuf.Map or raw object for map field");
  3159. }
  3160. return new ProtoBuf.Map(this, value);
  3161. } else {
  3162. return value;
  3163. }
  3164. }
  3165. // All non-repeated fields expect no array
  3166. if (!this.repeated && Array.isArray(value))
  3167. fail(typeof value, "no array expected");
  3168. return this.element.verifyValue(value);
  3169. };
  3170. /**
  3171. * Determines whether the field will have a presence on the wire given its
  3172. * value.
  3173. * @param {*} value Verified field value
  3174. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3175. * @return {boolean} Whether the field will be present on the wire
  3176. */
  3177. FieldPrototype.hasWirePresence = function(value, message) {
  3178. if (this.syntax !== 'proto3')
  3179. return (value !== null);
  3180. if (this.oneof && message[this.oneof.name] === this.name)
  3181. return true;
  3182. switch (this.type) {
  3183. case ProtoBuf.TYPES["int32"]:
  3184. case ProtoBuf.TYPES["sint32"]:
  3185. case ProtoBuf.TYPES["sfixed32"]:
  3186. case ProtoBuf.TYPES["uint32"]:
  3187. case ProtoBuf.TYPES["fixed32"]:
  3188. return value !== 0;
  3189. case ProtoBuf.TYPES["int64"]:
  3190. case ProtoBuf.TYPES["sint64"]:
  3191. case ProtoBuf.TYPES["sfixed64"]:
  3192. case ProtoBuf.TYPES["uint64"]:
  3193. case ProtoBuf.TYPES["fixed64"]:
  3194. return value.low !== 0 || value.high !== 0;
  3195. case ProtoBuf.TYPES["bool"]:
  3196. return value;
  3197. case ProtoBuf.TYPES["float"]:
  3198. case ProtoBuf.TYPES["double"]:
  3199. return value !== 0.0;
  3200. case ProtoBuf.TYPES["string"]:
  3201. return value.length > 0;
  3202. case ProtoBuf.TYPES["bytes"]:
  3203. return value.remaining() > 0;
  3204. case ProtoBuf.TYPES["enum"]:
  3205. return value !== 0;
  3206. case ProtoBuf.TYPES["message"]:
  3207. return value !== null;
  3208. default:
  3209. return true;
  3210. }
  3211. };
  3212. /**
  3213. * Encodes the specified field value to the specified buffer.
  3214. * @param {*} value Verified field value
  3215. * @param {ByteBuffer} buffer ByteBuffer to encode to
  3216. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3217. * @return {ByteBuffer} The ByteBuffer for chaining
  3218. * @throws {Error} If the field cannot be encoded
  3219. * @expose
  3220. */
  3221. FieldPrototype.encode = function(value, buffer, message) {
  3222. if (this.type === null || typeof this.type !== 'object')
  3223. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  3224. if (value === null || (this.repeated && value.length == 0))
  3225. return buffer; // Optional omitted
  3226. try {
  3227. if (this.repeated) {
  3228. var i;
  3229. // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
  3230. // types) can be declared 'packed'."
  3231. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3232. // "All of the elements of the field are packed into a single key-value pair with wire type 2
  3233. // (length-delimited). Each element is encoded the same way it would be normally, except without a
  3234. // tag preceding it."
  3235. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3236. buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
  3237. var start = buffer.offset; // Remember where the contents begin
  3238. for (i=0; i<value.length; i++)
  3239. this.element.encodeValue(this.id, value[i], buffer);
  3240. var len = buffer.offset-start,
  3241. varintLen = ByteBuffer.calculateVarint32(len);
  3242. if (varintLen > 1) { // We need to move the contents
  3243. var contents = buffer.slice(start, buffer.offset);
  3244. start += varintLen-1;
  3245. buffer.offset = start;
  3246. buffer.append(contents);
  3247. }
  3248. buffer.writeVarint32(len, start-varintLen);
  3249. } else {
  3250. // "If your message definition has repeated elements (without the [packed=true] option), the encoded
  3251. // message has zero or more key-value pairs with the same tag number"
  3252. for (i=0; i<value.length; i++)
  3253. buffer.writeVarint32((this.id << 3) | this.type.wireType),
  3254. this.element.encodeValue(this.id, value[i], buffer);
  3255. }
  3256. } else if (this.map) {
  3257. // Write out each map entry as a submessage.
  3258. value.forEach(function(val, key, m) {
  3259. // Compute the length of the submessage (key, val) pair.
  3260. var length =
  3261. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  3262. this.keyElement.calculateLength(1, key) +
  3263. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  3264. this.element.calculateLength(2, val);
  3265. // Submessage with wire type of length-delimited.
  3266. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3267. buffer.writeVarint32(length);
  3268. // Write out the key and val.
  3269. buffer.writeVarint32((1 << 3) | this.keyType.wireType);
  3270. this.keyElement.encodeValue(1, key, buffer);
  3271. buffer.writeVarint32((2 << 3) | this.type.wireType);
  3272. this.element.encodeValue(2, val, buffer);
  3273. }, this);
  3274. } else {
  3275. if (this.hasWirePresence(value, message)) {
  3276. buffer.writeVarint32((this.id << 3) | this.type.wireType);
  3277. this.element.encodeValue(this.id, value, buffer);
  3278. }
  3279. }
  3280. } catch (e) {
  3281. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  3282. }
  3283. return buffer;
  3284. };
  3285. /**
  3286. * Calculates the length of this field's value on the network level.
  3287. * @param {*} value Field value
  3288. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3289. * @returns {number} Byte length
  3290. * @expose
  3291. */
  3292. FieldPrototype.calculate = function(value, message) {
  3293. value = this.verifyValue(value); // May throw
  3294. if (this.type === null || typeof this.type !== 'object')
  3295. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  3296. if (value === null || (this.repeated && value.length == 0))
  3297. return 0; // Optional omitted
  3298. var n = 0;
  3299. try {
  3300. if (this.repeated) {
  3301. var i, ni;
  3302. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3303. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3304. ni = 0;
  3305. for (i=0; i<value.length; i++)
  3306. ni += this.element.calculateLength(this.id, value[i]);
  3307. n += ByteBuffer.calculateVarint32(ni);
  3308. n += ni;
  3309. } else {
  3310. for (i=0; i<value.length; i++)
  3311. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
  3312. n += this.element.calculateLength(this.id, value[i]);
  3313. }
  3314. } else if (this.map) {
  3315. // Each map entry becomes a submessage.
  3316. value.forEach(function(val, key, m) {
  3317. // Compute the length of the submessage (key, val) pair.
  3318. var length =
  3319. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  3320. this.keyElement.calculateLength(1, key) +
  3321. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  3322. this.element.calculateLength(2, val);
  3323. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3324. n += ByteBuffer.calculateVarint32(length);
  3325. n += length;
  3326. }, this);
  3327. } else {
  3328. if (this.hasWirePresence(value, message)) {
  3329. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
  3330. n += this.element.calculateLength(this.id, value);
  3331. }
  3332. }
  3333. } catch (e) {
  3334. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  3335. }
  3336. return n;
  3337. };
  3338. /**
  3339. * Decode the field value from the specified buffer.
  3340. * @param {number} wireType Leading wire type
  3341. * @param {ByteBuffer} buffer ByteBuffer to decode from
  3342. * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
  3343. * @return {*} Decoded value: array for packed repeated fields, [key, value] for
  3344. * map fields, or an individual value otherwise.
  3345. * @throws {Error} If the field cannot be decoded
  3346. * @expose
  3347. */
  3348. FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
  3349. var value, nBytes;
  3350. // We expect wireType to match the underlying type's wireType unless we see
  3351. // a packed repeated field, or unless this is a map field.
  3352. var wireTypeOK =
  3353. (!this.map && wireType == this.type.wireType) ||
  3354. (!skipRepeated && this.repeated && this.options["packed"] &&
  3355. wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
  3356. (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
  3357. if (!wireTypeOK)
  3358. throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
  3359. // Handle packed repeated fields.
  3360. if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3361. if (!skipRepeated) {
  3362. nBytes = buffer.readVarint32();
  3363. nBytes = buffer.offset + nBytes; // Limit
  3364. var values = [];
  3365. while (buffer.offset < nBytes)
  3366. values.push(this.decode(this.type.wireType, buffer, true));
  3367. return values;
  3368. }
  3369. // Read the next value otherwise...
  3370. }
  3371. // Handle maps.
  3372. if (this.map) {
  3373. // Read one (key, value) submessage, and return [key, value]
  3374. var key = Element.defaultFieldValue(this.keyType);
  3375. value = Element.defaultFieldValue(this.type);
  3376. // Read the length
  3377. nBytes = buffer.readVarint32();
  3378. if (buffer.remaining() < nBytes)
  3379. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  3380. // Get a sub-buffer of this key/value submessage
  3381. var msgbuf = buffer.clone();
  3382. msgbuf.limit = msgbuf.offset + nBytes;
  3383. buffer.offset += nBytes;
  3384. while (msgbuf.remaining() > 0) {
  3385. var tag = msgbuf.readVarint32();
  3386. wireType = tag & 0x07;
  3387. var id = tag >>> 3;
  3388. if (id === 1) {
  3389. key = this.keyElement.decode(msgbuf, wireType, id);
  3390. } else if (id === 2) {
  3391. value = this.element.decode(msgbuf, wireType, id);
  3392. } else {
  3393. throw Error("Unexpected tag in map field key/value submessage");
  3394. }
  3395. }
  3396. return [key, value];
  3397. }
  3398. // Handle singular and non-packed repeated field values.
  3399. return this.element.decode(buffer, wireType, this.id);
  3400. };
  3401. /**
  3402. * @alias ProtoBuf.Reflect.Message.Field
  3403. * @expose
  3404. */
  3405. Reflect.Message.Field = Field;
  3406. /**
  3407. * Constructs a new Message ExtensionField.
  3408. * @exports ProtoBuf.Reflect.Message.ExtensionField
  3409. * @param {!ProtoBuf.Builder} builder Builder reference
  3410. * @param {!ProtoBuf.Reflect.Message} message Message reference
  3411. * @param {string} rule Rule, one of requried, optional, repeated
  3412. * @param {string} type Data type, e.g. int32
  3413. * @param {string} name Field name
  3414. * @param {number} id Unique field id
  3415. * @param {!Object.<string,*>=} options Options
  3416. * @constructor
  3417. * @extends ProtoBuf.Reflect.Message.Field
  3418. */
  3419. var ExtensionField = function(builder, message, rule, type, name, id, options) {
  3420. Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
  3421. /**
  3422. * Extension reference.
  3423. * @type {!ProtoBuf.Reflect.Extension}
  3424. * @expose
  3425. */
  3426. this.extension;
  3427. };
  3428. // Extends Field
  3429. ExtensionField.prototype = Object.create(Field.prototype);
  3430. /**
  3431. * @alias ProtoBuf.Reflect.Message.ExtensionField
  3432. * @expose
  3433. */
  3434. Reflect.Message.ExtensionField = ExtensionField;
  3435. /**
  3436. * Constructs a new Message OneOf.
  3437. * @exports ProtoBuf.Reflect.Message.OneOf
  3438. * @param {!ProtoBuf.Builder} builder Builder reference
  3439. * @param {!ProtoBuf.Reflect.Message} message Message reference
  3440. * @param {string} name OneOf name
  3441. * @constructor
  3442. * @extends ProtoBuf.Reflect.T
  3443. */
  3444. var OneOf = function(builder, message, name) {
  3445. T.call(this, builder, message, name);
  3446. /**
  3447. * Enclosed fields.
  3448. * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
  3449. * @expose
  3450. */
  3451. this.fields = [];
  3452. };
  3453. /**
  3454. * @alias ProtoBuf.Reflect.Message.OneOf
  3455. * @expose
  3456. */
  3457. Reflect.Message.OneOf = OneOf;
  3458. /**
  3459. * Constructs a new Enum.
  3460. * @exports ProtoBuf.Reflect.Enum
  3461. * @param {!ProtoBuf.Builder} builder Builder reference
  3462. * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
  3463. * @param {string} name Enum name
  3464. * @param {Object.<string,*>=} options Enum options
  3465. * @param {string?} syntax The syntax level (e.g., proto3)
  3466. * @constructor
  3467. * @extends ProtoBuf.Reflect.Namespace
  3468. */
  3469. var Enum = function(builder, parent, name, options, syntax) {
  3470. Namespace.call(this, builder, parent, name, options, syntax);
  3471. /**
  3472. * @override
  3473. */
  3474. this.className = "Enum";
  3475. /**
  3476. * Runtime enum object.
  3477. * @type {Object.<string,number>|null}
  3478. * @expose
  3479. */
  3480. this.object = null;
  3481. };
  3482. /**
  3483. * Gets the string name of an enum value.
  3484. * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
  3485. * @param {number} value Enum value
  3486. * @returns {?string} Name or `null` if not present
  3487. * @expose
  3488. */
  3489. Enum.getName = function(enm, value) {
  3490. var keys = Object.keys(enm);
  3491. for (var i=0, key; i<keys.length; ++i)
  3492. if (enm[key = keys[i]] === value)
  3493. return key;
  3494. return null;
  3495. };
  3496. /**
  3497. * @alias ProtoBuf.Reflect.Enum.prototype
  3498. * @inner
  3499. */
  3500. var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
  3501. /**
  3502. * Builds this enum and returns the runtime counterpart.
  3503. * @param {boolean} rebuild Whether to rebuild or not, defaults to false
  3504. * @returns {!Object.<string,number>}
  3505. * @expose
  3506. */
  3507. EnumPrototype.build = function(rebuild) {
  3508. if (this.object && !rebuild)
  3509. return this.object;
  3510. var enm = new ProtoBuf.Builder.Enum(),
  3511. values = this.getChildren(Enum.Value);
  3512. for (var i=0, k=values.length; i<k; ++i)
  3513. enm[values[i]['name']] = values[i]['id'];
  3514. if (Object.defineProperty)
  3515. Object.defineProperty(enm, '$options', {
  3516. "value": this.buildOpt(),
  3517. "enumerable": false
  3518. });
  3519. return this.object = enm;
  3520. };
  3521. /**
  3522. * @alias ProtoBuf.Reflect.Enum
  3523. * @expose
  3524. */
  3525. Reflect.Enum = Enum;
  3526. /**
  3527. * Constructs a new Enum Value.
  3528. * @exports ProtoBuf.Reflect.Enum.Value
  3529. * @param {!ProtoBuf.Builder} builder Builder reference
  3530. * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
  3531. * @param {string} name Field name
  3532. * @param {number} id Unique field id
  3533. * @constructor
  3534. * @extends ProtoBuf.Reflect.T
  3535. */
  3536. var Value = function(builder, enm, name, id) {
  3537. T.call(this, builder, enm, name);
  3538. /**
  3539. * @override
  3540. */
  3541. this.className = "Enum.Value";
  3542. /**
  3543. * Unique enum value id.
  3544. * @type {number}
  3545. * @expose
  3546. */
  3547. this.id = id;
  3548. };
  3549. // Extends T
  3550. Value.prototype = Object.create(T.prototype);
  3551. /**
  3552. * @alias ProtoBuf.Reflect.Enum.Value
  3553. * @expose
  3554. */
  3555. Reflect.Enum.Value = Value;
  3556. /**
  3557. * An extension (field).
  3558. * @exports ProtoBuf.Reflect.Extension
  3559. * @constructor
  3560. * @param {!ProtoBuf.Builder} builder Builder reference
  3561. * @param {!ProtoBuf.Reflect.T} parent Parent object
  3562. * @param {string} name Object name
  3563. * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
  3564. */
  3565. var Extension = function(builder, parent, name, field) {
  3566. T.call(this, builder, parent, name);
  3567. /**
  3568. * Extended message field.
  3569. * @type {!ProtoBuf.Reflect.Message.Field}
  3570. * @expose
  3571. */
  3572. this.field = field;
  3573. };
  3574. // Extends T
  3575. Extension.prototype = Object.create(T.prototype);
  3576. /**
  3577. * @alias ProtoBuf.Reflect.Extension
  3578. * @expose
  3579. */
  3580. Reflect.Extension = Extension;
  3581. /**
  3582. * Constructs a new Service.
  3583. * @exports ProtoBuf.Reflect.Service
  3584. * @param {!ProtoBuf.Builder} builder Builder reference
  3585. * @param {!ProtoBuf.Reflect.Namespace} root Root
  3586. * @param {string} name Service name
  3587. * @param {Object.<string,*>=} options Options
  3588. * @constructor
  3589. * @extends ProtoBuf.Reflect.Namespace
  3590. */
  3591. var Service = function(builder, root, name, options) {
  3592. Namespace.call(this, builder, root, name, options);
  3593. /**
  3594. * @override
  3595. */
  3596. this.className = "Service";
  3597. /**
  3598. * Built runtime service class.
  3599. * @type {?function(new:ProtoBuf.Builder.Service)}
  3600. */
  3601. this.clazz = null;
  3602. };
  3603. /**
  3604. * @alias ProtoBuf.Reflect.Service.prototype
  3605. * @inner
  3606. */
  3607. var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
  3608. /**
  3609. * Builds the service and returns the runtime counterpart, which is a fully functional class.
  3610. * @see ProtoBuf.Builder.Service
  3611. * @param {boolean=} rebuild Whether to rebuild or not
  3612. * @return {Function} Service class
  3613. * @throws {Error} If the message cannot be built
  3614. * @expose
  3615. */
  3616. ServicePrototype.build = function(rebuild) {
  3617. if (this.clazz && !rebuild)
  3618. return this.clazz;
  3619. // Create the runtime Service class in its own scope
  3620. return this.clazz = (function(ProtoBuf, T) {
  3621. /**
  3622. * Constructs a new runtime Service.
  3623. * @name ProtoBuf.Builder.Service
  3624. * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
  3625. * @class Barebone of all runtime services.
  3626. * @constructor
  3627. * @throws {Error} If the service cannot be created
  3628. */
  3629. var Service = function(rpcImpl) {
  3630. ProtoBuf.Builder.Service.call(this);
  3631. /**
  3632. * Service implementation.
  3633. * @name ProtoBuf.Builder.Service#rpcImpl
  3634. * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
  3635. * @expose
  3636. */
  3637. this.rpcImpl = rpcImpl || function(name, msg, callback) {
  3638. // This is what a user has to implement: A function receiving the method name, the actual message to
  3639. // send (type checked) and the callback that's either provided with the error as its first
  3640. // argument or null and the actual response message.
  3641. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
  3642. };
  3643. };
  3644. /**
  3645. * @alias ProtoBuf.Builder.Service.prototype
  3646. * @inner
  3647. */
  3648. var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
  3649. /**
  3650. * Asynchronously performs an RPC call using the given RPC implementation.
  3651. * @name ProtoBuf.Builder.Service.[Method]
  3652. * @function
  3653. * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
  3654. * @param {ProtoBuf.Builder.Message} req Request
  3655. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  3656. * the error if any and the response either as a pre-parsed message or as its raw bytes
  3657. * @abstract
  3658. */
  3659. /**
  3660. * Asynchronously performs an RPC call using the instance's RPC implementation.
  3661. * @name ProtoBuf.Builder.Service#[Method]
  3662. * @function
  3663. * @param {ProtoBuf.Builder.Message} req Request
  3664. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  3665. * the error if any and the response either as a pre-parsed message or as its raw bytes
  3666. * @abstract
  3667. */
  3668. var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
  3669. for (var i=0; i<rpc.length; i++) {
  3670. (function(method) {
  3671. // service#Method(message, callback)
  3672. ServicePrototype[method.name] = function(req, callback) {
  3673. try {
  3674. try {
  3675. // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
  3676. req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
  3677. } catch (err) {
  3678. if (!(err instanceof TypeError))
  3679. throw err;
  3680. }
  3681. if (req === null || typeof req !== 'object')
  3682. throw Error("Illegal arguments");
  3683. if (!(req instanceof method.resolvedRequestType.clazz))
  3684. req = new method.resolvedRequestType.clazz(req);
  3685. this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
  3686. if (err) {
  3687. callback(err);
  3688. return;
  3689. }
  3690. // Coalesce to empty string when service response has empty content
  3691. if (res === null)
  3692. res = ''
  3693. try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
  3694. if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
  3695. callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
  3696. return;
  3697. }
  3698. callback(null, res);
  3699. });
  3700. } catch (err) {
  3701. setTimeout(callback.bind(this, err), 0);
  3702. }
  3703. };
  3704. // Service.Method(rpcImpl, message, callback)
  3705. Service[method.name] = function(rpcImpl, req, callback) {
  3706. new Service(rpcImpl)[method.name](req, callback);
  3707. };
  3708. if (Object.defineProperty)
  3709. Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
  3710. Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
  3711. })(rpc[i]);
  3712. }
  3713. // Properties
  3714. /**
  3715. * Service options.
  3716. * @name ProtoBuf.Builder.Service.$options
  3717. * @type {Object.<string,*>}
  3718. * @expose
  3719. */
  3720. var $optionsS; // cc needs this
  3721. /**
  3722. * Service options.
  3723. * @name ProtoBuf.Builder.Service#$options
  3724. * @type {Object.<string,*>}
  3725. * @expose
  3726. */
  3727. var $options;
  3728. /**
  3729. * Reflection type.
  3730. * @name ProtoBuf.Builder.Service.$type
  3731. * @type {!ProtoBuf.Reflect.Service}
  3732. * @expose
  3733. */
  3734. var $typeS;
  3735. /**
  3736. * Reflection type.
  3737. * @name ProtoBuf.Builder.Service#$type
  3738. * @type {!ProtoBuf.Reflect.Service}
  3739. * @expose
  3740. */
  3741. var $type;
  3742. if (Object.defineProperty)
  3743. Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
  3744. Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
  3745. Object.defineProperty(Service, "$type", { "value": T }),
  3746. Object.defineProperty(ServicePrototype, "$type", { "value": T });
  3747. return Service;
  3748. })(ProtoBuf, this);
  3749. };
  3750. /**
  3751. * @alias ProtoBuf.Reflect.Service
  3752. * @expose
  3753. */
  3754. Reflect.Service = Service;
  3755. /**
  3756. * Abstract service method.
  3757. * @exports ProtoBuf.Reflect.Service.Method
  3758. * @param {!ProtoBuf.Builder} builder Builder reference
  3759. * @param {!ProtoBuf.Reflect.Service} svc Service
  3760. * @param {string} name Method name
  3761. * @param {Object.<string,*>=} options Options
  3762. * @constructor
  3763. * @extends ProtoBuf.Reflect.T
  3764. */
  3765. var Method = function(builder, svc, name, options) {
  3766. T.call(this, builder, svc, name);
  3767. /**
  3768. * @override
  3769. */
  3770. this.className = "Service.Method";
  3771. /**
  3772. * Options.
  3773. * @type {Object.<string, *>}
  3774. * @expose
  3775. */
  3776. this.options = options || {};
  3777. };
  3778. /**
  3779. * @alias ProtoBuf.Reflect.Service.Method.prototype
  3780. * @inner
  3781. */
  3782. var MethodPrototype = Method.prototype = Object.create(T.prototype);
  3783. /**
  3784. * Builds the method's '$options' property.
  3785. * @name ProtoBuf.Reflect.Service.Method#buildOpt
  3786. * @function
  3787. * @return {Object.<string,*>}
  3788. */
  3789. MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
  3790. /**
  3791. * @alias ProtoBuf.Reflect.Service.Method
  3792. * @expose
  3793. */
  3794. Reflect.Service.Method = Method;
  3795. /**
  3796. * RPC service method.
  3797. * @exports ProtoBuf.Reflect.Service.RPCMethod
  3798. * @param {!ProtoBuf.Builder} builder Builder reference
  3799. * @param {!ProtoBuf.Reflect.Service} svc Service
  3800. * @param {string} name Method name
  3801. * @param {string} request Request message name
  3802. * @param {string} response Response message name
  3803. * @param {boolean} request_stream Whether requests are streamed
  3804. * @param {boolean} response_stream Whether responses are streamed
  3805. * @param {Object.<string,*>=} options Options
  3806. * @constructor
  3807. * @extends ProtoBuf.Reflect.Service.Method
  3808. */
  3809. var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
  3810. Method.call(this, builder, svc, name, options);
  3811. /**
  3812. * @override
  3813. */
  3814. this.className = "Service.RPCMethod";
  3815. /**
  3816. * Request message name.
  3817. * @type {string}
  3818. * @expose
  3819. */
  3820. this.requestName = request;
  3821. /**
  3822. * Response message name.
  3823. * @type {string}
  3824. * @expose
  3825. */
  3826. this.responseName = response;
  3827. /**
  3828. * Whether requests are streamed
  3829. * @type {bool}
  3830. * @expose
  3831. */
  3832. this.requestStream = request_stream;
  3833. /**
  3834. * Whether responses are streamed
  3835. * @type {bool}
  3836. * @expose
  3837. */
  3838. this.responseStream = response_stream;
  3839. /**
  3840. * Resolved request message type.
  3841. * @type {ProtoBuf.Reflect.Message}
  3842. * @expose
  3843. */
  3844. this.resolvedRequestType = null;
  3845. /**
  3846. * Resolved response message type.
  3847. * @type {ProtoBuf.Reflect.Message}
  3848. * @expose
  3849. */
  3850. this.resolvedResponseType = null;
  3851. };
  3852. // Extends Method
  3853. RPCMethod.prototype = Object.create(Method.prototype);
  3854. /**
  3855. * @alias ProtoBuf.Reflect.Service.RPCMethod
  3856. * @expose
  3857. */
  3858. Reflect.Service.RPCMethod = RPCMethod;
  3859. return Reflect;
  3860. })(ProtoBuf);
  3861. /**
  3862. * @alias ProtoBuf.Builder
  3863. * @expose
  3864. */
  3865. ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
  3866. "use strict";
  3867. /**
  3868. * Constructs a new Builder.
  3869. * @exports ProtoBuf.Builder
  3870. * @class Provides the functionality to build protocol messages.
  3871. * @param {Object.<string,*>=} options Options
  3872. * @constructor
  3873. */
  3874. var Builder = function(options) {
  3875. /**
  3876. * Namespace.
  3877. * @type {ProtoBuf.Reflect.Namespace}
  3878. * @expose
  3879. */
  3880. this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
  3881. /**
  3882. * Namespace pointer.
  3883. * @type {ProtoBuf.Reflect.T}
  3884. * @expose
  3885. */
  3886. this.ptr = this.ns;
  3887. /**
  3888. * Resolved flag.
  3889. * @type {boolean}
  3890. * @expose
  3891. */
  3892. this.resolved = false;
  3893. /**
  3894. * The current building result.
  3895. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
  3896. * @expose
  3897. */
  3898. this.result = null;
  3899. /**
  3900. * Imported files.
  3901. * @type {Array.<string>}
  3902. * @expose
  3903. */
  3904. this.files = {};
  3905. /**
  3906. * Import root override.
  3907. * @type {?string}
  3908. * @expose
  3909. */
  3910. this.importRoot = null;
  3911. /**
  3912. * Options.
  3913. * @type {!Object.<string, *>}
  3914. * @expose
  3915. */
  3916. this.options = options || {};
  3917. };
  3918. /**
  3919. * @alias ProtoBuf.Builder.prototype
  3920. * @inner
  3921. */
  3922. var BuilderPrototype = Builder.prototype;
  3923. // ----- Definition tests -----
  3924. /**
  3925. * Tests if a definition most likely describes a message.
  3926. * @param {!Object} def
  3927. * @returns {boolean}
  3928. * @expose
  3929. */
  3930. Builder.isMessage = function(def) {
  3931. // Messages require a string name
  3932. if (typeof def["name"] !== 'string')
  3933. return false;
  3934. // Messages do not contain values (enum) or rpc methods (service)
  3935. if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
  3936. return false;
  3937. return true;
  3938. };
  3939. /**
  3940. * Tests if a definition most likely describes a message field.
  3941. * @param {!Object} def
  3942. * @returns {boolean}
  3943. * @expose
  3944. */
  3945. Builder.isMessageField = function(def) {
  3946. // Message fields require a string rule, name and type and an id
  3947. if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
  3948. return false;
  3949. return true;
  3950. };
  3951. /**
  3952. * Tests if a definition most likely describes an enum.
  3953. * @param {!Object} def
  3954. * @returns {boolean}
  3955. * @expose
  3956. */
  3957. Builder.isEnum = function(def) {
  3958. // Enums require a string name
  3959. if (typeof def["name"] !== 'string')
  3960. return false;
  3961. // Enums require at least one value
  3962. if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
  3963. return false;
  3964. return true;
  3965. };
  3966. /**
  3967. * Tests if a definition most likely describes a service.
  3968. * @param {!Object} def
  3969. * @returns {boolean}
  3970. * @expose
  3971. */
  3972. Builder.isService = function(def) {
  3973. // Services require a string name and an rpc object
  3974. if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
  3975. return false;
  3976. return true;
  3977. };
  3978. /**
  3979. * Tests if a definition most likely describes an extended message
  3980. * @param {!Object} def
  3981. * @returns {boolean}
  3982. * @expose
  3983. */
  3984. Builder.isExtend = function(def) {
  3985. // Extends rquire a string ref
  3986. if (typeof def["ref"] !== 'string')
  3987. return false;
  3988. return true;
  3989. };
  3990. // ----- Building -----
  3991. /**
  3992. * Resets the pointer to the root namespace.
  3993. * @returns {!ProtoBuf.Builder} this
  3994. * @expose
  3995. */
  3996. BuilderPrototype.reset = function() {
  3997. this.ptr = this.ns;
  3998. return this;
  3999. };
  4000. /**
  4001. * Defines a namespace on top of the current pointer position and places the pointer on it.
  4002. * @param {string} namespace
  4003. * @return {!ProtoBuf.Builder} this
  4004. * @expose
  4005. */
  4006. BuilderPrototype.define = function(namespace) {
  4007. if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
  4008. throw Error("illegal namespace: "+namespace);
  4009. namespace.split(".").forEach(function(part) {
  4010. var ns = this.ptr.getChild(part);
  4011. if (ns === null) // Keep existing
  4012. this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
  4013. this.ptr = ns;
  4014. }, this);
  4015. return this;
  4016. };
  4017. /**
  4018. * Creates the specified definitions at the current pointer position.
  4019. * @param {!Array.<!Object>} defs Messages, enums or services to create
  4020. * @returns {!ProtoBuf.Builder} this
  4021. * @throws {Error} If a message definition is invalid
  4022. * @expose
  4023. */
  4024. BuilderPrototype.create = function(defs) {
  4025. if (!defs)
  4026. return this; // Nothing to create
  4027. if (!Array.isArray(defs))
  4028. defs = [defs];
  4029. else {
  4030. if (defs.length === 0)
  4031. return this;
  4032. defs = defs.slice();
  4033. }
  4034. // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
  4035. var stack = [defs];
  4036. while (stack.length > 0) {
  4037. defs = stack.pop();
  4038. if (!Array.isArray(defs)) // Stack always contains entire namespaces
  4039. throw Error("not a valid namespace: "+JSON.stringify(defs));
  4040. while (defs.length > 0) {
  4041. var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
  4042. if (Builder.isMessage(def)) {
  4043. var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
  4044. // Create OneOfs
  4045. var oneofs = {};
  4046. if (def["oneofs"])
  4047. Object.keys(def["oneofs"]).forEach(function(name) {
  4048. obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
  4049. }, this);
  4050. // Create fields
  4051. if (def["fields"])
  4052. def["fields"].forEach(function(fld) {
  4053. if (obj.getChild(fld["id"]|0) !== null)
  4054. throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
  4055. if (fld["options"] && typeof fld["options"] !== 'object')
  4056. throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
  4057. var oneof = null;
  4058. if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
  4059. throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
  4060. fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
  4061. if (oneof)
  4062. oneof.fields.push(fld);
  4063. obj.addChild(fld);
  4064. }, this);
  4065. // Push children to stack
  4066. var subObj = [];
  4067. if (def["enums"])
  4068. def["enums"].forEach(function(enm) {
  4069. subObj.push(enm);
  4070. });
  4071. if (def["messages"])
  4072. def["messages"].forEach(function(msg) {
  4073. subObj.push(msg);
  4074. });
  4075. if (def["services"])
  4076. def["services"].forEach(function(svc) {
  4077. subObj.push(svc);
  4078. });
  4079. // Set extension ranges
  4080. if (def["extensions"]) {
  4081. if (typeof def["extensions"][0] === 'number') // pre 5.0.1
  4082. obj.extensions = [ def["extensions"] ];
  4083. else
  4084. obj.extensions = def["extensions"];
  4085. }
  4086. // Create on top of current namespace
  4087. this.ptr.addChild(obj);
  4088. if (subObj.length > 0) {
  4089. stack.push(defs); // Push the current level back
  4090. defs = subObj; // Continue processing sub level
  4091. subObj = null;
  4092. this.ptr = obj; // And move the pointer to this namespace
  4093. obj = null;
  4094. continue;
  4095. }
  4096. subObj = null;
  4097. } else if (Builder.isEnum(def)) {
  4098. obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
  4099. def["values"].forEach(function(val) {
  4100. obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
  4101. }, this);
  4102. this.ptr.addChild(obj);
  4103. } else if (Builder.isService(def)) {
  4104. obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
  4105. Object.keys(def["rpc"]).forEach(function(name) {
  4106. var mtd = def["rpc"][name];
  4107. obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
  4108. }, this);
  4109. this.ptr.addChild(obj);
  4110. } else if (Builder.isExtend(def)) {
  4111. obj = this.ptr.resolve(def["ref"], true);
  4112. if (obj) {
  4113. def["fields"].forEach(function(fld) {
  4114. if (obj.getChild(fld['id']|0) !== null)
  4115. throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
  4116. // Check if field id is allowed to be extended
  4117. if (obj.extensions) {
  4118. var valid = false;
  4119. obj.extensions.forEach(function(range) {
  4120. if (fld["id"] >= range[0] && fld["id"] <= range[1])
  4121. valid = true;
  4122. });
  4123. if (!valid)
  4124. throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
  4125. }
  4126. // Convert extension field names to camel case notation if the override is set
  4127. var name = fld["name"];
  4128. if (this.options['convertFieldsToCamelCase'])
  4129. name = ProtoBuf.Util.toCamelCase(name);
  4130. // see #161: Extensions use their fully qualified name as their runtime key and...
  4131. var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
  4132. // ...are added on top of the current namespace as an extension which is used for
  4133. // resolving their type later on (the extension always keeps the original name to
  4134. // prevent naming collisions)
  4135. var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
  4136. field.extension = ext;
  4137. this.ptr.addChild(ext);
  4138. obj.addChild(field);
  4139. }, this);
  4140. } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
  4141. throw Error("extended message "+def["ref"]+" is not defined");
  4142. } else
  4143. throw Error("not a valid definition: "+JSON.stringify(def));
  4144. def = null;
  4145. obj = null;
  4146. }
  4147. // Break goes here
  4148. defs = null;
  4149. this.ptr = this.ptr.parent; // Namespace done, continue at parent
  4150. }
  4151. this.resolved = false; // Require re-resolve
  4152. this.result = null; // Require re-build
  4153. return this;
  4154. };
  4155. /**
  4156. * Propagates syntax to all children.
  4157. * @param {!Object} parent
  4158. * @inner
  4159. */
  4160. function propagateSyntax(parent) {
  4161. if (parent['messages']) {
  4162. parent['messages'].forEach(function(child) {
  4163. child["syntax"] = parent["syntax"];
  4164. propagateSyntax(child);
  4165. });
  4166. }
  4167. if (parent['enums']) {
  4168. parent['enums'].forEach(function(child) {
  4169. child["syntax"] = parent["syntax"];
  4170. });
  4171. }
  4172. }
  4173. /**
  4174. * Imports another definition into this builder.
  4175. * @param {Object.<string,*>} json Parsed import
  4176. * @param {(string|{root: string, file: string})=} filename Imported file name
  4177. * @returns {!ProtoBuf.Builder} this
  4178. * @throws {Error} If the definition or file cannot be imported
  4179. * @expose
  4180. */
  4181. BuilderPrototype["import"] = function(json, filename) {
  4182. var delim = '/';
  4183. // Make sure to skip duplicate imports
  4184. if (typeof filename === 'string') {
  4185. if (ProtoBuf.Util.IS_NODE)
  4186. filename = require("path")['resolve'](filename);
  4187. if (this.files[filename] === true)
  4188. return this.reset();
  4189. this.files[filename] = true;
  4190. } else if (typeof filename === 'object') { // Object with root, file.
  4191. var root = filename.root;
  4192. if (ProtoBuf.Util.IS_NODE)
  4193. root = require("path")['resolve'](root);
  4194. if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
  4195. delim = '\\';
  4196. var fname = root + delim + filename.file;
  4197. if (this.files[fname] === true)
  4198. return this.reset();
  4199. this.files[fname] = true;
  4200. }
  4201. // Import imports
  4202. if (json['imports'] && json['imports'].length > 0) {
  4203. var importRoot,
  4204. resetRoot = false;
  4205. if (typeof filename === 'object') { // If an import root is specified, override
  4206. this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
  4207. importRoot = this.importRoot;
  4208. filename = filename["file"];
  4209. if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
  4210. delim = '\\';
  4211. } else if (typeof filename === 'string') {
  4212. if (this.importRoot) // If import root is overridden, use it
  4213. importRoot = this.importRoot;
  4214. else { // Otherwise compute from filename
  4215. if (filename.indexOf("/") >= 0) { // Unix
  4216. importRoot = filename.replace(/\/[^\/]*$/, "");
  4217. if (/* /file.proto */ importRoot === "")
  4218. importRoot = "/";
  4219. } else if (filename.indexOf("\\") >= 0) { // Windows
  4220. importRoot = filename.replace(/\\[^\\]*$/, "");
  4221. delim = '\\';
  4222. } else
  4223. importRoot = ".";
  4224. }
  4225. } else
  4226. importRoot = null;
  4227. for (var i=0; i<json['imports'].length; i++) {
  4228. if (typeof json['imports'][i] === 'string') { // Import file
  4229. if (!importRoot)
  4230. throw Error("cannot determine import root");
  4231. var importFilename = json['imports'][i];
  4232. if (importFilename === "google/protobuf/descriptor.proto")
  4233. continue; // Not needed and therefore not used
  4234. importFilename = importRoot + delim + importFilename;
  4235. if (this.files[importFilename] === true)
  4236. continue; // Already imported
  4237. if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
  4238. importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
  4239. var contents = ProtoBuf.Util.fetch(importFilename);
  4240. if (contents === null)
  4241. throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
  4242. if (/\.json$/i.test(importFilename)) // Always possible
  4243. this["import"](JSON.parse(contents+""), importFilename); // May throw
  4244. else
  4245. this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
  4246. } else // Import structure
  4247. if (!filename)
  4248. this["import"](json['imports'][i]);
  4249. else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
  4250. this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
  4251. else // Without extension: Append _importN to make it unique
  4252. this["import"](json['imports'][i], filename+"_import"+i);
  4253. }
  4254. if (resetRoot) // Reset import root override when all imports are done
  4255. this.importRoot = null;
  4256. }
  4257. // Import structures
  4258. if (json['package'])
  4259. this.define(json['package']);
  4260. if (json['syntax'])
  4261. propagateSyntax(json);
  4262. var base = this.ptr;
  4263. if (json['options'])
  4264. Object.keys(json['options']).forEach(function(key) {
  4265. base.options[key] = json['options'][key];
  4266. });
  4267. if (json['messages'])
  4268. this.create(json['messages']),
  4269. this.ptr = base;
  4270. if (json['enums'])
  4271. this.create(json['enums']),
  4272. this.ptr = base;
  4273. if (json['services'])
  4274. this.create(json['services']),
  4275. this.ptr = base;
  4276. if (json['extends'])
  4277. this.create(json['extends']);
  4278. return this.reset();
  4279. };
  4280. /**
  4281. * Resolves all namespace objects.
  4282. * @throws {Error} If a type cannot be resolved
  4283. * @returns {!ProtoBuf.Builder} this
  4284. * @expose
  4285. */
  4286. BuilderPrototype.resolveAll = function() {
  4287. // Resolve all reflected objects
  4288. var res;
  4289. if (this.ptr == null || typeof this.ptr.type === 'object')
  4290. return this; // Done (already resolved)
  4291. if (this.ptr instanceof Reflect.Namespace) { // Resolve children
  4292. this.ptr.children.forEach(function(child) {
  4293. this.ptr = child;
  4294. this.resolveAll();
  4295. }, this);
  4296. } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
  4297. if (!Lang.TYPE.test(this.ptr.type)) {
  4298. if (!Lang.TYPEREF.test(this.ptr.type))
  4299. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4300. res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
  4301. if (!res)
  4302. throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4303. this.ptr.resolvedType = res;
  4304. if (res instanceof Reflect.Enum) {
  4305. this.ptr.type = ProtoBuf.TYPES["enum"];
  4306. if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
  4307. throw Error("proto3 message cannot reference proto2 enum");
  4308. }
  4309. else if (res instanceof Reflect.Message)
  4310. this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
  4311. else
  4312. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4313. } else
  4314. this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
  4315. // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
  4316. // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
  4317. if (this.ptr.map) {
  4318. if (!Lang.TYPE.test(this.ptr.keyType))
  4319. throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
  4320. this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
  4321. }
  4322. } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
  4323. if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
  4324. res = this.ptr.parent.resolve(this.ptr.requestName, true);
  4325. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  4326. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
  4327. this.ptr.resolvedRequestType = res;
  4328. res = this.ptr.parent.resolve(this.ptr.responseName, true);
  4329. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  4330. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
  4331. this.ptr.resolvedResponseType = res;
  4332. } else // Should not happen as nothing else is implemented
  4333. throw Error("illegal service type in "+this.ptr.toString(true));
  4334. } else if (
  4335. !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
  4336. !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
  4337. !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
  4338. )
  4339. throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
  4340. return this.reset();
  4341. };
  4342. /**
  4343. * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
  4344. * return the built package.
  4345. * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
  4346. * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
  4347. * @throws {Error} If a type could not be resolved
  4348. * @expose
  4349. */
  4350. BuilderPrototype.build = function(path) {
  4351. this.reset();
  4352. if (!this.resolved)
  4353. this.resolveAll(),
  4354. this.resolved = true,
  4355. this.result = null; // Require re-build
  4356. if (this.result === null) // (Re-)Build
  4357. this.result = this.ns.build();
  4358. if (!path)
  4359. return this.result;
  4360. var part = typeof path === 'string' ? path.split(".") : path,
  4361. ptr = this.result; // Build namespace pointer (no hasChild etc.)
  4362. for (var i=0; i<part.length; i++)
  4363. if (ptr[part[i]])
  4364. ptr = ptr[part[i]];
  4365. else {
  4366. ptr = null;
  4367. break;
  4368. }
  4369. return ptr;
  4370. };
  4371. /**
  4372. * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
  4373. * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
  4374. * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
  4375. * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
  4376. */
  4377. BuilderPrototype.lookup = function(path, excludeNonNamespace) {
  4378. return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
  4379. };
  4380. /**
  4381. * Returns a string representation of this object.
  4382. * @return {string} String representation as of "Builder"
  4383. * @expose
  4384. */
  4385. BuilderPrototype.toString = function() {
  4386. return "Builder";
  4387. };
  4388. // ----- Base classes -----
  4389. // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
  4390. /**
  4391. * @alias ProtoBuf.Builder.Message
  4392. */
  4393. Builder.Message = function() {};
  4394. /**
  4395. * @alias ProtoBuf.Builder.Enum
  4396. */
  4397. Builder.Enum = function() {};
  4398. /**
  4399. * @alias ProtoBuf.Builder.Message
  4400. */
  4401. Builder.Service = function() {};
  4402. return Builder;
  4403. })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
  4404. /**
  4405. * @alias ProtoBuf.Map
  4406. * @expose
  4407. */
  4408. ProtoBuf.Map = (function(ProtoBuf, Reflect) {
  4409. "use strict";
  4410. /**
  4411. * Constructs a new Map. A Map is a container that is used to implement map
  4412. * fields on message objects. It closely follows the ES6 Map API; however,
  4413. * it is distinct because we do not want to depend on external polyfills or
  4414. * on ES6 itself.
  4415. *
  4416. * @exports ProtoBuf.Map
  4417. * @param {!ProtoBuf.Reflect.Field} field Map field
  4418. * @param {Object.<string,*>=} contents Initial contents
  4419. * @constructor
  4420. */
  4421. var Map = function(field, contents) {
  4422. if (!field.map)
  4423. throw Error("field is not a map");
  4424. /**
  4425. * The field corresponding to this map.
  4426. * @type {!ProtoBuf.Reflect.Field}
  4427. */
  4428. this.field = field;
  4429. /**
  4430. * Element instance corresponding to key type.
  4431. * @type {!ProtoBuf.Reflect.Element}
  4432. */
  4433. this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
  4434. /**
  4435. * Element instance corresponding to value type.
  4436. * @type {!ProtoBuf.Reflect.Element}
  4437. */
  4438. this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
  4439. /**
  4440. * Internal map: stores mapping of (string form of key) -> (key, value)
  4441. * pair.
  4442. *
  4443. * We provide map semantics for arbitrary key types, but we build on top
  4444. * of an Object, which has only string keys. In order to avoid the need
  4445. * to convert a string key back to its native type in many situations,
  4446. * we store the native key value alongside the value. Thus, we only need
  4447. * a one-way mapping from a key type to its string form that guarantees
  4448. * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
  4449. * === K2).
  4450. *
  4451. * @type {!Object<string, {key: *, value: *}>}
  4452. */
  4453. this.map = {};
  4454. /**
  4455. * Returns the number of elements in the map.
  4456. */
  4457. Object.defineProperty(this, "size", {
  4458. get: function() { return Object.keys(this.map).length; }
  4459. });
  4460. // Fill initial contents from a raw object.
  4461. if (contents) {
  4462. var keys = Object.keys(contents);
  4463. for (var i = 0; i < keys.length; i++) {
  4464. var key = this.keyElem.valueFromString(keys[i]);
  4465. var val = this.valueElem.verifyValue(contents[keys[i]]);
  4466. this.map[this.keyElem.valueToString(key)] =
  4467. { key: key, value: val };
  4468. }
  4469. }
  4470. };
  4471. var MapPrototype = Map.prototype;
  4472. /**
  4473. * Helper: return an iterator over an array.
  4474. * @param {!Array<*>} arr the array
  4475. * @returns {!Object} an iterator
  4476. * @inner
  4477. */
  4478. function arrayIterator(arr) {
  4479. var idx = 0;
  4480. return {
  4481. next: function() {
  4482. if (idx < arr.length)
  4483. return { done: false, value: arr[idx++] };
  4484. return { done: true };
  4485. }
  4486. }
  4487. }
  4488. /**
  4489. * Clears the map.
  4490. */
  4491. MapPrototype.clear = function() {
  4492. this.map = {};
  4493. };
  4494. /**
  4495. * Deletes a particular key from the map.
  4496. * @returns {boolean} Whether any entry with this key was deleted.
  4497. */
  4498. MapPrototype["delete"] = function(key) {
  4499. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4500. var hadKey = keyValue in this.map;
  4501. delete this.map[keyValue];
  4502. return hadKey;
  4503. };
  4504. /**
  4505. * Returns an iterator over [key, value] pairs in the map.
  4506. * @returns {Object} The iterator
  4507. */
  4508. MapPrototype.entries = function() {
  4509. var entries = [];
  4510. var strKeys = Object.keys(this.map);
  4511. for (var i = 0, entry; i < strKeys.length; i++)
  4512. entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
  4513. return arrayIterator(entries);
  4514. };
  4515. /**
  4516. * Returns an iterator over keys in the map.
  4517. * @returns {Object} The iterator
  4518. */
  4519. MapPrototype.keys = function() {
  4520. var keys = [];
  4521. var strKeys = Object.keys(this.map);
  4522. for (var i = 0; i < strKeys.length; i++)
  4523. keys.push(this.map[strKeys[i]].key);
  4524. return arrayIterator(keys);
  4525. };
  4526. /**
  4527. * Returns an iterator over values in the map.
  4528. * @returns {!Object} The iterator
  4529. */
  4530. MapPrototype.values = function() {
  4531. var values = [];
  4532. var strKeys = Object.keys(this.map);
  4533. for (var i = 0; i < strKeys.length; i++)
  4534. values.push(this.map[strKeys[i]].value);
  4535. return arrayIterator(values);
  4536. };
  4537. /**
  4538. * Iterates over entries in the map, calling a function on each.
  4539. * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
  4540. * @param {Object=} thisArg The `this` value for the callback
  4541. */
  4542. MapPrototype.forEach = function(cb, thisArg) {
  4543. var strKeys = Object.keys(this.map);
  4544. for (var i = 0, entry; i < strKeys.length; i++)
  4545. cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
  4546. };
  4547. /**
  4548. * Sets a key in the map to the given value.
  4549. * @param {*} key The key
  4550. * @param {*} value The value
  4551. * @returns {!ProtoBuf.Map} The map instance
  4552. */
  4553. MapPrototype.set = function(key, value) {
  4554. var keyValue = this.keyElem.verifyValue(key);
  4555. var valValue = this.valueElem.verifyValue(value);
  4556. this.map[this.keyElem.valueToString(keyValue)] =
  4557. { key: keyValue, value: valValue };
  4558. return this;
  4559. };
  4560. /**
  4561. * Gets the value corresponding to a key in the map.
  4562. * @param {*} key The key
  4563. * @returns {*|undefined} The value, or `undefined` if key not present
  4564. */
  4565. MapPrototype.get = function(key) {
  4566. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4567. if (!(keyValue in this.map))
  4568. return undefined;
  4569. return this.map[keyValue].value;
  4570. };
  4571. /**
  4572. * Determines whether the given key is present in the map.
  4573. * @param {*} key The key
  4574. * @returns {boolean} `true` if the key is present
  4575. */
  4576. MapPrototype.has = function(key) {
  4577. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4578. return (keyValue in this.map);
  4579. };
  4580. return Map;
  4581. })(ProtoBuf, ProtoBuf.Reflect);
  4582. /**
  4583. * Loads a .proto string and returns the Builder.
  4584. * @param {string} proto .proto file contents
  4585. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  4586. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4587. * @return {ProtoBuf.Builder} Builder to create new messages
  4588. * @throws {Error} If the definition cannot be parsed or built
  4589. * @expose
  4590. */
  4591. ProtoBuf.loadProto = function(proto, builder, filename) {
  4592. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  4593. filename = builder,
  4594. builder = undefined;
  4595. return ProtoBuf.loadJson(ProtoBuf.DotProto.Parser.parse(proto), builder, filename);
  4596. };
  4597. /**
  4598. * Loads a .proto string and returns the Builder. This is an alias of {@link ProtoBuf.loadProto}.
  4599. * @function
  4600. * @param {string} proto .proto file contents
  4601. * @param {(ProtoBuf.Builder|string)=} builder Builder to append to. Will create a new one if omitted.
  4602. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4603. * @return {ProtoBuf.Builder} Builder to create new messages
  4604. * @throws {Error} If the definition cannot be parsed or built
  4605. * @expose
  4606. */
  4607. ProtoBuf.protoFromString = ProtoBuf.loadProto; // Legacy
  4608. /**
  4609. * Loads a .proto file and returns the Builder.
  4610. * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
  4611. * an overridden 'root' path for all imported files.
  4612. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4613. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4614. * file will be read synchronously and this function will return the Builder.
  4615. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4616. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4617. * request has failed), else undefined
  4618. * @expose
  4619. */
  4620. ProtoBuf.loadProtoFile = function(filename, callback, builder) {
  4621. if (callback && typeof callback === 'object')
  4622. builder = callback,
  4623. callback = null;
  4624. else if (!callback || typeof callback !== 'function')
  4625. callback = null;
  4626. if (callback)
  4627. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  4628. if (contents === null) {
  4629. callback(Error("Failed to fetch file"));
  4630. return;
  4631. }
  4632. try {
  4633. callback(null, ProtoBuf.loadProto(contents, builder, filename));
  4634. } catch (e) {
  4635. callback(e);
  4636. }
  4637. });
  4638. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  4639. return contents === null ? null : ProtoBuf.loadProto(contents, builder, filename);
  4640. };
  4641. /**
  4642. * Loads a .proto file and returns the Builder. This is an alias of {@link ProtoBuf.loadProtoFile}.
  4643. * @function
  4644. * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
  4645. * an overridden 'root' path for all imported files.
  4646. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4647. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4648. * file will be read synchronously and this function will return the Builder.
  4649. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4650. * @return {!ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4651. * request has failed), else undefined
  4652. * @expose
  4653. */
  4654. ProtoBuf.protoFromFile = ProtoBuf.loadProtoFile; // Legacy
  4655. /**
  4656. * Constructs a new empty Builder.
  4657. * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
  4658. * @return {!ProtoBuf.Builder} Builder
  4659. * @expose
  4660. */
  4661. ProtoBuf.newBuilder = function(options) {
  4662. options = options || {};
  4663. if (typeof options['convertFieldsToCamelCase'] === 'undefined')
  4664. options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
  4665. if (typeof options['populateAccessors'] === 'undefined')
  4666. options['populateAccessors'] = ProtoBuf.populateAccessors;
  4667. return new ProtoBuf.Builder(options);
  4668. };
  4669. /**
  4670. * Loads a .json definition and returns the Builder.
  4671. * @param {!*|string} json JSON definition
  4672. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  4673. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4674. * @return {ProtoBuf.Builder} Builder to create new messages
  4675. * @throws {Error} If the definition cannot be parsed or built
  4676. * @expose
  4677. */
  4678. ProtoBuf.loadJson = function(json, builder, filename) {
  4679. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  4680. filename = builder,
  4681. builder = null;
  4682. if (!builder || typeof builder !== 'object')
  4683. builder = ProtoBuf.newBuilder();
  4684. if (typeof json === 'string')
  4685. json = JSON.parse(json);
  4686. builder["import"](json, filename);
  4687. builder.resolveAll();
  4688. return builder;
  4689. };
  4690. /**
  4691. * Loads a .json file and returns the Builder.
  4692. * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
  4693. * an overridden 'root' path for all imported files.
  4694. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4695. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4696. * file will be read synchronously and this function will return the Builder.
  4697. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4698. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4699. * request has failed), else undefined
  4700. * @expose
  4701. */
  4702. ProtoBuf.loadJsonFile = function(filename, callback, builder) {
  4703. if (callback && typeof callback === 'object')
  4704. builder = callback,
  4705. callback = null;
  4706. else if (!callback || typeof callback !== 'function')
  4707. callback = null;
  4708. if (callback)
  4709. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  4710. if (contents === null) {
  4711. callback(Error("Failed to fetch file"));
  4712. return;
  4713. }
  4714. try {
  4715. callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
  4716. } catch (e) {
  4717. callback(e);
  4718. }
  4719. });
  4720. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  4721. return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
  4722. };
  4723. return ProtoBuf;
  4724. });