protobuf.js 208 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265
  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.3";
  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]*)(?:\.[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. if (msg.hasOwnProperty("extensions")) {
  1014. msg["extensions"] = msg["extensions"].concat(this._parseExtensionRanges())
  1015. } else {
  1016. msg["extensions"] = this._parseExtensionRanges();
  1017. }
  1018. else if (token === "reserved")
  1019. this._parseIgnored(); // TODO
  1020. else if (token === "extend")
  1021. this._parseExtend(msg);
  1022. else if (Lang.TYPEREF.test(token)) {
  1023. if (!this.proto3)
  1024. throw Error("illegal field rule: "+token);
  1025. this._parseMessageField(msg, "optional", token);
  1026. } else
  1027. throw Error("illegal message token: "+token);
  1028. }
  1029. this.tn.omit(";");
  1030. parent["messages"].push(msg);
  1031. return msg;
  1032. };
  1033. /**
  1034. * Parses an ignored statement.
  1035. * @private
  1036. */
  1037. ParserPrototype._parseIgnored = function() {
  1038. while (this.tn.peek() !== ';')
  1039. this.tn.next();
  1040. this.tn.skip(";");
  1041. };
  1042. /**
  1043. * Parses a message field.
  1044. * @param {!Object} msg Message definition
  1045. * @param {string} rule Field rule
  1046. * @param {string=} type Field type if already known (never known for maps)
  1047. * @returns {!Object} Field descriptor
  1048. * @private
  1049. */
  1050. ParserPrototype._parseMessageField = function(msg, rule, type) {
  1051. if (!Lang.RULE.test(rule))
  1052. throw Error("illegal message field rule: "+rule);
  1053. var fld = {
  1054. "rule": rule,
  1055. "type": "",
  1056. "name": "",
  1057. "options": {},
  1058. "id": 0
  1059. };
  1060. var token;
  1061. if (rule === "map") {
  1062. if (type)
  1063. throw Error("illegal type: " + type);
  1064. this.tn.skip('<');
  1065. token = this.tn.next();
  1066. if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
  1067. throw Error("illegal message field type: " + token);
  1068. fld["keytype"] = token;
  1069. this.tn.skip(',');
  1070. token = this.tn.next();
  1071. if (!Lang.TYPE.test(token) && !Lang.TYPEREF.test(token))
  1072. throw Error("illegal message field: " + token);
  1073. fld["type"] = token;
  1074. this.tn.skip('>');
  1075. token = this.tn.next();
  1076. if (!Lang.NAME.test(token))
  1077. throw Error("illegal message field name: " + token);
  1078. fld["name"] = token;
  1079. this.tn.skip("=");
  1080. fld["id"] = mkId(this.tn.next());
  1081. token = this.tn.peek();
  1082. if (token === '[')
  1083. this._parseFieldOptions(fld);
  1084. this.tn.skip(";");
  1085. } else {
  1086. type = typeof type !== 'undefined' ? type : this.tn.next();
  1087. if (type === "group") {
  1088. // "A [legacy] group simply combines a nested message type and a field into a single declaration. In your
  1089. // code, you can treat this message just as if it had a Result type field called result (the latter name is
  1090. // converted to lower-case so that it does not conflict with the former)."
  1091. var grp = this._parseMessage(msg, fld);
  1092. if (!/^[A-Z]/.test(grp["name"]))
  1093. throw Error('illegal group name: '+grp["name"]);
  1094. fld["type"] = grp["name"];
  1095. fld["name"] = grp["name"].toLowerCase();
  1096. this.tn.omit(";");
  1097. } else {
  1098. if (!Lang.TYPE.test(type) && !Lang.TYPEREF.test(type))
  1099. throw Error("illegal message field type: " + type);
  1100. fld["type"] = type;
  1101. token = this.tn.next();
  1102. if (!Lang.NAME.test(token))
  1103. throw Error("illegal message field name: " + token);
  1104. fld["name"] = token;
  1105. this.tn.skip("=");
  1106. fld["id"] = mkId(this.tn.next());
  1107. token = this.tn.peek();
  1108. if (token === "[")
  1109. this._parseFieldOptions(fld);
  1110. this.tn.skip(";");
  1111. }
  1112. }
  1113. msg["fields"].push(fld);
  1114. return fld;
  1115. };
  1116. /**
  1117. * Parses a message oneof.
  1118. * @param {!Object} msg Message definition
  1119. * @private
  1120. */
  1121. ParserPrototype._parseMessageOneOf = function(msg) {
  1122. var token = this.tn.next();
  1123. if (!Lang.NAME.test(token))
  1124. throw Error("illegal oneof name: "+token);
  1125. var name = token,
  1126. fld;
  1127. var fields = [];
  1128. this.tn.skip("{");
  1129. while ((token = this.tn.next()) !== "}") {
  1130. fld = this._parseMessageField(msg, "optional", token);
  1131. fld["oneof"] = name;
  1132. fields.push(fld["id"]);
  1133. }
  1134. this.tn.omit(";");
  1135. msg["oneofs"][name] = fields;
  1136. };
  1137. /**
  1138. * Parses a set of field option definitions.
  1139. * @param {!Object} fld Field definition
  1140. * @private
  1141. */
  1142. ParserPrototype._parseFieldOptions = function(fld) {
  1143. this.tn.skip("[");
  1144. var token,
  1145. first = true;
  1146. while ((token = this.tn.peek()) !== ']') {
  1147. if (!first)
  1148. this.tn.skip(",");
  1149. this._parseOption(fld, true);
  1150. first = false;
  1151. }
  1152. this.tn.next();
  1153. };
  1154. /**
  1155. * Parses an enum.
  1156. * @param {!Object} msg Message definition
  1157. * @private
  1158. */
  1159. ParserPrototype._parseEnum = function(msg) {
  1160. var enm = {
  1161. "name": "",
  1162. "values": [],
  1163. "options": {}
  1164. };
  1165. var token = this.tn.next();
  1166. if (!Lang.NAME.test(token))
  1167. throw Error("illegal name: "+token);
  1168. enm["name"] = token;
  1169. this.tn.skip("{");
  1170. while ((token = this.tn.next()) !== '}') {
  1171. if (token === "option")
  1172. this._parseOption(enm);
  1173. else {
  1174. if (!Lang.NAME.test(token))
  1175. throw Error("illegal name: "+token);
  1176. this.tn.skip("=");
  1177. var val = {
  1178. "name": token,
  1179. "id": mkId(this.tn.next(), true)
  1180. };
  1181. token = this.tn.peek();
  1182. if (token === "[")
  1183. this._parseFieldOptions({ "options": {} });
  1184. this.tn.skip(";");
  1185. enm["values"].push(val);
  1186. }
  1187. }
  1188. this.tn.omit(";");
  1189. msg["enums"].push(enm);
  1190. };
  1191. /**
  1192. * Parses extension / reserved ranges.
  1193. * @returns {!Array.<!Array.<number>>}
  1194. * @private
  1195. */
  1196. ParserPrototype._parseExtensionRanges = function() {
  1197. var ranges = [];
  1198. var token,
  1199. range,
  1200. value;
  1201. do {
  1202. range = [];
  1203. while (true) {
  1204. token = this.tn.next();
  1205. switch (token) {
  1206. case "min":
  1207. value = ProtoBuf.ID_MIN;
  1208. break;
  1209. case "max":
  1210. value = ProtoBuf.ID_MAX;
  1211. break;
  1212. default:
  1213. value = mkNumber(token);
  1214. break;
  1215. }
  1216. range.push(value);
  1217. if (range.length === 2)
  1218. break;
  1219. if (this.tn.peek() !== "to") {
  1220. range.push(value);
  1221. break;
  1222. }
  1223. this.tn.next();
  1224. }
  1225. ranges.push(range);
  1226. } while (this.tn.omit(","));
  1227. this.tn.skip(";");
  1228. return ranges;
  1229. };
  1230. /**
  1231. * Parses an extend block.
  1232. * @param {!Object} parent Parent object
  1233. * @private
  1234. */
  1235. ParserPrototype._parseExtend = function(parent) {
  1236. var token = this.tn.next();
  1237. if (!Lang.TYPEREF.test(token))
  1238. throw Error("illegal extend reference: "+token);
  1239. var ext = {
  1240. "ref": token,
  1241. "fields": []
  1242. };
  1243. this.tn.skip("{");
  1244. while ((token = this.tn.next()) !== '}') {
  1245. if (Lang.RULE.test(token))
  1246. this._parseMessageField(ext, token);
  1247. else if (Lang.TYPEREF.test(token)) {
  1248. if (!this.proto3)
  1249. throw Error("illegal field rule: "+token);
  1250. this._parseMessageField(ext, "optional", token);
  1251. } else
  1252. throw Error("illegal extend token: "+token);
  1253. }
  1254. this.tn.omit(";");
  1255. parent["messages"].push(ext);
  1256. return ext;
  1257. };
  1258. // ----- General -----
  1259. /**
  1260. * Returns a string representation of this parser.
  1261. * @returns {string}
  1262. */
  1263. ParserPrototype.toString = function() {
  1264. return "Parser at line "+this.tn.line;
  1265. };
  1266. /**
  1267. * @alias ProtoBuf.DotProto.Parser
  1268. * @expose
  1269. */
  1270. DotProto.Parser = Parser;
  1271. return DotProto;
  1272. })(ProtoBuf, ProtoBuf.Lang);
  1273. /**
  1274. * @alias ProtoBuf.Reflect
  1275. * @expose
  1276. */
  1277. ProtoBuf.Reflect = (function(ProtoBuf) {
  1278. "use strict";
  1279. /**
  1280. * Reflection types.
  1281. * @exports ProtoBuf.Reflect
  1282. * @namespace
  1283. */
  1284. var Reflect = {};
  1285. /**
  1286. * Constructs a Reflect base class.
  1287. * @exports ProtoBuf.Reflect.T
  1288. * @constructor
  1289. * @abstract
  1290. * @param {!ProtoBuf.Builder} builder Builder reference
  1291. * @param {?ProtoBuf.Reflect.T} parent Parent object
  1292. * @param {string} name Object name
  1293. */
  1294. var T = function(builder, parent, name) {
  1295. /**
  1296. * Builder reference.
  1297. * @type {!ProtoBuf.Builder}
  1298. * @expose
  1299. */
  1300. this.builder = builder;
  1301. /**
  1302. * Parent object.
  1303. * @type {?ProtoBuf.Reflect.T}
  1304. * @expose
  1305. */
  1306. this.parent = parent;
  1307. /**
  1308. * Object name in namespace.
  1309. * @type {string}
  1310. * @expose
  1311. */
  1312. this.name = name;
  1313. /**
  1314. * Fully qualified class name
  1315. * @type {string}
  1316. * @expose
  1317. */
  1318. this.className;
  1319. };
  1320. /**
  1321. * @alias ProtoBuf.Reflect.T.prototype
  1322. * @inner
  1323. */
  1324. var TPrototype = T.prototype;
  1325. /**
  1326. * Returns the fully qualified name of this object.
  1327. * @returns {string} Fully qualified name as of ".PATH.TO.THIS"
  1328. * @expose
  1329. */
  1330. TPrototype.fqn = function() {
  1331. var name = this.name,
  1332. ptr = this;
  1333. do {
  1334. ptr = ptr.parent;
  1335. if (ptr == null)
  1336. break;
  1337. name = ptr.name+"."+name;
  1338. } while (true);
  1339. return name;
  1340. };
  1341. /**
  1342. * Returns a string representation of this Reflect object (its fully qualified name).
  1343. * @param {boolean=} includeClass Set to true to include the class name. Defaults to false.
  1344. * @return String representation
  1345. * @expose
  1346. */
  1347. TPrototype.toString = function(includeClass) {
  1348. return (includeClass ? this.className + " " : "") + this.fqn();
  1349. };
  1350. /**
  1351. * Builds this type.
  1352. * @throws {Error} If this type cannot be built directly
  1353. * @expose
  1354. */
  1355. TPrototype.build = function() {
  1356. throw Error(this.toString(true)+" cannot be built directly");
  1357. };
  1358. /**
  1359. * @alias ProtoBuf.Reflect.T
  1360. * @expose
  1361. */
  1362. Reflect.T = T;
  1363. /**
  1364. * Constructs a new Namespace.
  1365. * @exports ProtoBuf.Reflect.Namespace
  1366. * @param {!ProtoBuf.Builder} builder Builder reference
  1367. * @param {?ProtoBuf.Reflect.Namespace} parent Namespace parent
  1368. * @param {string} name Namespace name
  1369. * @param {Object.<string,*>=} options Namespace options
  1370. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  1371. * @constructor
  1372. * @extends ProtoBuf.Reflect.T
  1373. */
  1374. var Namespace = function(builder, parent, name, options, syntax) {
  1375. T.call(this, builder, parent, name);
  1376. /**
  1377. * @override
  1378. */
  1379. this.className = "Namespace";
  1380. /**
  1381. * Children inside the namespace.
  1382. * @type {!Array.<ProtoBuf.Reflect.T>}
  1383. */
  1384. this.children = [];
  1385. /**
  1386. * Options.
  1387. * @type {!Object.<string, *>}
  1388. */
  1389. this.options = options || {};
  1390. /**
  1391. * Syntax level (e.g., proto2 or proto3).
  1392. * @type {!string}
  1393. */
  1394. this.syntax = syntax || "proto2";
  1395. };
  1396. /**
  1397. * @alias ProtoBuf.Reflect.Namespace.prototype
  1398. * @inner
  1399. */
  1400. var NamespacePrototype = Namespace.prototype = Object.create(T.prototype);
  1401. /**
  1402. * Returns an array of the namespace's children.
  1403. * @param {ProtoBuf.Reflect.T=} type Filter type (returns instances of this type only). Defaults to null (all children).
  1404. * @return {Array.<ProtoBuf.Reflect.T>}
  1405. * @expose
  1406. */
  1407. NamespacePrototype.getChildren = function(type) {
  1408. type = type || null;
  1409. if (type == null)
  1410. return this.children.slice();
  1411. var children = [];
  1412. for (var i=0, k=this.children.length; i<k; ++i)
  1413. if (this.children[i] instanceof type)
  1414. children.push(this.children[i]);
  1415. return children;
  1416. };
  1417. /**
  1418. * Adds a child to the namespace.
  1419. * @param {ProtoBuf.Reflect.T} child Child
  1420. * @throws {Error} If the child cannot be added (duplicate)
  1421. * @expose
  1422. */
  1423. NamespacePrototype.addChild = function(child) {
  1424. var other;
  1425. if (other = this.getChild(child.name)) {
  1426. // Try to revert camelcase transformation on collision
  1427. if (other instanceof Message.Field && other.name !== other.originalName && this.getChild(other.originalName) === null)
  1428. other.name = other.originalName; // Revert previous first (effectively keeps both originals)
  1429. else if (child instanceof Message.Field && child.name !== child.originalName && this.getChild(child.originalName) === null)
  1430. child.name = child.originalName;
  1431. else
  1432. throw Error("Duplicate name in namespace "+this.toString(true)+": "+child.name);
  1433. }
  1434. this.children.push(child);
  1435. };
  1436. /**
  1437. * Gets a child by its name or id.
  1438. * @param {string|number} nameOrId Child name or id
  1439. * @return {?ProtoBuf.Reflect.T} The child or null if not found
  1440. * @expose
  1441. */
  1442. NamespacePrototype.getChild = function(nameOrId) {
  1443. var key = typeof nameOrId === 'number' ? 'id' : 'name';
  1444. for (var i=0, k=this.children.length; i<k; ++i)
  1445. if (this.children[i][key] === nameOrId)
  1446. return this.children[i];
  1447. return null;
  1448. };
  1449. /**
  1450. * Resolves a reflect object inside of this namespace.
  1451. * @param {string|!Array.<string>} qn Qualified name to resolve
  1452. * @param {boolean=} excludeNonNamespace Excludes non-namespace types, defaults to `false`
  1453. * @return {?ProtoBuf.Reflect.Namespace} The resolved type or null if not found
  1454. * @expose
  1455. */
  1456. NamespacePrototype.resolve = function(qn, excludeNonNamespace) {
  1457. var part = typeof qn === 'string' ? qn.split(".") : qn,
  1458. ptr = this,
  1459. i = 0;
  1460. if (part[i] === "") { // Fully qualified name, e.g. ".My.Message'
  1461. while (ptr.parent !== null)
  1462. ptr = ptr.parent;
  1463. i++;
  1464. }
  1465. var child;
  1466. do {
  1467. do {
  1468. if (!(ptr instanceof Reflect.Namespace)) {
  1469. ptr = null;
  1470. break;
  1471. }
  1472. child = ptr.getChild(part[i]);
  1473. if (!child || !(child instanceof Reflect.T) || (excludeNonNamespace && !(child instanceof Reflect.Namespace))) {
  1474. ptr = null;
  1475. break;
  1476. }
  1477. ptr = child; i++;
  1478. } while (i < part.length);
  1479. if (ptr != null)
  1480. break; // Found
  1481. // Else search the parent
  1482. if (this.parent !== null)
  1483. return this.parent.resolve(qn, excludeNonNamespace);
  1484. } while (ptr != null);
  1485. return ptr;
  1486. };
  1487. /**
  1488. * Determines the shortest qualified name of the specified type, if any, relative to this namespace.
  1489. * @param {!ProtoBuf.Reflect.T} t Reflection type
  1490. * @returns {string} The shortest qualified name or, if there is none, the fqn
  1491. * @expose
  1492. */
  1493. NamespacePrototype.qn = function(t) {
  1494. var part = [], ptr = t;
  1495. do {
  1496. part.unshift(ptr.name);
  1497. ptr = ptr.parent;
  1498. } while (ptr !== null);
  1499. for (var len=1; len <= part.length; len++) {
  1500. var qn = part.slice(part.length-len);
  1501. if (t === this.resolve(qn, t instanceof Reflect.Namespace))
  1502. return qn.join(".");
  1503. }
  1504. return t.fqn();
  1505. };
  1506. /**
  1507. * Builds the namespace and returns the runtime counterpart.
  1508. * @return {Object.<string,Function|Object>} Runtime namespace
  1509. * @expose
  1510. */
  1511. NamespacePrototype.build = function() {
  1512. /** @dict */
  1513. var ns = {};
  1514. var children = this.children;
  1515. for (var i=0, k=children.length, child; i<k; ++i) {
  1516. child = children[i];
  1517. if (child instanceof Namespace)
  1518. ns[child.name] = child.build();
  1519. }
  1520. if (Object.defineProperty)
  1521. Object.defineProperty(ns, "$options", { "value": this.buildOpt() });
  1522. return ns;
  1523. };
  1524. /**
  1525. * Builds the namespace's '$options' property.
  1526. * @return {Object.<string,*>}
  1527. */
  1528. NamespacePrototype.buildOpt = function() {
  1529. var opt = {},
  1530. keys = Object.keys(this.options);
  1531. for (var i=0, k=keys.length; i<k; ++i) {
  1532. var key = keys[i],
  1533. val = this.options[keys[i]];
  1534. // TODO: Options are not resolved, yet.
  1535. // if (val instanceof Namespace) {
  1536. // opt[key] = val.build();
  1537. // } else {
  1538. opt[key] = val;
  1539. // }
  1540. }
  1541. return opt;
  1542. };
  1543. /**
  1544. * Gets the value assigned to the option with the specified name.
  1545. * @param {string=} name Returns the option value if specified, otherwise all options are returned.
  1546. * @return {*|Object.<string,*>}null} Option value or NULL if there is no such option
  1547. */
  1548. NamespacePrototype.getOption = function(name) {
  1549. if (typeof name === 'undefined')
  1550. return this.options;
  1551. return typeof this.options[name] !== 'undefined' ? this.options[name] : null;
  1552. };
  1553. /**
  1554. * @alias ProtoBuf.Reflect.Namespace
  1555. * @expose
  1556. */
  1557. Reflect.Namespace = Namespace;
  1558. /**
  1559. * Constructs a new Element implementation that checks and converts values for a
  1560. * particular field type, as appropriate.
  1561. *
  1562. * An Element represents a single value: either the value of a singular field,
  1563. * or a value contained in one entry of a repeated field or map field. This
  1564. * class does not implement these higher-level concepts; it only encapsulates
  1565. * the low-level typechecking and conversion.
  1566. *
  1567. * @exports ProtoBuf.Reflect.Element
  1568. * @param {{name: string, wireType: number}} type Resolved data type
  1569. * @param {ProtoBuf.Reflect.T|null} resolvedType Resolved type, if relevant
  1570. * (e.g. submessage field).
  1571. * @param {boolean} isMapKey Is this element a Map key? The value will be
  1572. * converted to string form if so.
  1573. * @param {string} syntax Syntax level of defining message type, e.g.,
  1574. * proto2 or proto3.
  1575. * @param {string} name Name of the field containing this element (for error
  1576. * messages)
  1577. * @constructor
  1578. */
  1579. var Element = function(type, resolvedType, isMapKey, syntax, name) {
  1580. /**
  1581. * Element type, as a string (e.g., int32).
  1582. * @type {{name: string, wireType: number}}
  1583. */
  1584. this.type = type;
  1585. /**
  1586. * Element type reference to submessage or enum definition, if needed.
  1587. * @type {ProtoBuf.Reflect.T|null}
  1588. */
  1589. this.resolvedType = resolvedType;
  1590. /**
  1591. * Element is a map key.
  1592. * @type {boolean}
  1593. */
  1594. this.isMapKey = isMapKey;
  1595. /**
  1596. * Syntax level of defining message type, e.g., proto2 or proto3.
  1597. * @type {string}
  1598. */
  1599. this.syntax = syntax;
  1600. /**
  1601. * Name of the field containing this element (for error messages)
  1602. * @type {string}
  1603. */
  1604. this.name = name;
  1605. if (isMapKey && ProtoBuf.MAP_KEY_TYPES.indexOf(type) < 0)
  1606. throw Error("Invalid map key type: " + type.name);
  1607. };
  1608. var ElementPrototype = Element.prototype;
  1609. /**
  1610. * Obtains a (new) default value for the specified type.
  1611. * @param type {string|{name: string, wireType: number}} Field type
  1612. * @returns {*} Default value
  1613. * @inner
  1614. */
  1615. function mkDefault(type) {
  1616. if (typeof type === 'string')
  1617. type = ProtoBuf.TYPES[type];
  1618. if (typeof type.defaultValue === 'undefined')
  1619. throw Error("default value for type "+type.name+" is not supported");
  1620. if (type == ProtoBuf.TYPES["bytes"])
  1621. return new ByteBuffer(0);
  1622. return type.defaultValue;
  1623. }
  1624. /**
  1625. * Returns the default value for this field in proto3.
  1626. * @function
  1627. * @param type {string|{name: string, wireType: number}} the field type
  1628. * @returns {*} Default value
  1629. */
  1630. Element.defaultFieldValue = mkDefault;
  1631. /**
  1632. * Makes a Long from a value.
  1633. * @param {{low: number, high: number, unsigned: boolean}|string|number} value Value
  1634. * @param {boolean=} unsigned Whether unsigned or not, defaults to reuse it from Long-like objects or to signed for
  1635. * strings and numbers
  1636. * @returns {!Long}
  1637. * @throws {Error} If the value cannot be converted to a Long
  1638. * @inner
  1639. */
  1640. function mkLong(value, unsigned) {
  1641. if (value && typeof value.low === 'number' && typeof value.high === 'number' && typeof value.unsigned === 'boolean'
  1642. && value.low === value.low && value.high === value.high)
  1643. return new ProtoBuf.Long(value.low, value.high, typeof unsigned === 'undefined' ? value.unsigned : unsigned);
  1644. if (typeof value === 'string')
  1645. return ProtoBuf.Long.fromString(value, unsigned || false, 10);
  1646. if (typeof value === 'number')
  1647. return ProtoBuf.Long.fromNumber(value, unsigned || false);
  1648. throw Error("not convertible to Long");
  1649. }
  1650. ElementPrototype.toString = function() {
  1651. return (this.name || '') + (this.isMapKey ? 'map' : 'value') + ' element';
  1652. }
  1653. /**
  1654. * Checks if the given value can be set for an element of this type (singular
  1655. * field or one element of a repeated field or map).
  1656. * @param {*} value Value to check
  1657. * @return {*} Verified, maybe adjusted, value
  1658. * @throws {Error} If the value cannot be verified for this element slot
  1659. * @expose
  1660. */
  1661. ElementPrototype.verifyValue = function(value) {
  1662. var self = this;
  1663. function fail(val, msg) {
  1664. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  1665. }
  1666. switch (this.type) {
  1667. // Signed 32bit
  1668. case ProtoBuf.TYPES["int32"]:
  1669. case ProtoBuf.TYPES["sint32"]:
  1670. case ProtoBuf.TYPES["sfixed32"]:
  1671. // Account for !NaN: value === value
  1672. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1673. fail(typeof value, "not an integer");
  1674. return value > 4294967295 ? value | 0 : value;
  1675. // Unsigned 32bit
  1676. case ProtoBuf.TYPES["uint32"]:
  1677. case ProtoBuf.TYPES["fixed32"]:
  1678. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1679. fail(typeof value, "not an integer");
  1680. return value < 0 ? value >>> 0 : value;
  1681. // Signed 64bit
  1682. case ProtoBuf.TYPES["int64"]:
  1683. case ProtoBuf.TYPES["sint64"]:
  1684. case ProtoBuf.TYPES["sfixed64"]: {
  1685. if (ProtoBuf.Long)
  1686. try {
  1687. return mkLong(value, false);
  1688. } catch (e) {
  1689. fail(typeof value, e.message);
  1690. }
  1691. else
  1692. fail(typeof value, "requires Long.js");
  1693. }
  1694. // Unsigned 64bit
  1695. case ProtoBuf.TYPES["uint64"]:
  1696. case ProtoBuf.TYPES["fixed64"]: {
  1697. if (ProtoBuf.Long)
  1698. try {
  1699. return mkLong(value, true);
  1700. } catch (e) {
  1701. fail(typeof value, e.message);
  1702. }
  1703. else
  1704. fail(typeof value, "requires Long.js");
  1705. }
  1706. // Bool
  1707. case ProtoBuf.TYPES["bool"]:
  1708. if (typeof value !== 'boolean')
  1709. fail(typeof value, "not a boolean");
  1710. return value;
  1711. // Float
  1712. case ProtoBuf.TYPES["float"]:
  1713. case ProtoBuf.TYPES["double"]:
  1714. if (typeof value !== 'number')
  1715. fail(typeof value, "not a number");
  1716. return value;
  1717. // Length-delimited string
  1718. case ProtoBuf.TYPES["string"]:
  1719. if (typeof value !== 'string' && !(value && value instanceof String))
  1720. fail(typeof value, "not a string");
  1721. return ""+value; // Convert String object to string
  1722. // Length-delimited bytes
  1723. case ProtoBuf.TYPES["bytes"]:
  1724. if (ByteBuffer.isByteBuffer(value))
  1725. return value;
  1726. return ByteBuffer.wrap(value, "base64");
  1727. // Constant enum value
  1728. case ProtoBuf.TYPES["enum"]: {
  1729. var values = this.resolvedType.getChildren(ProtoBuf.Reflect.Enum.Value);
  1730. for (i=0; i<values.length; i++)
  1731. if (values[i].name == value)
  1732. return values[i].id;
  1733. else if (values[i].id == value)
  1734. return values[i].id;
  1735. if (this.syntax === 'proto3') {
  1736. // proto3: just make sure it's an integer.
  1737. if (typeof value !== 'number' || (value === value && value % 1 !== 0))
  1738. fail(typeof value, "not an integer");
  1739. if (value > 4294967295 || value < 0)
  1740. fail(typeof value, "not in range for uint32")
  1741. return value;
  1742. } else {
  1743. // proto2 requires enum values to be valid.
  1744. fail(value, "not a valid enum value");
  1745. }
  1746. }
  1747. // Embedded message
  1748. case ProtoBuf.TYPES["group"]:
  1749. case ProtoBuf.TYPES["message"]: {
  1750. if (!value || typeof value !== 'object')
  1751. fail(typeof value, "object expected");
  1752. if (value instanceof this.resolvedType.clazz)
  1753. return value;
  1754. if (value instanceof ProtoBuf.Builder.Message) {
  1755. // Mismatched type: Convert to object (see: https://github.com/dcodeIO/ProtoBuf.js/issues/180)
  1756. var obj = {};
  1757. for (var i in value)
  1758. if (value.hasOwnProperty(i))
  1759. obj[i] = value[i];
  1760. value = obj;
  1761. }
  1762. // Else let's try to construct one from a key-value object
  1763. return new (this.resolvedType.clazz)(value); // May throw for a hundred of reasons
  1764. }
  1765. }
  1766. // We should never end here
  1767. throw Error("[INTERNAL] Illegal value for "+this.toString(true)+": "+value+" (undefined type "+this.type+")");
  1768. };
  1769. /**
  1770. * Calculates the byte length of an element on the wire.
  1771. * @param {number} id Field number
  1772. * @param {*} value Field value
  1773. * @returns {number} Byte length
  1774. * @throws {Error} If the value cannot be calculated
  1775. * @expose
  1776. */
  1777. ElementPrototype.calculateLength = function(id, value) {
  1778. if (value === null) return 0; // Nothing to encode
  1779. // Tag has already been written
  1780. var n;
  1781. switch (this.type) {
  1782. case ProtoBuf.TYPES["int32"]:
  1783. return value < 0 ? ByteBuffer.calculateVarint64(value) : ByteBuffer.calculateVarint32(value);
  1784. case ProtoBuf.TYPES["uint32"]:
  1785. return ByteBuffer.calculateVarint32(value);
  1786. case ProtoBuf.TYPES["sint32"]:
  1787. return ByteBuffer.calculateVarint32(ByteBuffer.zigZagEncode32(value));
  1788. case ProtoBuf.TYPES["fixed32"]:
  1789. case ProtoBuf.TYPES["sfixed32"]:
  1790. case ProtoBuf.TYPES["float"]:
  1791. return 4;
  1792. case ProtoBuf.TYPES["int64"]:
  1793. case ProtoBuf.TYPES["uint64"]:
  1794. return ByteBuffer.calculateVarint64(value);
  1795. case ProtoBuf.TYPES["sint64"]:
  1796. return ByteBuffer.calculateVarint64(ByteBuffer.zigZagEncode64(value));
  1797. case ProtoBuf.TYPES["fixed64"]:
  1798. case ProtoBuf.TYPES["sfixed64"]:
  1799. return 8;
  1800. case ProtoBuf.TYPES["bool"]:
  1801. return 1;
  1802. case ProtoBuf.TYPES["enum"]:
  1803. return ByteBuffer.calculateVarint32(value);
  1804. case ProtoBuf.TYPES["double"]:
  1805. return 8;
  1806. case ProtoBuf.TYPES["string"]:
  1807. n = ByteBuffer.calculateUTF8Bytes(value);
  1808. return ByteBuffer.calculateVarint32(n) + n;
  1809. case ProtoBuf.TYPES["bytes"]:
  1810. if (value.remaining() < 0)
  1811. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  1812. return ByteBuffer.calculateVarint32(value.remaining()) + value.remaining();
  1813. case ProtoBuf.TYPES["message"]:
  1814. n = this.resolvedType.calculate(value);
  1815. return ByteBuffer.calculateVarint32(n) + n;
  1816. case ProtoBuf.TYPES["group"]:
  1817. n = this.resolvedType.calculate(value);
  1818. return n + ByteBuffer.calculateVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  1819. }
  1820. // We should never end here
  1821. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  1822. };
  1823. /**
  1824. * Encodes a value to the specified buffer. Does not encode the key.
  1825. * @param {number} id Field number
  1826. * @param {*} value Field value
  1827. * @param {ByteBuffer} buffer ByteBuffer to encode to
  1828. * @return {ByteBuffer} The ByteBuffer for chaining
  1829. * @throws {Error} If the value cannot be encoded
  1830. * @expose
  1831. */
  1832. ElementPrototype.encodeValue = function(id, value, buffer) {
  1833. if (value === null) return buffer; // Nothing to encode
  1834. // Tag has already been written
  1835. switch (this.type) {
  1836. // 32bit signed varint
  1837. case ProtoBuf.TYPES["int32"]:
  1838. // "If you use int32 or int64 as the type for a negative number, the resulting varint is always ten bytes
  1839. // long – it is, effectively, treated like a very large unsigned integer." (see #122)
  1840. if (value < 0)
  1841. buffer.writeVarint64(value);
  1842. else
  1843. buffer.writeVarint32(value);
  1844. break;
  1845. // 32bit unsigned varint
  1846. case ProtoBuf.TYPES["uint32"]:
  1847. buffer.writeVarint32(value);
  1848. break;
  1849. // 32bit varint zig-zag
  1850. case ProtoBuf.TYPES["sint32"]:
  1851. buffer.writeVarint32ZigZag(value);
  1852. break;
  1853. // Fixed unsigned 32bit
  1854. case ProtoBuf.TYPES["fixed32"]:
  1855. buffer.writeUint32(value);
  1856. break;
  1857. // Fixed signed 32bit
  1858. case ProtoBuf.TYPES["sfixed32"]:
  1859. buffer.writeInt32(value);
  1860. break;
  1861. // 64bit varint as-is
  1862. case ProtoBuf.TYPES["int64"]:
  1863. case ProtoBuf.TYPES["uint64"]:
  1864. buffer.writeVarint64(value); // throws
  1865. break;
  1866. // 64bit varint zig-zag
  1867. case ProtoBuf.TYPES["sint64"]:
  1868. buffer.writeVarint64ZigZag(value); // throws
  1869. break;
  1870. // Fixed unsigned 64bit
  1871. case ProtoBuf.TYPES["fixed64"]:
  1872. buffer.writeUint64(value); // throws
  1873. break;
  1874. // Fixed signed 64bit
  1875. case ProtoBuf.TYPES["sfixed64"]:
  1876. buffer.writeInt64(value); // throws
  1877. break;
  1878. // Bool
  1879. case ProtoBuf.TYPES["bool"]:
  1880. if (typeof value === 'string')
  1881. buffer.writeVarint32(value.toLowerCase() === 'false' ? 0 : !!value);
  1882. else
  1883. buffer.writeVarint32(value ? 1 : 0);
  1884. break;
  1885. // Constant enum value
  1886. case ProtoBuf.TYPES["enum"]:
  1887. buffer.writeVarint32(value);
  1888. break;
  1889. // 32bit float
  1890. case ProtoBuf.TYPES["float"]:
  1891. buffer.writeFloat32(value);
  1892. break;
  1893. // 64bit float
  1894. case ProtoBuf.TYPES["double"]:
  1895. buffer.writeFloat64(value);
  1896. break;
  1897. // Length-delimited string
  1898. case ProtoBuf.TYPES["string"]:
  1899. buffer.writeVString(value);
  1900. break;
  1901. // Length-delimited bytes
  1902. case ProtoBuf.TYPES["bytes"]:
  1903. if (value.remaining() < 0)
  1904. throw Error("Illegal value for "+this.toString(true)+": "+value.remaining()+" bytes remaining");
  1905. var prevOffset = value.offset;
  1906. buffer.writeVarint32(value.remaining());
  1907. buffer.append(value);
  1908. value.offset = prevOffset;
  1909. break;
  1910. // Embedded message
  1911. case ProtoBuf.TYPES["message"]:
  1912. var bb = new ByteBuffer().LE();
  1913. this.resolvedType.encode(value, bb);
  1914. buffer.writeVarint32(bb.offset);
  1915. buffer.append(bb.flip());
  1916. break;
  1917. // Legacy group
  1918. case ProtoBuf.TYPES["group"]:
  1919. this.resolvedType.encode(value, buffer);
  1920. buffer.writeVarint32((id << 3) | ProtoBuf.WIRE_TYPES.ENDGROUP);
  1921. break;
  1922. default:
  1923. // We should never end here
  1924. throw Error("[INTERNAL] Illegal value to encode in "+this.toString(true)+": "+value+" (unknown type)");
  1925. }
  1926. return buffer;
  1927. };
  1928. /**
  1929. * Decode one element value from the specified buffer.
  1930. * @param {ByteBuffer} buffer ByteBuffer to decode from
  1931. * @param {number} wireType The field wire type
  1932. * @param {number} id The field number
  1933. * @return {*} Decoded value
  1934. * @throws {Error} If the field cannot be decoded
  1935. * @expose
  1936. */
  1937. ElementPrototype.decode = function(buffer, wireType, id) {
  1938. if (wireType != this.type.wireType)
  1939. throw Error("Unexpected wire type for element");
  1940. var value, nBytes;
  1941. switch (this.type) {
  1942. // 32bit signed varint
  1943. case ProtoBuf.TYPES["int32"]:
  1944. return buffer.readVarint32() | 0;
  1945. // 32bit unsigned varint
  1946. case ProtoBuf.TYPES["uint32"]:
  1947. return buffer.readVarint32() >>> 0;
  1948. // 32bit signed varint zig-zag
  1949. case ProtoBuf.TYPES["sint32"]:
  1950. return buffer.readVarint32ZigZag() | 0;
  1951. // Fixed 32bit unsigned
  1952. case ProtoBuf.TYPES["fixed32"]:
  1953. return buffer.readUint32() >>> 0;
  1954. case ProtoBuf.TYPES["sfixed32"]:
  1955. return buffer.readInt32() | 0;
  1956. // 64bit signed varint
  1957. case ProtoBuf.TYPES["int64"]:
  1958. return buffer.readVarint64();
  1959. // 64bit unsigned varint
  1960. case ProtoBuf.TYPES["uint64"]:
  1961. return buffer.readVarint64().toUnsigned();
  1962. // 64bit signed varint zig-zag
  1963. case ProtoBuf.TYPES["sint64"]:
  1964. return buffer.readVarint64ZigZag();
  1965. // Fixed 64bit unsigned
  1966. case ProtoBuf.TYPES["fixed64"]:
  1967. return buffer.readUint64();
  1968. // Fixed 64bit signed
  1969. case ProtoBuf.TYPES["sfixed64"]:
  1970. return buffer.readInt64();
  1971. // Bool varint
  1972. case ProtoBuf.TYPES["bool"]:
  1973. return !!buffer.readVarint32();
  1974. // Constant enum value (varint)
  1975. case ProtoBuf.TYPES["enum"]:
  1976. // The following Builder.Message#set will already throw
  1977. return buffer.readVarint32();
  1978. // 32bit float
  1979. case ProtoBuf.TYPES["float"]:
  1980. return buffer.readFloat();
  1981. // 64bit float
  1982. case ProtoBuf.TYPES["double"]:
  1983. return buffer.readDouble();
  1984. // Length-delimited string
  1985. case ProtoBuf.TYPES["string"]:
  1986. return buffer.readVString();
  1987. // Length-delimited bytes
  1988. case ProtoBuf.TYPES["bytes"]: {
  1989. nBytes = buffer.readVarint32();
  1990. if (buffer.remaining() < nBytes)
  1991. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  1992. value = buffer.clone(); // Offset already set
  1993. value.limit = value.offset+nBytes;
  1994. buffer.offset += nBytes;
  1995. return value;
  1996. }
  1997. // Length-delimited embedded message
  1998. case ProtoBuf.TYPES["message"]: {
  1999. nBytes = buffer.readVarint32();
  2000. return this.resolvedType.decode(buffer, nBytes);
  2001. }
  2002. // Legacy group
  2003. case ProtoBuf.TYPES["group"]:
  2004. return this.resolvedType.decode(buffer, -1, id);
  2005. }
  2006. // We should never end here
  2007. throw Error("[INTERNAL] Illegal decode type");
  2008. };
  2009. /**
  2010. * Converts a value from a string to the canonical element type.
  2011. *
  2012. * Legal only when isMapKey is true.
  2013. *
  2014. * @param {string} str The string value
  2015. * @returns {*} The value
  2016. */
  2017. ElementPrototype.valueFromString = function(str) {
  2018. if (!this.isMapKey) {
  2019. throw Error("valueFromString() called on non-map-key element");
  2020. }
  2021. switch (this.type) {
  2022. case ProtoBuf.TYPES["int32"]:
  2023. case ProtoBuf.TYPES["sint32"]:
  2024. case ProtoBuf.TYPES["sfixed32"]:
  2025. case ProtoBuf.TYPES["uint32"]:
  2026. case ProtoBuf.TYPES["fixed32"]:
  2027. return this.verifyValue(parseInt(str));
  2028. case ProtoBuf.TYPES["int64"]:
  2029. case ProtoBuf.TYPES["sint64"]:
  2030. case ProtoBuf.TYPES["sfixed64"]:
  2031. case ProtoBuf.TYPES["uint64"]:
  2032. case ProtoBuf.TYPES["fixed64"]:
  2033. // Long-based fields support conversions from string already.
  2034. return this.verifyValue(str);
  2035. case ProtoBuf.TYPES["bool"]:
  2036. return str === "true";
  2037. case ProtoBuf.TYPES["string"]:
  2038. return this.verifyValue(str);
  2039. case ProtoBuf.TYPES["bytes"]:
  2040. return ByteBuffer.fromBinary(str);
  2041. }
  2042. };
  2043. /**
  2044. * Converts a value from the canonical element type to a string.
  2045. *
  2046. * It should be the case that `valueFromString(valueToString(val))` returns
  2047. * a value equivalent to `verifyValue(val)` for every legal value of `val`
  2048. * according to this element type.
  2049. *
  2050. * This may be used when the element must be stored or used as a string,
  2051. * e.g., as a map key on an Object.
  2052. *
  2053. * Legal only when isMapKey is true.
  2054. *
  2055. * @param {*} val The value
  2056. * @returns {string} The string form of the value.
  2057. */
  2058. ElementPrototype.valueToString = function(value) {
  2059. if (!this.isMapKey) {
  2060. throw Error("valueToString() called on non-map-key element");
  2061. }
  2062. if (this.type === ProtoBuf.TYPES["bytes"]) {
  2063. return value.toString("binary");
  2064. } else {
  2065. return value.toString();
  2066. }
  2067. };
  2068. /**
  2069. * @alias ProtoBuf.Reflect.Element
  2070. * @expose
  2071. */
  2072. Reflect.Element = Element;
  2073. /**
  2074. * Constructs a new Message.
  2075. * @exports ProtoBuf.Reflect.Message
  2076. * @param {!ProtoBuf.Builder} builder Builder reference
  2077. * @param {!ProtoBuf.Reflect.Namespace} parent Parent message or namespace
  2078. * @param {string} name Message name
  2079. * @param {Object.<string,*>=} options Message options
  2080. * @param {boolean=} isGroup `true` if this is a legacy group
  2081. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  2082. * @constructor
  2083. * @extends ProtoBuf.Reflect.Namespace
  2084. */
  2085. var Message = function(builder, parent, name, options, isGroup, syntax) {
  2086. Namespace.call(this, builder, parent, name, options, syntax);
  2087. /**
  2088. * @override
  2089. */
  2090. this.className = "Message";
  2091. /**
  2092. * Extensions range.
  2093. * @type {!Array.<number>|undefined}
  2094. * @expose
  2095. */
  2096. this.extensions = undefined;
  2097. /**
  2098. * Runtime message class.
  2099. * @type {?function(new:ProtoBuf.Builder.Message)}
  2100. * @expose
  2101. */
  2102. this.clazz = null;
  2103. /**
  2104. * Whether this is a legacy group or not.
  2105. * @type {boolean}
  2106. * @expose
  2107. */
  2108. this.isGroup = !!isGroup;
  2109. // The following cached collections are used to efficiently iterate over or look up fields when decoding.
  2110. /**
  2111. * Cached fields.
  2112. * @type {?Array.<!ProtoBuf.Reflect.Message.Field>}
  2113. * @private
  2114. */
  2115. this._fields = null;
  2116. /**
  2117. * Cached fields by id.
  2118. * @type {?Object.<number,!ProtoBuf.Reflect.Message.Field>}
  2119. * @private
  2120. */
  2121. this._fieldsById = null;
  2122. /**
  2123. * Cached fields by name.
  2124. * @type {?Object.<string,!ProtoBuf.Reflect.Message.Field>}
  2125. * @private
  2126. */
  2127. this._fieldsByName = null;
  2128. };
  2129. /**
  2130. * @alias ProtoBuf.Reflect.Message.prototype
  2131. * @inner
  2132. */
  2133. var MessagePrototype = Message.prototype = Object.create(Namespace.prototype);
  2134. /**
  2135. * Builds the message and returns the runtime counterpart, which is a fully functional class.
  2136. * @see ProtoBuf.Builder.Message
  2137. * @param {boolean=} rebuild Whether to rebuild or not, defaults to false
  2138. * @return {ProtoBuf.Reflect.Message} Message class
  2139. * @throws {Error} If the message cannot be built
  2140. * @expose
  2141. */
  2142. MessagePrototype.build = function(rebuild) {
  2143. if (this.clazz && !rebuild)
  2144. return this.clazz;
  2145. // Create the runtime Message class in its own scope
  2146. var clazz = (function(ProtoBuf, T) {
  2147. var fields = T.getChildren(ProtoBuf.Reflect.Message.Field),
  2148. oneofs = T.getChildren(ProtoBuf.Reflect.Message.OneOf);
  2149. /**
  2150. * Constructs a new runtime Message.
  2151. * @name ProtoBuf.Builder.Message
  2152. * @class Barebone of all runtime messages.
  2153. * @param {!Object.<string,*>|string} values Preset values
  2154. * @param {...string} var_args
  2155. * @constructor
  2156. * @throws {Error} If the message cannot be created
  2157. */
  2158. var Message = function(values, var_args) {
  2159. ProtoBuf.Builder.Message.call(this);
  2160. // Create virtual oneof properties
  2161. for (var i=0, k=oneofs.length; i<k; ++i)
  2162. this[oneofs[i].name] = null;
  2163. // Create fields and set default values
  2164. for (i=0, k=fields.length; i<k; ++i) {
  2165. var field = fields[i];
  2166. this[field.name] =
  2167. field.repeated ? [] :
  2168. (field.map ? new ProtoBuf.Map(field) : null);
  2169. if ((field.required || T.syntax === 'proto3') &&
  2170. field.defaultValue !== null)
  2171. this[field.name] = field.defaultValue;
  2172. }
  2173. if (arguments.length > 0) {
  2174. var value;
  2175. // Set field values from a values object
  2176. if (arguments.length === 1 && values !== null && typeof values === 'object' &&
  2177. /* not _another_ Message */ (typeof values.encode !== 'function' || values instanceof Message) &&
  2178. /* not a repeated field */ !Array.isArray(values) &&
  2179. /* not a Map */ !(values instanceof ProtoBuf.Map) &&
  2180. /* not a ByteBuffer */ !ByteBuffer.isByteBuffer(values) &&
  2181. /* not an ArrayBuffer */ !(values instanceof ArrayBuffer) &&
  2182. /* not a Long */ !(ProtoBuf.Long && values instanceof ProtoBuf.Long)) {
  2183. this.$set(values);
  2184. } else // Set field values from arguments, in declaration order
  2185. for (i=0, k=arguments.length; i<k; ++i)
  2186. if (typeof (value = arguments[i]) !== 'undefined')
  2187. this.$set(fields[i].name, value); // May throw
  2188. }
  2189. };
  2190. /**
  2191. * @alias ProtoBuf.Builder.Message.prototype
  2192. * @inner
  2193. */
  2194. var MessagePrototype = Message.prototype = Object.create(ProtoBuf.Builder.Message.prototype);
  2195. /**
  2196. * Adds a value to a repeated field.
  2197. * @name ProtoBuf.Builder.Message#add
  2198. * @function
  2199. * @param {string} key Field name
  2200. * @param {*} value Value to add
  2201. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  2202. * @returns {!ProtoBuf.Builder.Message} this
  2203. * @throws {Error} If the value cannot be added
  2204. * @expose
  2205. */
  2206. MessagePrototype.add = function(key, value, noAssert) {
  2207. var field = T._fieldsByName[key];
  2208. if (!noAssert) {
  2209. if (!field)
  2210. throw Error(this+"#"+key+" is undefined");
  2211. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2212. throw Error(this+"#"+key+" is not a field: "+field.toString(true)); // May throw if it's an enum or embedded message
  2213. if (!field.repeated)
  2214. throw Error(this+"#"+key+" is not a repeated field");
  2215. value = field.verifyValue(value, true);
  2216. }
  2217. if (this[key] === null)
  2218. this[key] = [];
  2219. this[key].push(value);
  2220. return this;
  2221. };
  2222. /**
  2223. * Adds a value to a repeated field. This is an alias for {@link ProtoBuf.Builder.Message#add}.
  2224. * @name ProtoBuf.Builder.Message#$add
  2225. * @function
  2226. * @param {string} key Field name
  2227. * @param {*} value Value to add
  2228. * @param {boolean=} noAssert Whether to assert the value or not (asserts by default)
  2229. * @returns {!ProtoBuf.Builder.Message} this
  2230. * @throws {Error} If the value cannot be added
  2231. * @expose
  2232. */
  2233. MessagePrototype.$add = MessagePrototype.add;
  2234. /**
  2235. * Sets a field's value.
  2236. * @name ProtoBuf.Builder.Message#set
  2237. * @function
  2238. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  2239. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  2240. * @param {boolean=} noAssert Whether to not assert for an actual field / proper value type, defaults to `false`
  2241. * @returns {!ProtoBuf.Builder.Message} this
  2242. * @throws {Error} If the value cannot be set
  2243. * @expose
  2244. */
  2245. MessagePrototype.set = function(keyOrObj, value, noAssert) {
  2246. if (keyOrObj && typeof keyOrObj === 'object') {
  2247. noAssert = value;
  2248. for (var ikey in keyOrObj) {
  2249. // Check if virtual oneof field - don't set these
  2250. if (keyOrObj.hasOwnProperty(ikey) && typeof (value = keyOrObj[ikey]) !== 'undefined' && T._oneofsByName[ikey] === undefined)
  2251. this.$set(ikey, value, noAssert);
  2252. }
  2253. return this;
  2254. }
  2255. var field = T._fieldsByName[keyOrObj];
  2256. if (!noAssert) {
  2257. if (!field)
  2258. throw Error(this+"#"+keyOrObj+" is not a field: undefined");
  2259. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2260. throw Error(this+"#"+keyOrObj+" is not a field: "+field.toString(true));
  2261. this[field.name] = (value = field.verifyValue(value)); // May throw
  2262. } else
  2263. this[keyOrObj] = value;
  2264. if (field && field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  2265. var currentField = this[field.oneof.name]; // Virtual field references currently set field
  2266. if (value !== null) {
  2267. if (currentField !== null && currentField !== field.name)
  2268. this[currentField] = null; // Clear currently set field
  2269. this[field.oneof.name] = field.name; // Point virtual field at this field
  2270. } else if (/* value === null && */currentField === keyOrObj)
  2271. this[field.oneof.name] = null; // Clear virtual field (current field explicitly cleared)
  2272. }
  2273. return this;
  2274. };
  2275. /**
  2276. * Sets a field's value. This is an alias for [@link ProtoBuf.Builder.Message#set}.
  2277. * @name ProtoBuf.Builder.Message#$set
  2278. * @function
  2279. * @param {string|!Object.<string,*>} keyOrObj String key or plain object holding multiple values
  2280. * @param {(*|boolean)=} value Value to set if key is a string, otherwise omitted
  2281. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2282. * @throws {Error} If the value cannot be set
  2283. * @expose
  2284. */
  2285. MessagePrototype.$set = MessagePrototype.set;
  2286. /**
  2287. * Gets a field's value.
  2288. * @name ProtoBuf.Builder.Message#get
  2289. * @function
  2290. * @param {string} key Key
  2291. * @param {boolean=} noAssert Whether to not assert for an actual field, defaults to `false`
  2292. * @return {*} Value
  2293. * @throws {Error} If there is no such field
  2294. * @expose
  2295. */
  2296. MessagePrototype.get = function(key, noAssert) {
  2297. if (noAssert)
  2298. return this[key];
  2299. var field = T._fieldsByName[key];
  2300. if (!field || !(field instanceof ProtoBuf.Reflect.Message.Field))
  2301. throw Error(this+"#"+key+" is not a field: undefined");
  2302. if (!(field instanceof ProtoBuf.Reflect.Message.Field))
  2303. throw Error(this+"#"+key+" is not a field: "+field.toString(true));
  2304. return this[field.name];
  2305. };
  2306. /**
  2307. * Gets a field's value. This is an alias for {@link ProtoBuf.Builder.Message#$get}.
  2308. * @name ProtoBuf.Builder.Message#$get
  2309. * @function
  2310. * @param {string} key Key
  2311. * @return {*} Value
  2312. * @throws {Error} If there is no such field
  2313. * @expose
  2314. */
  2315. MessagePrototype.$get = MessagePrototype.get;
  2316. // Getters and setters
  2317. for (var i=0; i<fields.length; i++) {
  2318. var field = fields[i];
  2319. // no setters for extension fields as these are named by their fqn
  2320. if (field instanceof ProtoBuf.Reflect.Message.ExtensionField)
  2321. continue;
  2322. if (T.builder.options['populateAccessors'])
  2323. (function(field) {
  2324. // set/get[SomeValue]
  2325. var Name = field.originalName.replace(/(_[a-zA-Z])/g, function(match) {
  2326. return match.toUpperCase().replace('_','');
  2327. });
  2328. Name = Name.substring(0,1).toUpperCase() + Name.substring(1);
  2329. // set/get_[some_value] FIXME: Do we really need these?
  2330. var name = field.originalName.replace(/([A-Z])/g, function(match) {
  2331. return "_"+match;
  2332. });
  2333. /**
  2334. * The current field's unbound setter function.
  2335. * @function
  2336. * @param {*} value
  2337. * @param {boolean=} noAssert
  2338. * @returns {!ProtoBuf.Builder.Message}
  2339. * @inner
  2340. */
  2341. var setter = function(value, noAssert) {
  2342. this[field.name] = noAssert ? value : field.verifyValue(value);
  2343. return this;
  2344. };
  2345. /**
  2346. * The current field's unbound getter function.
  2347. * @function
  2348. * @returns {*}
  2349. * @inner
  2350. */
  2351. var getter = function() {
  2352. return this[field.name];
  2353. };
  2354. if (T.getChild("set"+Name) === null)
  2355. /**
  2356. * Sets a value. This method is present for each field, but only if there is no name conflict with
  2357. * another field.
  2358. * @name ProtoBuf.Builder.Message#set[SomeField]
  2359. * @function
  2360. * @param {*} value Value to set
  2361. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2362. * @returns {!ProtoBuf.Builder.Message} this
  2363. * @abstract
  2364. * @throws {Error} If the value cannot be set
  2365. */
  2366. MessagePrototype["set"+Name] = setter;
  2367. if (T.getChild("set_"+name) === null)
  2368. /**
  2369. * Sets a value. This method is present for each field, but only if there is no name conflict with
  2370. * another field.
  2371. * @name ProtoBuf.Builder.Message#set_[some_field]
  2372. * @function
  2373. * @param {*} value Value to set
  2374. * @param {boolean=} noAssert Whether to not assert the value, defaults to `false`
  2375. * @returns {!ProtoBuf.Builder.Message} this
  2376. * @abstract
  2377. * @throws {Error} If the value cannot be set
  2378. */
  2379. MessagePrototype["set_"+name] = setter;
  2380. if (T.getChild("get"+Name) === null)
  2381. /**
  2382. * Gets a value. This method is present for each field, but only if there is no name conflict with
  2383. * another field.
  2384. * @name ProtoBuf.Builder.Message#get[SomeField]
  2385. * @function
  2386. * @abstract
  2387. * @return {*} The value
  2388. */
  2389. MessagePrototype["get"+Name] = getter;
  2390. if (T.getChild("get_"+name) === null)
  2391. /**
  2392. * Gets a value. This method is present for each field, but only if there is no name conflict with
  2393. * another field.
  2394. * @name ProtoBuf.Builder.Message#get_[some_field]
  2395. * @function
  2396. * @return {*} The value
  2397. * @abstract
  2398. */
  2399. MessagePrototype["get_"+name] = getter;
  2400. })(field);
  2401. }
  2402. // En-/decoding
  2403. /**
  2404. * Encodes the message.
  2405. * @name ProtoBuf.Builder.Message#$encode
  2406. * @function
  2407. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2408. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2409. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2410. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2411. * returns the encoded ByteBuffer in the `encoded` property on the error.
  2412. * @expose
  2413. * @see ProtoBuf.Builder.Message#encode64
  2414. * @see ProtoBuf.Builder.Message#encodeHex
  2415. * @see ProtoBuf.Builder.Message#encodeAB
  2416. */
  2417. MessagePrototype.encode = function(buffer, noVerify) {
  2418. if (typeof buffer === 'boolean')
  2419. noVerify = buffer,
  2420. buffer = undefined;
  2421. var isNew = false;
  2422. if (!buffer)
  2423. buffer = new ByteBuffer(),
  2424. isNew = true;
  2425. var le = buffer.littleEndian;
  2426. try {
  2427. T.encode(this, buffer.LE(), noVerify);
  2428. return (isNew ? buffer.flip() : buffer).LE(le);
  2429. } catch (e) {
  2430. buffer.LE(le);
  2431. throw(e);
  2432. }
  2433. };
  2434. /**
  2435. * Encodes a message using the specified data payload.
  2436. * @param {!Object.<string,*>} data Data payload
  2437. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2438. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2439. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2440. * @expose
  2441. */
  2442. Message.encode = function(data, buffer, noVerify) {
  2443. return new Message(data).encode(buffer, noVerify);
  2444. };
  2445. /**
  2446. * Calculates the byte length of the message.
  2447. * @name ProtoBuf.Builder.Message#calculate
  2448. * @function
  2449. * @returns {number} Byte length
  2450. * @throws {Error} If the message cannot be calculated or if required fields are missing.
  2451. * @expose
  2452. */
  2453. MessagePrototype.calculate = function() {
  2454. return T.calculate(this);
  2455. };
  2456. /**
  2457. * Encodes the varint32 length-delimited message.
  2458. * @name ProtoBuf.Builder.Message#encodeDelimited
  2459. * @function
  2460. * @param {(!ByteBuffer|boolean)=} buffer ByteBuffer to encode to. Will create a new one and flip it if omitted.
  2461. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2462. * @return {!ByteBuffer} Encoded message as a ByteBuffer
  2463. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2464. * returns the encoded ByteBuffer in the `encoded` property on the error.
  2465. * @expose
  2466. */
  2467. MessagePrototype.encodeDelimited = function(buffer, noVerify) {
  2468. var isNew = false;
  2469. if (!buffer)
  2470. buffer = new ByteBuffer(),
  2471. isNew = true;
  2472. var enc = new ByteBuffer().LE();
  2473. T.encode(this, enc, noVerify).flip();
  2474. buffer.writeVarint32(enc.remaining());
  2475. buffer.append(enc);
  2476. return isNew ? buffer.flip() : buffer;
  2477. };
  2478. /**
  2479. * Directly encodes the message to an ArrayBuffer.
  2480. * @name ProtoBuf.Builder.Message#encodeAB
  2481. * @function
  2482. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  2483. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2484. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  2485. * @expose
  2486. */
  2487. MessagePrototype.encodeAB = function() {
  2488. try {
  2489. return this.encode().toArrayBuffer();
  2490. } catch (e) {
  2491. if (e["encoded"]) e["encoded"] = e["encoded"].toArrayBuffer();
  2492. throw(e);
  2493. }
  2494. };
  2495. /**
  2496. * Returns the message as an ArrayBuffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeAB}.
  2497. * @name ProtoBuf.Builder.Message#toArrayBuffer
  2498. * @function
  2499. * @return {ArrayBuffer} Encoded message as ArrayBuffer
  2500. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2501. * returns the encoded ArrayBuffer in the `encoded` property on the error.
  2502. * @expose
  2503. */
  2504. MessagePrototype.toArrayBuffer = MessagePrototype.encodeAB;
  2505. /**
  2506. * Directly encodes the message to a node Buffer.
  2507. * @name ProtoBuf.Builder.Message#encodeNB
  2508. * @function
  2509. * @return {!Buffer}
  2510. * @throws {Error} If the message cannot be encoded, not running under node.js or if required fields are
  2511. * missing. The later still returns the encoded node Buffer in the `encoded` property on the error.
  2512. * @expose
  2513. */
  2514. MessagePrototype.encodeNB = function() {
  2515. try {
  2516. return this.encode().toBuffer();
  2517. } catch (e) {
  2518. if (e["encoded"]) e["encoded"] = e["encoded"].toBuffer();
  2519. throw(e);
  2520. }
  2521. };
  2522. /**
  2523. * Returns the message as a node Buffer. This is an alias for {@link ProtoBuf.Builder.Message#encodeNB}.
  2524. * @name ProtoBuf.Builder.Message#toBuffer
  2525. * @function
  2526. * @return {!Buffer}
  2527. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2528. * returns the encoded node Buffer in the `encoded` property on the error.
  2529. * @expose
  2530. */
  2531. MessagePrototype.toBuffer = MessagePrototype.encodeNB;
  2532. /**
  2533. * Directly encodes the message to a base64 encoded string.
  2534. * @name ProtoBuf.Builder.Message#encode64
  2535. * @function
  2536. * @return {string} Base64 encoded string
  2537. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  2538. * still returns the encoded base64 string in the `encoded` property on the error.
  2539. * @expose
  2540. */
  2541. MessagePrototype.encode64 = function() {
  2542. try {
  2543. return this.encode().toBase64();
  2544. } catch (e) {
  2545. if (e["encoded"]) e["encoded"] = e["encoded"].toBase64();
  2546. throw(e);
  2547. }
  2548. };
  2549. /**
  2550. * Returns the message as a base64 encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encode64}.
  2551. * @name ProtoBuf.Builder.Message#toBase64
  2552. * @function
  2553. * @return {string} Base64 encoded string
  2554. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2555. * returns the encoded base64 string in the `encoded` property on the error.
  2556. * @expose
  2557. */
  2558. MessagePrototype.toBase64 = MessagePrototype.encode64;
  2559. /**
  2560. * Directly encodes the message to a hex encoded string.
  2561. * @name ProtoBuf.Builder.Message#encodeHex
  2562. * @function
  2563. * @return {string} Hex encoded string
  2564. * @throws {Error} If the underlying buffer cannot be encoded or if required fields are missing. The later
  2565. * still returns the encoded hex string in the `encoded` property on the error.
  2566. * @expose
  2567. */
  2568. MessagePrototype.encodeHex = function() {
  2569. try {
  2570. return this.encode().toHex();
  2571. } catch (e) {
  2572. if (e["encoded"]) e["encoded"] = e["encoded"].toHex();
  2573. throw(e);
  2574. }
  2575. };
  2576. /**
  2577. * Returns the message as a hex encoded string. This is an alias for {@link ProtoBuf.Builder.Message#encodeHex}.
  2578. * @name ProtoBuf.Builder.Message#toHex
  2579. * @function
  2580. * @return {string} Hex encoded string
  2581. * @throws {Error} If the message cannot be encoded or if required fields are missing. The later still
  2582. * returns the encoded hex string in the `encoded` property on the error.
  2583. * @expose
  2584. */
  2585. MessagePrototype.toHex = MessagePrototype.encodeHex;
  2586. /**
  2587. * Clones a message object or field value to a raw object.
  2588. * @param {*} obj Object to clone
  2589. * @param {boolean} binaryAsBase64 Whether to include binary data as base64 strings or as a buffer otherwise
  2590. * @param {boolean} longsAsStrings Whether to encode longs as strings
  2591. * @param {!ProtoBuf.Reflect.T=} resolvedType The resolved field type if a field
  2592. * @returns {*} Cloned object
  2593. * @inner
  2594. */
  2595. function cloneRaw(obj, binaryAsBase64, longsAsStrings, resolvedType) {
  2596. if (obj === null || typeof obj !== 'object') {
  2597. // Convert enum values to their respective names
  2598. if (resolvedType && resolvedType instanceof ProtoBuf.Reflect.Enum) {
  2599. var name = ProtoBuf.Reflect.Enum.getName(resolvedType.object, obj);
  2600. if (name !== null)
  2601. return name;
  2602. }
  2603. // Pass-through string, number, boolean, null...
  2604. return obj;
  2605. }
  2606. // Convert ByteBuffers to raw buffer or strings
  2607. if (ByteBuffer.isByteBuffer(obj))
  2608. return binaryAsBase64 ? obj.toBase64() : obj.toBuffer();
  2609. // Convert Longs to proper objects or strings
  2610. if (ProtoBuf.Long.isLong(obj))
  2611. return longsAsStrings ? obj.toString() : ProtoBuf.Long.fromValue(obj);
  2612. var clone;
  2613. // Clone arrays
  2614. if (Array.isArray(obj)) {
  2615. clone = [];
  2616. obj.forEach(function(v, k) {
  2617. clone[k] = cloneRaw(v, binaryAsBase64, longsAsStrings, resolvedType);
  2618. });
  2619. return clone;
  2620. }
  2621. clone = {};
  2622. // Convert maps to objects
  2623. if (obj instanceof ProtoBuf.Map) {
  2624. var it = obj.entries();
  2625. for (var e = it.next(); !e.done; e = it.next())
  2626. clone[obj.keyElem.valueToString(e.value[0])] = cloneRaw(e.value[1], binaryAsBase64, longsAsStrings, obj.valueElem.resolvedType);
  2627. return clone;
  2628. }
  2629. // Everything else is a non-null object
  2630. var type = obj.$type,
  2631. field = undefined;
  2632. for (var i in obj)
  2633. if (obj.hasOwnProperty(i)) {
  2634. if (type && (field = type.getChild(i)))
  2635. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings, field.resolvedType);
  2636. else
  2637. clone[i] = cloneRaw(obj[i], binaryAsBase64, longsAsStrings);
  2638. }
  2639. return clone;
  2640. }
  2641. /**
  2642. * Returns the message's raw payload.
  2643. * @param {boolean=} binaryAsBase64 Whether to include binary data as base64 strings instead of Buffers, defaults to `false`
  2644. * @param {boolean} longsAsStrings Whether to encode longs as strings
  2645. * @returns {Object.<string,*>} Raw payload
  2646. * @expose
  2647. */
  2648. MessagePrototype.toRaw = function(binaryAsBase64, longsAsStrings) {
  2649. return cloneRaw(this, !!binaryAsBase64, !!longsAsStrings, this.$type);
  2650. };
  2651. /**
  2652. * Encodes a message to JSON.
  2653. * @returns {string} JSON string
  2654. * @expose
  2655. */
  2656. MessagePrototype.encodeJSON = function() {
  2657. return JSON.stringify(
  2658. cloneRaw(this,
  2659. /* binary-as-base64 */ true,
  2660. /* longs-as-strings */ true,
  2661. this.$type
  2662. )
  2663. );
  2664. };
  2665. /**
  2666. * Decodes a message from the specified buffer or string.
  2667. * @name ProtoBuf.Builder.Message.decode
  2668. * @function
  2669. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  2670. * @param {(number|string)=} length Message length. Defaults to decode all the remainig data.
  2671. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  2672. * @return {!ProtoBuf.Builder.Message} Decoded message
  2673. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2674. * returns the decoded message with missing fields in the `decoded` property on the error.
  2675. * @expose
  2676. * @see ProtoBuf.Builder.Message.decode64
  2677. * @see ProtoBuf.Builder.Message.decodeHex
  2678. */
  2679. Message.decode = function(buffer, length, enc) {
  2680. if (typeof length === 'string')
  2681. enc = length,
  2682. length = -1;
  2683. if (typeof buffer === 'string')
  2684. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  2685. else if (!ByteBuffer.isByteBuffer(buffer))
  2686. buffer = ByteBuffer.wrap(buffer); // May throw
  2687. var le = buffer.littleEndian;
  2688. try {
  2689. var msg = T.decode(buffer.LE(), length);
  2690. buffer.LE(le);
  2691. return msg;
  2692. } catch (e) {
  2693. buffer.LE(le);
  2694. throw(e);
  2695. }
  2696. };
  2697. /**
  2698. * Decodes a varint32 length-delimited message from the specified buffer or string.
  2699. * @name ProtoBuf.Builder.Message.decodeDelimited
  2700. * @function
  2701. * @param {!ByteBuffer|!ArrayBuffer|!Buffer|string} buffer Buffer to decode from
  2702. * @param {string=} enc Encoding if buffer is a string: hex, utf8 (not recommended), defaults to base64
  2703. * @return {ProtoBuf.Builder.Message} Decoded message or `null` if not enough bytes are available yet
  2704. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2705. * returns the decoded message with missing fields in the `decoded` property on the error.
  2706. * @expose
  2707. */
  2708. Message.decodeDelimited = function(buffer, enc) {
  2709. if (typeof buffer === 'string')
  2710. buffer = ByteBuffer.wrap(buffer, enc ? enc : "base64");
  2711. else if (!ByteBuffer.isByteBuffer(buffer))
  2712. buffer = ByteBuffer.wrap(buffer); // May throw
  2713. if (buffer.remaining() < 1)
  2714. return null;
  2715. var off = buffer.offset,
  2716. len = buffer.readVarint32();
  2717. if (buffer.remaining() < len) {
  2718. buffer.offset = off;
  2719. return null;
  2720. }
  2721. try {
  2722. var msg = T.decode(buffer.slice(buffer.offset, buffer.offset + len).LE());
  2723. buffer.offset += len;
  2724. return msg;
  2725. } catch (err) {
  2726. buffer.offset += len;
  2727. throw err;
  2728. }
  2729. };
  2730. /**
  2731. * Decodes the message from the specified base64 encoded string.
  2732. * @name ProtoBuf.Builder.Message.decode64
  2733. * @function
  2734. * @param {string} str String to decode from
  2735. * @return {!ProtoBuf.Builder.Message} Decoded message
  2736. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2737. * returns the decoded message with missing fields in the `decoded` property on the error.
  2738. * @expose
  2739. */
  2740. Message.decode64 = function(str) {
  2741. return Message.decode(str, "base64");
  2742. };
  2743. /**
  2744. * Decodes the message from the specified hex encoded string.
  2745. * @name ProtoBuf.Builder.Message.decodeHex
  2746. * @function
  2747. * @param {string} str String to decode from
  2748. * @return {!ProtoBuf.Builder.Message} Decoded message
  2749. * @throws {Error} If the message cannot be decoded or if required fields are missing. The later still
  2750. * returns the decoded message with missing fields in the `decoded` property on the error.
  2751. * @expose
  2752. */
  2753. Message.decodeHex = function(str) {
  2754. return Message.decode(str, "hex");
  2755. };
  2756. /**
  2757. * Decodes the message from a JSON string.
  2758. * @name ProtoBuf.Builder.Message.decodeJSON
  2759. * @function
  2760. * @param {string} str String to decode from
  2761. * @return {!ProtoBuf.Builder.Message} Decoded message
  2762. * @throws {Error} If the message cannot be decoded or if required fields are
  2763. * missing.
  2764. * @expose
  2765. */
  2766. Message.decodeJSON = function(str) {
  2767. return new Message(JSON.parse(str));
  2768. };
  2769. // Utility
  2770. /**
  2771. * Returns a string representation of this Message.
  2772. * @name ProtoBuf.Builder.Message#toString
  2773. * @function
  2774. * @return {string} String representation as of ".Fully.Qualified.MessageName"
  2775. * @expose
  2776. */
  2777. MessagePrototype.toString = function() {
  2778. return T.toString();
  2779. };
  2780. // Properties
  2781. /**
  2782. * Message options.
  2783. * @name ProtoBuf.Builder.Message.$options
  2784. * @type {Object.<string,*>}
  2785. * @expose
  2786. */
  2787. var $optionsS; // cc needs this
  2788. /**
  2789. * Message options.
  2790. * @name ProtoBuf.Builder.Message#$options
  2791. * @type {Object.<string,*>}
  2792. * @expose
  2793. */
  2794. var $options;
  2795. /**
  2796. * Reflection type.
  2797. * @name ProtoBuf.Builder.Message.$type
  2798. * @type {!ProtoBuf.Reflect.Message}
  2799. * @expose
  2800. */
  2801. var $typeS;
  2802. /**
  2803. * Reflection type.
  2804. * @name ProtoBuf.Builder.Message#$type
  2805. * @type {!ProtoBuf.Reflect.Message}
  2806. * @expose
  2807. */
  2808. var $type;
  2809. if (Object.defineProperty)
  2810. Object.defineProperty(Message, '$options', { "value": T.buildOpt() }),
  2811. Object.defineProperty(MessagePrototype, "$options", { "value": Message["$options"] }),
  2812. Object.defineProperty(Message, "$type", { "value": T }),
  2813. Object.defineProperty(MessagePrototype, "$type", { "value": T });
  2814. return Message;
  2815. })(ProtoBuf, this);
  2816. // Static enums and prototyped sub-messages / cached collections
  2817. this._fields = [];
  2818. this._fieldsById = {};
  2819. this._fieldsByName = {};
  2820. this._oneofsByName = {};
  2821. for (var i=0, k=this.children.length, child; i<k; i++) {
  2822. child = this.children[i];
  2823. if (child instanceof Enum || child instanceof Message || child instanceof Service) {
  2824. if (clazz.hasOwnProperty(child.name))
  2825. throw Error("Illegal reflect child of "+this.toString(true)+": "+child.toString(true)+" cannot override static property '"+child.name+"'");
  2826. clazz[child.name] = child.build();
  2827. } else if (child instanceof Message.Field)
  2828. child.build(),
  2829. this._fields.push(child),
  2830. this._fieldsById[child.id] = child,
  2831. this._fieldsByName[child.name] = child;
  2832. else if (child instanceof Message.OneOf) {
  2833. this._oneofsByName[child.name] = child;
  2834. }
  2835. else if (!(child instanceof Message.OneOf) && !(child instanceof Extension)) // Not built
  2836. throw Error("Illegal reflect child of "+this.toString(true)+": "+this.children[i].toString(true));
  2837. }
  2838. return this.clazz = clazz;
  2839. };
  2840. /**
  2841. * Encodes a runtime message's contents to the specified buffer.
  2842. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  2843. * @param {ByteBuffer} buffer ByteBuffer to write to
  2844. * @param {boolean=} noVerify Whether to not verify field values, defaults to `false`
  2845. * @return {ByteBuffer} The ByteBuffer for chaining
  2846. * @throws {Error} If required fields are missing or the message cannot be encoded for another reason
  2847. * @expose
  2848. */
  2849. MessagePrototype.encode = function(message, buffer, noVerify) {
  2850. var fieldMissing = null,
  2851. field;
  2852. for (var i=0, k=this._fields.length, val; i<k; ++i) {
  2853. field = this._fields[i];
  2854. val = message[field.name];
  2855. if (field.required && val === null) {
  2856. if (fieldMissing === null)
  2857. fieldMissing = field;
  2858. } else
  2859. field.encode(noVerify ? val : field.verifyValue(val), buffer, message);
  2860. }
  2861. if (fieldMissing !== null) {
  2862. var err = Error("Missing at least one required field for "+this.toString(true)+": "+fieldMissing);
  2863. err["encoded"] = buffer; // Still expose what we got
  2864. throw(err);
  2865. }
  2866. return buffer;
  2867. };
  2868. /**
  2869. * Calculates a runtime message's byte length.
  2870. * @param {!ProtoBuf.Builder.Message} message Runtime message to encode
  2871. * @returns {number} Byte length
  2872. * @throws {Error} If required fields are missing or the message cannot be calculated for another reason
  2873. * @expose
  2874. */
  2875. MessagePrototype.calculate = function(message) {
  2876. for (var n=0, i=0, k=this._fields.length, field, val; i<k; ++i) {
  2877. field = this._fields[i];
  2878. val = message[field.name];
  2879. if (field.required && val === null)
  2880. throw Error("Missing at least one required field for "+this.toString(true)+": "+field);
  2881. else
  2882. n += field.calculate(val, message);
  2883. }
  2884. return n;
  2885. };
  2886. /**
  2887. * Skips all data until the end of the specified group has been reached.
  2888. * @param {number} expectedId Expected GROUPEND id
  2889. * @param {!ByteBuffer} buf ByteBuffer
  2890. * @returns {boolean} `true` if a value as been skipped, `false` if the end has been reached
  2891. * @throws {Error} If it wasn't possible to find the end of the group (buffer overrun or end tag mismatch)
  2892. * @inner
  2893. */
  2894. function skipTillGroupEnd(expectedId, buf) {
  2895. var tag = buf.readVarint32(), // Throws on OOB
  2896. wireType = tag & 0x07,
  2897. id = tag >>> 3;
  2898. switch (wireType) {
  2899. case ProtoBuf.WIRE_TYPES.VARINT:
  2900. do tag = buf.readUint8();
  2901. while ((tag & 0x80) === 0x80);
  2902. break;
  2903. case ProtoBuf.WIRE_TYPES.BITS64:
  2904. buf.offset += 8;
  2905. break;
  2906. case ProtoBuf.WIRE_TYPES.LDELIM:
  2907. tag = buf.readVarint32(); // reads the varint
  2908. buf.offset += tag; // skips n bytes
  2909. break;
  2910. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2911. skipTillGroupEnd(id, buf);
  2912. break;
  2913. case ProtoBuf.WIRE_TYPES.ENDGROUP:
  2914. if (id === expectedId)
  2915. return false;
  2916. else
  2917. throw Error("Illegal GROUPEND after unknown group: "+id+" ("+expectedId+" expected)");
  2918. case ProtoBuf.WIRE_TYPES.BITS32:
  2919. buf.offset += 4;
  2920. break;
  2921. default:
  2922. throw Error("Illegal wire type in unknown group "+expectedId+": "+wireType);
  2923. }
  2924. return true;
  2925. }
  2926. /**
  2927. * Decodes an encoded message and returns the decoded message.
  2928. * @param {ByteBuffer} buffer ByteBuffer to decode from
  2929. * @param {number=} length Message length. Defaults to decode all remaining data.
  2930. * @param {number=} expectedGroupEndId Expected GROUPEND id if this is a legacy group
  2931. * @return {ProtoBuf.Builder.Message} Decoded message
  2932. * @throws {Error} If the message cannot be decoded
  2933. * @expose
  2934. */
  2935. MessagePrototype.decode = function(buffer, length, expectedGroupEndId) {
  2936. if (typeof length !== 'number')
  2937. length = -1;
  2938. var start = buffer.offset,
  2939. msg = new (this.clazz)(),
  2940. tag, wireType, id, field;
  2941. while (buffer.offset < start+length || (length === -1 && buffer.remaining() > 0)) {
  2942. tag = buffer.readVarint32();
  2943. wireType = tag & 0x07;
  2944. id = tag >>> 3;
  2945. if (wireType === ProtoBuf.WIRE_TYPES.ENDGROUP) {
  2946. if (id !== expectedGroupEndId)
  2947. throw Error("Illegal group end indicator for "+this.toString(true)+": "+id+" ("+(expectedGroupEndId ? expectedGroupEndId+" expected" : "not a group")+")");
  2948. break;
  2949. }
  2950. if (!(field = this._fieldsById[id])) {
  2951. // "messages created by your new code can be parsed by your old code: old binaries simply ignore the new field when parsing."
  2952. switch (wireType) {
  2953. case ProtoBuf.WIRE_TYPES.VARINT:
  2954. buffer.readVarint32();
  2955. break;
  2956. case ProtoBuf.WIRE_TYPES.BITS32:
  2957. buffer.offset += 4;
  2958. break;
  2959. case ProtoBuf.WIRE_TYPES.BITS64:
  2960. buffer.offset += 8;
  2961. break;
  2962. case ProtoBuf.WIRE_TYPES.LDELIM:
  2963. var len = buffer.readVarint32();
  2964. buffer.offset += len;
  2965. break;
  2966. case ProtoBuf.WIRE_TYPES.STARTGROUP:
  2967. while (skipTillGroupEnd(id, buffer)) {}
  2968. break;
  2969. default:
  2970. throw Error("Illegal wire type for unknown field "+id+" in "+this.toString(true)+"#decode: "+wireType);
  2971. }
  2972. continue;
  2973. }
  2974. if (field.repeated && !field.options["packed"]) {
  2975. msg[field.name].push(field.decode(wireType, buffer));
  2976. } else if (field.map) {
  2977. var keyval = field.decode(wireType, buffer);
  2978. msg[field.name].set(keyval[0], keyval[1]);
  2979. } else {
  2980. msg[field.name] = field.decode(wireType, buffer);
  2981. if (field.oneof) { // Field is part of an OneOf (not a virtual OneOf field)
  2982. var currentField = msg[field.oneof.name]; // Virtual field references currently set field
  2983. if (currentField !== null && currentField !== field.name)
  2984. msg[currentField] = null; // Clear currently set field
  2985. msg[field.oneof.name] = field.name; // Point virtual field at this field
  2986. }
  2987. }
  2988. }
  2989. // Check if all required fields are present and set default values for optional fields that are not
  2990. for (var i=0, k=this._fields.length; i<k; ++i) {
  2991. field = this._fields[i];
  2992. if (msg[field.name] === null) {
  2993. if (this.syntax === "proto3") { // Proto3 sets default values by specification
  2994. msg[field.name] = field.defaultValue;
  2995. } else if (field.required) {
  2996. var err = Error("Missing at least one required field for " + this.toString(true) + ": " + field.name);
  2997. err["decoded"] = msg; // Still expose what we got
  2998. throw(err);
  2999. } else if (ProtoBuf.populateDefaults && field.defaultValue !== null)
  3000. msg[field.name] = field.defaultValue;
  3001. }
  3002. }
  3003. return msg;
  3004. };
  3005. /**
  3006. * @alias ProtoBuf.Reflect.Message
  3007. * @expose
  3008. */
  3009. Reflect.Message = Message;
  3010. /**
  3011. * Constructs a new Message Field.
  3012. * @exports ProtoBuf.Reflect.Message.Field
  3013. * @param {!ProtoBuf.Builder} builder Builder reference
  3014. * @param {!ProtoBuf.Reflect.Message} message Message reference
  3015. * @param {string} rule Rule, one of requried, optional, repeated
  3016. * @param {string?} keytype Key data type, if any.
  3017. * @param {string} type Data type, e.g. int32
  3018. * @param {string} name Field name
  3019. * @param {number} id Unique field id
  3020. * @param {Object.<string,*>=} options Options
  3021. * @param {!ProtoBuf.Reflect.Message.OneOf=} oneof Enclosing OneOf
  3022. * @param {string?} syntax The syntax level of this definition (e.g., proto3)
  3023. * @constructor
  3024. * @extends ProtoBuf.Reflect.T
  3025. */
  3026. var Field = function(builder, message, rule, keytype, type, name, id, options, oneof, syntax) {
  3027. T.call(this, builder, message, name);
  3028. /**
  3029. * @override
  3030. */
  3031. this.className = "Message.Field";
  3032. /**
  3033. * Message field required flag.
  3034. * @type {boolean}
  3035. * @expose
  3036. */
  3037. this.required = rule === "required";
  3038. /**
  3039. * Message field repeated flag.
  3040. * @type {boolean}
  3041. * @expose
  3042. */
  3043. this.repeated = rule === "repeated";
  3044. /**
  3045. * Message field map flag.
  3046. * @type {boolean}
  3047. * @expose
  3048. */
  3049. this.map = rule === "map";
  3050. /**
  3051. * Message field key type. Type reference string if unresolved, protobuf
  3052. * type if resolved. Valid only if this.map === true, null otherwise.
  3053. * @type {string|{name: string, wireType: number}|null}
  3054. * @expose
  3055. */
  3056. this.keyType = keytype || null;
  3057. /**
  3058. * Message field type. Type reference string if unresolved, protobuf type if
  3059. * resolved. In a map field, this is the value type.
  3060. * @type {string|{name: string, wireType: number}}
  3061. * @expose
  3062. */
  3063. this.type = type;
  3064. /**
  3065. * Resolved type reference inside the global namespace.
  3066. * @type {ProtoBuf.Reflect.T|null}
  3067. * @expose
  3068. */
  3069. this.resolvedType = null;
  3070. /**
  3071. * Unique message field id.
  3072. * @type {number}
  3073. * @expose
  3074. */
  3075. this.id = id;
  3076. /**
  3077. * Message field options.
  3078. * @type {!Object.<string,*>}
  3079. * @dict
  3080. * @expose
  3081. */
  3082. this.options = options || {};
  3083. /**
  3084. * Default value.
  3085. * @type {*}
  3086. * @expose
  3087. */
  3088. this.defaultValue = null;
  3089. /**
  3090. * Enclosing OneOf.
  3091. * @type {?ProtoBuf.Reflect.Message.OneOf}
  3092. * @expose
  3093. */
  3094. this.oneof = oneof || null;
  3095. /**
  3096. * Syntax level of this definition (e.g., proto3).
  3097. * @type {string}
  3098. * @expose
  3099. */
  3100. this.syntax = syntax || 'proto2';
  3101. /**
  3102. * Original field name.
  3103. * @type {string}
  3104. * @expose
  3105. */
  3106. this.originalName = this.name; // Used to revert camelcase transformation on naming collisions
  3107. /**
  3108. * Element implementation. Created in build() after types are resolved.
  3109. * @type {ProtoBuf.Element}
  3110. * @expose
  3111. */
  3112. this.element = null;
  3113. /**
  3114. * Key element implementation, for map fields. Created in build() after
  3115. * types are resolved.
  3116. * @type {ProtoBuf.Element}
  3117. * @expose
  3118. */
  3119. this.keyElement = null;
  3120. // Convert field names to camel case notation if the override is set
  3121. if (this.builder.options['convertFieldsToCamelCase'] && !(this instanceof Message.ExtensionField))
  3122. this.name = ProtoBuf.Util.toCamelCase(this.name);
  3123. };
  3124. /**
  3125. * @alias ProtoBuf.Reflect.Message.Field.prototype
  3126. * @inner
  3127. */
  3128. var FieldPrototype = Field.prototype = Object.create(T.prototype);
  3129. /**
  3130. * Builds the field.
  3131. * @override
  3132. * @expose
  3133. */
  3134. FieldPrototype.build = function() {
  3135. this.element = new Element(this.type, this.resolvedType, false, this.syntax, this.name);
  3136. if (this.map)
  3137. this.keyElement = new Element(this.keyType, undefined, true, this.syntax, this.name);
  3138. // In proto3, fields do not have field presence, and every field is set to
  3139. // its type's default value ("", 0, 0.0, or false).
  3140. if (this.syntax === 'proto3' && !this.repeated && !this.map)
  3141. this.defaultValue = Element.defaultFieldValue(this.type);
  3142. // Otherwise, default values are present when explicitly specified
  3143. else if (typeof this.options['default'] !== 'undefined')
  3144. this.defaultValue = this.verifyValue(this.options['default']);
  3145. };
  3146. /**
  3147. * Checks if the given value can be set for this field.
  3148. * @param {*} value Value to check
  3149. * @param {boolean=} skipRepeated Whether to skip the repeated value check or not. Defaults to false.
  3150. * @return {*} Verified, maybe adjusted, value
  3151. * @throws {Error} If the value cannot be set for this field
  3152. * @expose
  3153. */
  3154. FieldPrototype.verifyValue = function(value, skipRepeated) {
  3155. skipRepeated = skipRepeated || false;
  3156. var self = this;
  3157. function fail(val, msg) {
  3158. throw Error("Illegal value for "+self.toString(true)+" of type "+self.type.name+": "+val+" ("+msg+")");
  3159. }
  3160. if (value === null) { // NULL values for optional fields
  3161. if (this.required)
  3162. fail(typeof value, "required");
  3163. if (this.syntax === 'proto3' && this.type !== ProtoBuf.TYPES["message"])
  3164. fail(typeof value, "proto3 field without field presence cannot be null");
  3165. return null;
  3166. }
  3167. var i;
  3168. if (this.repeated && !skipRepeated) { // Repeated values as arrays
  3169. if (!Array.isArray(value))
  3170. value = [value];
  3171. var res = [];
  3172. for (i=0; i<value.length; i++)
  3173. res.push(this.element.verifyValue(value[i]));
  3174. return res;
  3175. }
  3176. if (this.map && !skipRepeated) { // Map values as objects
  3177. if (!(value instanceof ProtoBuf.Map)) {
  3178. // If not already a Map, attempt to convert.
  3179. if (!(value instanceof Object)) {
  3180. fail(typeof value,
  3181. "expected ProtoBuf.Map or raw object for map field");
  3182. }
  3183. return new ProtoBuf.Map(this, value);
  3184. } else {
  3185. return value;
  3186. }
  3187. }
  3188. // All non-repeated fields expect no array
  3189. if (!this.repeated && Array.isArray(value))
  3190. fail(typeof value, "no array expected");
  3191. return this.element.verifyValue(value);
  3192. };
  3193. /**
  3194. * Determines whether the field will have a presence on the wire given its
  3195. * value.
  3196. * @param {*} value Verified field value
  3197. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3198. * @return {boolean} Whether the field will be present on the wire
  3199. */
  3200. FieldPrototype.hasWirePresence = function(value, message) {
  3201. if (this.syntax !== 'proto3')
  3202. return (value !== null);
  3203. if (this.oneof && message[this.oneof.name] === this.name)
  3204. return true;
  3205. switch (this.type) {
  3206. case ProtoBuf.TYPES["int32"]:
  3207. case ProtoBuf.TYPES["sint32"]:
  3208. case ProtoBuf.TYPES["sfixed32"]:
  3209. case ProtoBuf.TYPES["uint32"]:
  3210. case ProtoBuf.TYPES["fixed32"]:
  3211. return value !== 0;
  3212. case ProtoBuf.TYPES["int64"]:
  3213. case ProtoBuf.TYPES["sint64"]:
  3214. case ProtoBuf.TYPES["sfixed64"]:
  3215. case ProtoBuf.TYPES["uint64"]:
  3216. case ProtoBuf.TYPES["fixed64"]:
  3217. return value.low !== 0 || value.high !== 0;
  3218. case ProtoBuf.TYPES["bool"]:
  3219. return value;
  3220. case ProtoBuf.TYPES["float"]:
  3221. case ProtoBuf.TYPES["double"]:
  3222. return value !== 0.0;
  3223. case ProtoBuf.TYPES["string"]:
  3224. return value.length > 0;
  3225. case ProtoBuf.TYPES["bytes"]:
  3226. return value.remaining() > 0;
  3227. case ProtoBuf.TYPES["enum"]:
  3228. return value !== 0;
  3229. case ProtoBuf.TYPES["message"]:
  3230. return value !== null;
  3231. default:
  3232. return true;
  3233. }
  3234. };
  3235. /**
  3236. * Encodes the specified field value to the specified buffer.
  3237. * @param {*} value Verified field value
  3238. * @param {ByteBuffer} buffer ByteBuffer to encode to
  3239. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3240. * @return {ByteBuffer} The ByteBuffer for chaining
  3241. * @throws {Error} If the field cannot be encoded
  3242. * @expose
  3243. */
  3244. FieldPrototype.encode = function(value, buffer, message) {
  3245. if (this.type === null || typeof this.type !== 'object')
  3246. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  3247. if (value === null || (this.repeated && value.length == 0))
  3248. return buffer; // Optional omitted
  3249. try {
  3250. if (this.repeated) {
  3251. var i;
  3252. // "Only repeated fields of primitive numeric types (types which use the varint, 32-bit, or 64-bit wire
  3253. // types) can be declared 'packed'."
  3254. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3255. // "All of the elements of the field are packed into a single key-value pair with wire type 2
  3256. // (length-delimited). Each element is encoded the same way it would be normally, except without a
  3257. // tag preceding it."
  3258. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3259. buffer.ensureCapacity(buffer.offset += 1); // We do not know the length yet, so let's assume a varint of length 1
  3260. var start = buffer.offset; // Remember where the contents begin
  3261. for (i=0; i<value.length; i++)
  3262. this.element.encodeValue(this.id, value[i], buffer);
  3263. var len = buffer.offset-start,
  3264. varintLen = ByteBuffer.calculateVarint32(len);
  3265. if (varintLen > 1) { // We need to move the contents
  3266. var contents = buffer.slice(start, buffer.offset);
  3267. start += varintLen-1;
  3268. buffer.offset = start;
  3269. buffer.append(contents);
  3270. }
  3271. buffer.writeVarint32(len, start-varintLen);
  3272. } else {
  3273. // "If your message definition has repeated elements (without the [packed=true] option), the encoded
  3274. // message has zero or more key-value pairs with the same tag number"
  3275. for (i=0; i<value.length; i++)
  3276. buffer.writeVarint32((this.id << 3) | this.type.wireType),
  3277. this.element.encodeValue(this.id, value[i], buffer);
  3278. }
  3279. } else if (this.map) {
  3280. // Write out each map entry as a submessage.
  3281. value.forEach(function(val, key, m) {
  3282. // Compute the length of the submessage (key, val) pair.
  3283. var length =
  3284. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  3285. this.keyElement.calculateLength(1, key) +
  3286. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  3287. this.element.calculateLength(2, val);
  3288. // Submessage with wire type of length-delimited.
  3289. buffer.writeVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3290. buffer.writeVarint32(length);
  3291. // Write out the key and val.
  3292. buffer.writeVarint32((1 << 3) | this.keyType.wireType);
  3293. this.keyElement.encodeValue(1, key, buffer);
  3294. buffer.writeVarint32((2 << 3) | this.type.wireType);
  3295. this.element.encodeValue(2, val, buffer);
  3296. }, this);
  3297. } else {
  3298. if (this.hasWirePresence(value, message)) {
  3299. buffer.writeVarint32((this.id << 3) | this.type.wireType);
  3300. this.element.encodeValue(this.id, value, buffer);
  3301. }
  3302. }
  3303. } catch (e) {
  3304. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  3305. }
  3306. return buffer;
  3307. };
  3308. /**
  3309. * Calculates the length of this field's value on the network level.
  3310. * @param {*} value Field value
  3311. * @param {!ProtoBuf.Builder.Message} message Runtime message
  3312. * @returns {number} Byte length
  3313. * @expose
  3314. */
  3315. FieldPrototype.calculate = function(value, message) {
  3316. value = this.verifyValue(value); // May throw
  3317. if (this.type === null || typeof this.type !== 'object')
  3318. throw Error("[INTERNAL] Unresolved type in "+this.toString(true)+": "+this.type);
  3319. if (value === null || (this.repeated && value.length == 0))
  3320. return 0; // Optional omitted
  3321. var n = 0;
  3322. try {
  3323. if (this.repeated) {
  3324. var i, ni;
  3325. if (this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3326. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3327. ni = 0;
  3328. for (i=0; i<value.length; i++)
  3329. ni += this.element.calculateLength(this.id, value[i]);
  3330. n += ByteBuffer.calculateVarint32(ni);
  3331. n += ni;
  3332. } else {
  3333. for (i=0; i<value.length; i++)
  3334. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType),
  3335. n += this.element.calculateLength(this.id, value[i]);
  3336. }
  3337. } else if (this.map) {
  3338. // Each map entry becomes a submessage.
  3339. value.forEach(function(val, key, m) {
  3340. // Compute the length of the submessage (key, val) pair.
  3341. var length =
  3342. ByteBuffer.calculateVarint32((1 << 3) | this.keyType.wireType) +
  3343. this.keyElement.calculateLength(1, key) +
  3344. ByteBuffer.calculateVarint32((2 << 3) | this.type.wireType) +
  3345. this.element.calculateLength(2, val);
  3346. n += ByteBuffer.calculateVarint32((this.id << 3) | ProtoBuf.WIRE_TYPES.LDELIM);
  3347. n += ByteBuffer.calculateVarint32(length);
  3348. n += length;
  3349. }, this);
  3350. } else {
  3351. if (this.hasWirePresence(value, message)) {
  3352. n += ByteBuffer.calculateVarint32((this.id << 3) | this.type.wireType);
  3353. n += this.element.calculateLength(this.id, value);
  3354. }
  3355. }
  3356. } catch (e) {
  3357. throw Error("Illegal value for "+this.toString(true)+": "+value+" ("+e+")");
  3358. }
  3359. return n;
  3360. };
  3361. /**
  3362. * Decode the field value from the specified buffer.
  3363. * @param {number} wireType Leading wire type
  3364. * @param {ByteBuffer} buffer ByteBuffer to decode from
  3365. * @param {boolean=} skipRepeated Whether to skip the repeated check or not. Defaults to false.
  3366. * @return {*} Decoded value: array for packed repeated fields, [key, value] for
  3367. * map fields, or an individual value otherwise.
  3368. * @throws {Error} If the field cannot be decoded
  3369. * @expose
  3370. */
  3371. FieldPrototype.decode = function(wireType, buffer, skipRepeated) {
  3372. var value, nBytes;
  3373. // We expect wireType to match the underlying type's wireType unless we see
  3374. // a packed repeated field, or unless this is a map field.
  3375. var wireTypeOK =
  3376. (!this.map && wireType == this.type.wireType) ||
  3377. (!skipRepeated && this.repeated && this.options["packed"] &&
  3378. wireType == ProtoBuf.WIRE_TYPES.LDELIM) ||
  3379. (this.map && wireType == ProtoBuf.WIRE_TYPES.LDELIM);
  3380. if (!wireTypeOK)
  3381. throw Error("Illegal wire type for field "+this.toString(true)+": "+wireType+" ("+this.type.wireType+" expected)");
  3382. // Handle packed repeated fields.
  3383. if (wireType == ProtoBuf.WIRE_TYPES.LDELIM && this.repeated && this.options["packed"] && ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) {
  3384. if (!skipRepeated) {
  3385. nBytes = buffer.readVarint32();
  3386. nBytes = buffer.offset + nBytes; // Limit
  3387. var values = [];
  3388. while (buffer.offset < nBytes)
  3389. values.push(this.decode(this.type.wireType, buffer, true));
  3390. return values;
  3391. }
  3392. // Read the next value otherwise...
  3393. }
  3394. // Handle maps.
  3395. if (this.map) {
  3396. // Read one (key, value) submessage, and return [key, value]
  3397. var key = Element.defaultFieldValue(this.keyType);
  3398. value = Element.defaultFieldValue(this.type);
  3399. // Read the length
  3400. nBytes = buffer.readVarint32();
  3401. if (buffer.remaining() < nBytes)
  3402. throw Error("Illegal number of bytes for "+this.toString(true)+": "+nBytes+" required but got only "+buffer.remaining());
  3403. // Get a sub-buffer of this key/value submessage
  3404. var msgbuf = buffer.clone();
  3405. msgbuf.limit = msgbuf.offset + nBytes;
  3406. buffer.offset += nBytes;
  3407. while (msgbuf.remaining() > 0) {
  3408. var tag = msgbuf.readVarint32();
  3409. wireType = tag & 0x07;
  3410. var id = tag >>> 3;
  3411. if (id === 1) {
  3412. key = this.keyElement.decode(msgbuf, wireType, id);
  3413. } else if (id === 2) {
  3414. value = this.element.decode(msgbuf, wireType, id);
  3415. } else {
  3416. throw Error("Unexpected tag in map field key/value submessage");
  3417. }
  3418. }
  3419. return [key, value];
  3420. }
  3421. // Handle singular and non-packed repeated field values.
  3422. return this.element.decode(buffer, wireType, this.id);
  3423. };
  3424. /**
  3425. * @alias ProtoBuf.Reflect.Message.Field
  3426. * @expose
  3427. */
  3428. Reflect.Message.Field = Field;
  3429. /**
  3430. * Constructs a new Message ExtensionField.
  3431. * @exports ProtoBuf.Reflect.Message.ExtensionField
  3432. * @param {!ProtoBuf.Builder} builder Builder reference
  3433. * @param {!ProtoBuf.Reflect.Message} message Message reference
  3434. * @param {string} rule Rule, one of requried, optional, repeated
  3435. * @param {string} type Data type, e.g. int32
  3436. * @param {string} name Field name
  3437. * @param {number} id Unique field id
  3438. * @param {!Object.<string,*>=} options Options
  3439. * @constructor
  3440. * @extends ProtoBuf.Reflect.Message.Field
  3441. */
  3442. var ExtensionField = function(builder, message, rule, type, name, id, options) {
  3443. Field.call(this, builder, message, rule, /* keytype = */ null, type, name, id, options);
  3444. /**
  3445. * Extension reference.
  3446. * @type {!ProtoBuf.Reflect.Extension}
  3447. * @expose
  3448. */
  3449. this.extension;
  3450. };
  3451. // Extends Field
  3452. ExtensionField.prototype = Object.create(Field.prototype);
  3453. /**
  3454. * @alias ProtoBuf.Reflect.Message.ExtensionField
  3455. * @expose
  3456. */
  3457. Reflect.Message.ExtensionField = ExtensionField;
  3458. /**
  3459. * Constructs a new Message OneOf.
  3460. * @exports ProtoBuf.Reflect.Message.OneOf
  3461. * @param {!ProtoBuf.Builder} builder Builder reference
  3462. * @param {!ProtoBuf.Reflect.Message} message Message reference
  3463. * @param {string} name OneOf name
  3464. * @constructor
  3465. * @extends ProtoBuf.Reflect.T
  3466. */
  3467. var OneOf = function(builder, message, name) {
  3468. T.call(this, builder, message, name);
  3469. /**
  3470. * Enclosed fields.
  3471. * @type {!Array.<!ProtoBuf.Reflect.Message.Field>}
  3472. * @expose
  3473. */
  3474. this.fields = [];
  3475. };
  3476. /**
  3477. * @alias ProtoBuf.Reflect.Message.OneOf
  3478. * @expose
  3479. */
  3480. Reflect.Message.OneOf = OneOf;
  3481. /**
  3482. * Constructs a new Enum.
  3483. * @exports ProtoBuf.Reflect.Enum
  3484. * @param {!ProtoBuf.Builder} builder Builder reference
  3485. * @param {!ProtoBuf.Reflect.T} parent Parent Reflect object
  3486. * @param {string} name Enum name
  3487. * @param {Object.<string,*>=} options Enum options
  3488. * @param {string?} syntax The syntax level (e.g., proto3)
  3489. * @constructor
  3490. * @extends ProtoBuf.Reflect.Namespace
  3491. */
  3492. var Enum = function(builder, parent, name, options, syntax) {
  3493. Namespace.call(this, builder, parent, name, options, syntax);
  3494. /**
  3495. * @override
  3496. */
  3497. this.className = "Enum";
  3498. /**
  3499. * Runtime enum object.
  3500. * @type {Object.<string,number>|null}
  3501. * @expose
  3502. */
  3503. this.object = null;
  3504. };
  3505. /**
  3506. * Gets the string name of an enum value.
  3507. * @param {!ProtoBuf.Builder.Enum} enm Runtime enum
  3508. * @param {number} value Enum value
  3509. * @returns {?string} Name or `null` if not present
  3510. * @expose
  3511. */
  3512. Enum.getName = function(enm, value) {
  3513. var keys = Object.keys(enm);
  3514. for (var i=0, key; i<keys.length; ++i)
  3515. if (enm[key = keys[i]] === value)
  3516. return key;
  3517. return null;
  3518. };
  3519. /**
  3520. * @alias ProtoBuf.Reflect.Enum.prototype
  3521. * @inner
  3522. */
  3523. var EnumPrototype = Enum.prototype = Object.create(Namespace.prototype);
  3524. /**
  3525. * Builds this enum and returns the runtime counterpart.
  3526. * @param {boolean} rebuild Whether to rebuild or not, defaults to false
  3527. * @returns {!Object.<string,number>}
  3528. * @expose
  3529. */
  3530. EnumPrototype.build = function(rebuild) {
  3531. if (this.object && !rebuild)
  3532. return this.object;
  3533. var enm = new ProtoBuf.Builder.Enum(),
  3534. values = this.getChildren(Enum.Value);
  3535. for (var i=0, k=values.length; i<k; ++i)
  3536. enm[values[i]['name']] = values[i]['id'];
  3537. if (Object.defineProperty)
  3538. Object.defineProperty(enm, '$options', {
  3539. "value": this.buildOpt(),
  3540. "enumerable": false
  3541. });
  3542. return this.object = enm;
  3543. };
  3544. /**
  3545. * @alias ProtoBuf.Reflect.Enum
  3546. * @expose
  3547. */
  3548. Reflect.Enum = Enum;
  3549. /**
  3550. * Constructs a new Enum Value.
  3551. * @exports ProtoBuf.Reflect.Enum.Value
  3552. * @param {!ProtoBuf.Builder} builder Builder reference
  3553. * @param {!ProtoBuf.Reflect.Enum} enm Enum reference
  3554. * @param {string} name Field name
  3555. * @param {number} id Unique field id
  3556. * @constructor
  3557. * @extends ProtoBuf.Reflect.T
  3558. */
  3559. var Value = function(builder, enm, name, id) {
  3560. T.call(this, builder, enm, name);
  3561. /**
  3562. * @override
  3563. */
  3564. this.className = "Enum.Value";
  3565. /**
  3566. * Unique enum value id.
  3567. * @type {number}
  3568. * @expose
  3569. */
  3570. this.id = id;
  3571. };
  3572. // Extends T
  3573. Value.prototype = Object.create(T.prototype);
  3574. /**
  3575. * @alias ProtoBuf.Reflect.Enum.Value
  3576. * @expose
  3577. */
  3578. Reflect.Enum.Value = Value;
  3579. /**
  3580. * An extension (field).
  3581. * @exports ProtoBuf.Reflect.Extension
  3582. * @constructor
  3583. * @param {!ProtoBuf.Builder} builder Builder reference
  3584. * @param {!ProtoBuf.Reflect.T} parent Parent object
  3585. * @param {string} name Object name
  3586. * @param {!ProtoBuf.Reflect.Message.Field} field Extension field
  3587. */
  3588. var Extension = function(builder, parent, name, field) {
  3589. T.call(this, builder, parent, name);
  3590. /**
  3591. * Extended message field.
  3592. * @type {!ProtoBuf.Reflect.Message.Field}
  3593. * @expose
  3594. */
  3595. this.field = field;
  3596. };
  3597. // Extends T
  3598. Extension.prototype = Object.create(T.prototype);
  3599. /**
  3600. * @alias ProtoBuf.Reflect.Extension
  3601. * @expose
  3602. */
  3603. Reflect.Extension = Extension;
  3604. /**
  3605. * Constructs a new Service.
  3606. * @exports ProtoBuf.Reflect.Service
  3607. * @param {!ProtoBuf.Builder} builder Builder reference
  3608. * @param {!ProtoBuf.Reflect.Namespace} root Root
  3609. * @param {string} name Service name
  3610. * @param {Object.<string,*>=} options Options
  3611. * @constructor
  3612. * @extends ProtoBuf.Reflect.Namespace
  3613. */
  3614. var Service = function(builder, root, name, options) {
  3615. Namespace.call(this, builder, root, name, options);
  3616. /**
  3617. * @override
  3618. */
  3619. this.className = "Service";
  3620. /**
  3621. * Built runtime service class.
  3622. * @type {?function(new:ProtoBuf.Builder.Service)}
  3623. */
  3624. this.clazz = null;
  3625. };
  3626. /**
  3627. * @alias ProtoBuf.Reflect.Service.prototype
  3628. * @inner
  3629. */
  3630. var ServicePrototype = Service.prototype = Object.create(Namespace.prototype);
  3631. /**
  3632. * Builds the service and returns the runtime counterpart, which is a fully functional class.
  3633. * @see ProtoBuf.Builder.Service
  3634. * @param {boolean=} rebuild Whether to rebuild or not
  3635. * @return {Function} Service class
  3636. * @throws {Error} If the message cannot be built
  3637. * @expose
  3638. */
  3639. ServicePrototype.build = function(rebuild) {
  3640. if (this.clazz && !rebuild)
  3641. return this.clazz;
  3642. // Create the runtime Service class in its own scope
  3643. return this.clazz = (function(ProtoBuf, T) {
  3644. /**
  3645. * Constructs a new runtime Service.
  3646. * @name ProtoBuf.Builder.Service
  3647. * @param {function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))=} rpcImpl RPC implementation receiving the method name and the message
  3648. * @class Barebone of all runtime services.
  3649. * @constructor
  3650. * @throws {Error} If the service cannot be created
  3651. */
  3652. var Service = function(rpcImpl) {
  3653. ProtoBuf.Builder.Service.call(this);
  3654. /**
  3655. * Service implementation.
  3656. * @name ProtoBuf.Builder.Service#rpcImpl
  3657. * @type {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))}
  3658. * @expose
  3659. */
  3660. this.rpcImpl = rpcImpl || function(name, msg, callback) {
  3661. // This is what a user has to implement: A function receiving the method name, the actual message to
  3662. // send (type checked) and the callback that's either provided with the error as its first
  3663. // argument or null and the actual response message.
  3664. setTimeout(callback.bind(this, Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")), 0); // Must be async!
  3665. };
  3666. };
  3667. /**
  3668. * @alias ProtoBuf.Builder.Service.prototype
  3669. * @inner
  3670. */
  3671. var ServicePrototype = Service.prototype = Object.create(ProtoBuf.Builder.Service.prototype);
  3672. /**
  3673. * Asynchronously performs an RPC call using the given RPC implementation.
  3674. * @name ProtoBuf.Builder.Service.[Method]
  3675. * @function
  3676. * @param {!function(string, ProtoBuf.Builder.Message, function(Error, ProtoBuf.Builder.Message=))} rpcImpl RPC implementation
  3677. * @param {ProtoBuf.Builder.Message} req Request
  3678. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  3679. * the error if any and the response either as a pre-parsed message or as its raw bytes
  3680. * @abstract
  3681. */
  3682. /**
  3683. * Asynchronously performs an RPC call using the instance's RPC implementation.
  3684. * @name ProtoBuf.Builder.Service#[Method]
  3685. * @function
  3686. * @param {ProtoBuf.Builder.Message} req Request
  3687. * @param {function(Error, (ProtoBuf.Builder.Message|ByteBuffer|Buffer|string)=)} callback Callback receiving
  3688. * the error if any and the response either as a pre-parsed message or as its raw bytes
  3689. * @abstract
  3690. */
  3691. var rpc = T.getChildren(ProtoBuf.Reflect.Service.RPCMethod);
  3692. for (var i=0; i<rpc.length; i++) {
  3693. (function(method) {
  3694. // service#Method(message, callback)
  3695. ServicePrototype[method.name] = function(req, callback) {
  3696. try {
  3697. try {
  3698. // If given as a buffer, decode the request. Will throw a TypeError if not a valid buffer.
  3699. req = method.resolvedRequestType.clazz.decode(ByteBuffer.wrap(req));
  3700. } catch (err) {
  3701. if (!(err instanceof TypeError))
  3702. throw err;
  3703. }
  3704. if (req === null || typeof req !== 'object')
  3705. throw Error("Illegal arguments");
  3706. if (!(req instanceof method.resolvedRequestType.clazz))
  3707. req = new method.resolvedRequestType.clazz(req);
  3708. this.rpcImpl(method.fqn(), req, function(err, res) { // Assumes that this is properly async
  3709. if (err) {
  3710. callback(err);
  3711. return;
  3712. }
  3713. // Coalesce to empty string when service response has empty content
  3714. if (res === null)
  3715. res = ''
  3716. try { res = method.resolvedResponseType.clazz.decode(res); } catch (notABuffer) {}
  3717. if (!res || !(res instanceof method.resolvedResponseType.clazz)) {
  3718. callback(Error("Illegal response type received in service method "+ T.name+"#"+method.name));
  3719. return;
  3720. }
  3721. callback(null, res);
  3722. });
  3723. } catch (err) {
  3724. setTimeout(callback.bind(this, err), 0);
  3725. }
  3726. };
  3727. // Service.Method(rpcImpl, message, callback)
  3728. Service[method.name] = function(rpcImpl, req, callback) {
  3729. new Service(rpcImpl)[method.name](req, callback);
  3730. };
  3731. if (Object.defineProperty)
  3732. Object.defineProperty(Service[method.name], "$options", { "value": method.buildOpt() }),
  3733. Object.defineProperty(ServicePrototype[method.name], "$options", { "value": Service[method.name]["$options"] });
  3734. })(rpc[i]);
  3735. }
  3736. // Properties
  3737. /**
  3738. * Service options.
  3739. * @name ProtoBuf.Builder.Service.$options
  3740. * @type {Object.<string,*>}
  3741. * @expose
  3742. */
  3743. var $optionsS; // cc needs this
  3744. /**
  3745. * Service options.
  3746. * @name ProtoBuf.Builder.Service#$options
  3747. * @type {Object.<string,*>}
  3748. * @expose
  3749. */
  3750. var $options;
  3751. /**
  3752. * Reflection type.
  3753. * @name ProtoBuf.Builder.Service.$type
  3754. * @type {!ProtoBuf.Reflect.Service}
  3755. * @expose
  3756. */
  3757. var $typeS;
  3758. /**
  3759. * Reflection type.
  3760. * @name ProtoBuf.Builder.Service#$type
  3761. * @type {!ProtoBuf.Reflect.Service}
  3762. * @expose
  3763. */
  3764. var $type;
  3765. if (Object.defineProperty)
  3766. Object.defineProperty(Service, "$options", { "value": T.buildOpt() }),
  3767. Object.defineProperty(ServicePrototype, "$options", { "value": Service["$options"] }),
  3768. Object.defineProperty(Service, "$type", { "value": T }),
  3769. Object.defineProperty(ServicePrototype, "$type", { "value": T });
  3770. return Service;
  3771. })(ProtoBuf, this);
  3772. };
  3773. /**
  3774. * @alias ProtoBuf.Reflect.Service
  3775. * @expose
  3776. */
  3777. Reflect.Service = Service;
  3778. /**
  3779. * Abstract service method.
  3780. * @exports ProtoBuf.Reflect.Service.Method
  3781. * @param {!ProtoBuf.Builder} builder Builder reference
  3782. * @param {!ProtoBuf.Reflect.Service} svc Service
  3783. * @param {string} name Method name
  3784. * @param {Object.<string,*>=} options Options
  3785. * @constructor
  3786. * @extends ProtoBuf.Reflect.T
  3787. */
  3788. var Method = function(builder, svc, name, options) {
  3789. T.call(this, builder, svc, name);
  3790. /**
  3791. * @override
  3792. */
  3793. this.className = "Service.Method";
  3794. /**
  3795. * Options.
  3796. * @type {Object.<string, *>}
  3797. * @expose
  3798. */
  3799. this.options = options || {};
  3800. };
  3801. /**
  3802. * @alias ProtoBuf.Reflect.Service.Method.prototype
  3803. * @inner
  3804. */
  3805. var MethodPrototype = Method.prototype = Object.create(T.prototype);
  3806. /**
  3807. * Builds the method's '$options' property.
  3808. * @name ProtoBuf.Reflect.Service.Method#buildOpt
  3809. * @function
  3810. * @return {Object.<string,*>}
  3811. */
  3812. MethodPrototype.buildOpt = NamespacePrototype.buildOpt;
  3813. /**
  3814. * @alias ProtoBuf.Reflect.Service.Method
  3815. * @expose
  3816. */
  3817. Reflect.Service.Method = Method;
  3818. /**
  3819. * RPC service method.
  3820. * @exports ProtoBuf.Reflect.Service.RPCMethod
  3821. * @param {!ProtoBuf.Builder} builder Builder reference
  3822. * @param {!ProtoBuf.Reflect.Service} svc Service
  3823. * @param {string} name Method name
  3824. * @param {string} request Request message name
  3825. * @param {string} response Response message name
  3826. * @param {boolean} request_stream Whether requests are streamed
  3827. * @param {boolean} response_stream Whether responses are streamed
  3828. * @param {Object.<string,*>=} options Options
  3829. * @constructor
  3830. * @extends ProtoBuf.Reflect.Service.Method
  3831. */
  3832. var RPCMethod = function(builder, svc, name, request, response, request_stream, response_stream, options) {
  3833. Method.call(this, builder, svc, name, options);
  3834. /**
  3835. * @override
  3836. */
  3837. this.className = "Service.RPCMethod";
  3838. /**
  3839. * Request message name.
  3840. * @type {string}
  3841. * @expose
  3842. */
  3843. this.requestName = request;
  3844. /**
  3845. * Response message name.
  3846. * @type {string}
  3847. * @expose
  3848. */
  3849. this.responseName = response;
  3850. /**
  3851. * Whether requests are streamed
  3852. * @type {bool}
  3853. * @expose
  3854. */
  3855. this.requestStream = request_stream;
  3856. /**
  3857. * Whether responses are streamed
  3858. * @type {bool}
  3859. * @expose
  3860. */
  3861. this.responseStream = response_stream;
  3862. /**
  3863. * Resolved request message type.
  3864. * @type {ProtoBuf.Reflect.Message}
  3865. * @expose
  3866. */
  3867. this.resolvedRequestType = null;
  3868. /**
  3869. * Resolved response message type.
  3870. * @type {ProtoBuf.Reflect.Message}
  3871. * @expose
  3872. */
  3873. this.resolvedResponseType = null;
  3874. };
  3875. // Extends Method
  3876. RPCMethod.prototype = Object.create(Method.prototype);
  3877. /**
  3878. * @alias ProtoBuf.Reflect.Service.RPCMethod
  3879. * @expose
  3880. */
  3881. Reflect.Service.RPCMethod = RPCMethod;
  3882. return Reflect;
  3883. })(ProtoBuf);
  3884. /**
  3885. * @alias ProtoBuf.Builder
  3886. * @expose
  3887. */
  3888. ProtoBuf.Builder = (function(ProtoBuf, Lang, Reflect) {
  3889. "use strict";
  3890. /**
  3891. * Constructs a new Builder.
  3892. * @exports ProtoBuf.Builder
  3893. * @class Provides the functionality to build protocol messages.
  3894. * @param {Object.<string,*>=} options Options
  3895. * @constructor
  3896. */
  3897. var Builder = function(options) {
  3898. /**
  3899. * Namespace.
  3900. * @type {ProtoBuf.Reflect.Namespace}
  3901. * @expose
  3902. */
  3903. this.ns = new Reflect.Namespace(this, null, ""); // Global namespace
  3904. /**
  3905. * Namespace pointer.
  3906. * @type {ProtoBuf.Reflect.T}
  3907. * @expose
  3908. */
  3909. this.ptr = this.ns;
  3910. /**
  3911. * Resolved flag.
  3912. * @type {boolean}
  3913. * @expose
  3914. */
  3915. this.resolved = false;
  3916. /**
  3917. * The current building result.
  3918. * @type {Object.<string,ProtoBuf.Builder.Message|Object>|null}
  3919. * @expose
  3920. */
  3921. this.result = null;
  3922. /**
  3923. * Imported files.
  3924. * @type {Array.<string>}
  3925. * @expose
  3926. */
  3927. this.files = {};
  3928. /**
  3929. * Import root override.
  3930. * @type {?string}
  3931. * @expose
  3932. */
  3933. this.importRoot = null;
  3934. /**
  3935. * Options.
  3936. * @type {!Object.<string, *>}
  3937. * @expose
  3938. */
  3939. this.options = options || {};
  3940. };
  3941. /**
  3942. * @alias ProtoBuf.Builder.prototype
  3943. * @inner
  3944. */
  3945. var BuilderPrototype = Builder.prototype;
  3946. // ----- Definition tests -----
  3947. /**
  3948. * Tests if a definition most likely describes a message.
  3949. * @param {!Object} def
  3950. * @returns {boolean}
  3951. * @expose
  3952. */
  3953. Builder.isMessage = function(def) {
  3954. // Messages require a string name
  3955. if (typeof def["name"] !== 'string')
  3956. return false;
  3957. // Messages do not contain values (enum) or rpc methods (service)
  3958. if (typeof def["values"] !== 'undefined' || typeof def["rpc"] !== 'undefined')
  3959. return false;
  3960. return true;
  3961. };
  3962. /**
  3963. * Tests if a definition most likely describes a message field.
  3964. * @param {!Object} def
  3965. * @returns {boolean}
  3966. * @expose
  3967. */
  3968. Builder.isMessageField = function(def) {
  3969. // Message fields require a string rule, name and type and an id
  3970. if (typeof def["rule"] !== 'string' || typeof def["name"] !== 'string' || typeof def["type"] !== 'string' || typeof def["id"] === 'undefined')
  3971. return false;
  3972. return true;
  3973. };
  3974. /**
  3975. * Tests if a definition most likely describes an enum.
  3976. * @param {!Object} def
  3977. * @returns {boolean}
  3978. * @expose
  3979. */
  3980. Builder.isEnum = function(def) {
  3981. // Enums require a string name
  3982. if (typeof def["name"] !== 'string')
  3983. return false;
  3984. // Enums require at least one value
  3985. if (typeof def["values"] === 'undefined' || !Array.isArray(def["values"]) || def["values"].length === 0)
  3986. return false;
  3987. return true;
  3988. };
  3989. /**
  3990. * Tests if a definition most likely describes a service.
  3991. * @param {!Object} def
  3992. * @returns {boolean}
  3993. * @expose
  3994. */
  3995. Builder.isService = function(def) {
  3996. // Services require a string name and an rpc object
  3997. if (typeof def["name"] !== 'string' || typeof def["rpc"] !== 'object' || !def["rpc"])
  3998. return false;
  3999. return true;
  4000. };
  4001. /**
  4002. * Tests if a definition most likely describes an extended message
  4003. * @param {!Object} def
  4004. * @returns {boolean}
  4005. * @expose
  4006. */
  4007. Builder.isExtend = function(def) {
  4008. // Extends rquire a string ref
  4009. if (typeof def["ref"] !== 'string')
  4010. return false;
  4011. return true;
  4012. };
  4013. // ----- Building -----
  4014. /**
  4015. * Resets the pointer to the root namespace.
  4016. * @returns {!ProtoBuf.Builder} this
  4017. * @expose
  4018. */
  4019. BuilderPrototype.reset = function() {
  4020. this.ptr = this.ns;
  4021. return this;
  4022. };
  4023. /**
  4024. * Defines a namespace on top of the current pointer position and places the pointer on it.
  4025. * @param {string} namespace
  4026. * @return {!ProtoBuf.Builder} this
  4027. * @expose
  4028. */
  4029. BuilderPrototype.define = function(namespace) {
  4030. if (typeof namespace !== 'string' || !Lang.TYPEREF.test(namespace))
  4031. throw Error("illegal namespace: "+namespace);
  4032. namespace.split(".").forEach(function(part) {
  4033. var ns = this.ptr.getChild(part);
  4034. if (ns === null) // Keep existing
  4035. this.ptr.addChild(ns = new Reflect.Namespace(this, this.ptr, part));
  4036. this.ptr = ns;
  4037. }, this);
  4038. return this;
  4039. };
  4040. /**
  4041. * Creates the specified definitions at the current pointer position.
  4042. * @param {!Array.<!Object>} defs Messages, enums or services to create
  4043. * @returns {!ProtoBuf.Builder} this
  4044. * @throws {Error} If a message definition is invalid
  4045. * @expose
  4046. */
  4047. BuilderPrototype.create = function(defs) {
  4048. if (!defs)
  4049. return this; // Nothing to create
  4050. if (!Array.isArray(defs))
  4051. defs = [defs];
  4052. else {
  4053. if (defs.length === 0)
  4054. return this;
  4055. defs = defs.slice();
  4056. }
  4057. // It's quite hard to keep track of scopes and memory here, so let's do this iteratively.
  4058. var stack = [defs];
  4059. while (stack.length > 0) {
  4060. defs = stack.pop();
  4061. if (!Array.isArray(defs)) // Stack always contains entire namespaces
  4062. throw Error("not a valid namespace: "+JSON.stringify(defs));
  4063. while (defs.length > 0) {
  4064. var def = defs.shift(); // Namespaces always contain an array of messages, enums and services
  4065. if (Builder.isMessage(def)) {
  4066. var obj = new Reflect.Message(this, this.ptr, def["name"], def["options"], def["isGroup"], def["syntax"]);
  4067. // Create OneOfs
  4068. var oneofs = {};
  4069. if (def["oneofs"])
  4070. Object.keys(def["oneofs"]).forEach(function(name) {
  4071. obj.addChild(oneofs[name] = new Reflect.Message.OneOf(this, obj, name));
  4072. }, this);
  4073. // Create fields
  4074. if (def["fields"])
  4075. def["fields"].forEach(function(fld) {
  4076. if (obj.getChild(fld["id"]|0) !== null)
  4077. throw Error("duplicate or invalid field id in "+obj.name+": "+fld['id']);
  4078. if (fld["options"] && typeof fld["options"] !== 'object')
  4079. throw Error("illegal field options in "+obj.name+"#"+fld["name"]);
  4080. var oneof = null;
  4081. if (typeof fld["oneof"] === 'string' && !(oneof = oneofs[fld["oneof"]]))
  4082. throw Error("illegal oneof in "+obj.name+"#"+fld["name"]+": "+fld["oneof"]);
  4083. fld = new Reflect.Message.Field(this, obj, fld["rule"], fld["keytype"], fld["type"], fld["name"], fld["id"], fld["options"], oneof, def["syntax"]);
  4084. if (oneof)
  4085. oneof.fields.push(fld);
  4086. obj.addChild(fld);
  4087. }, this);
  4088. // Push children to stack
  4089. var subObj = [];
  4090. if (def["enums"])
  4091. def["enums"].forEach(function(enm) {
  4092. subObj.push(enm);
  4093. });
  4094. if (def["messages"])
  4095. def["messages"].forEach(function(msg) {
  4096. subObj.push(msg);
  4097. });
  4098. if (def["services"])
  4099. def["services"].forEach(function(svc) {
  4100. subObj.push(svc);
  4101. });
  4102. // Set extension ranges
  4103. if (def["extensions"]) {
  4104. if (typeof def["extensions"][0] === 'number') // pre 5.0.1
  4105. obj.extensions = [ def["extensions"] ];
  4106. else
  4107. obj.extensions = def["extensions"];
  4108. }
  4109. // Create on top of current namespace
  4110. this.ptr.addChild(obj);
  4111. if (subObj.length > 0) {
  4112. stack.push(defs); // Push the current level back
  4113. defs = subObj; // Continue processing sub level
  4114. subObj = null;
  4115. this.ptr = obj; // And move the pointer to this namespace
  4116. obj = null;
  4117. continue;
  4118. }
  4119. subObj = null;
  4120. } else if (Builder.isEnum(def)) {
  4121. obj = new Reflect.Enum(this, this.ptr, def["name"], def["options"], def["syntax"]);
  4122. def["values"].forEach(function(val) {
  4123. obj.addChild(new Reflect.Enum.Value(this, obj, val["name"], val["id"]));
  4124. }, this);
  4125. this.ptr.addChild(obj);
  4126. } else if (Builder.isService(def)) {
  4127. obj = new Reflect.Service(this, this.ptr, def["name"], def["options"]);
  4128. Object.keys(def["rpc"]).forEach(function(name) {
  4129. var mtd = def["rpc"][name];
  4130. obj.addChild(new Reflect.Service.RPCMethod(this, obj, name, mtd["request"], mtd["response"], !!mtd["request_stream"], !!mtd["response_stream"], mtd["options"]));
  4131. }, this);
  4132. this.ptr.addChild(obj);
  4133. } else if (Builder.isExtend(def)) {
  4134. obj = this.ptr.resolve(def["ref"], true);
  4135. if (obj) {
  4136. def["fields"].forEach(function(fld) {
  4137. if (obj.getChild(fld['id']|0) !== null)
  4138. throw Error("duplicate extended field id in "+obj.name+": "+fld['id']);
  4139. // Check if field id is allowed to be extended
  4140. if (obj.extensions) {
  4141. var valid = false;
  4142. obj.extensions.forEach(function(range) {
  4143. if (fld["id"] >= range[0] && fld["id"] <= range[1])
  4144. valid = true;
  4145. });
  4146. if (!valid)
  4147. throw Error("illegal extended field id in "+obj.name+": "+fld['id']+" (not within valid ranges)");
  4148. }
  4149. // Convert extension field names to camel case notation if the override is set
  4150. var name = fld["name"];
  4151. if (this.options['convertFieldsToCamelCase'])
  4152. name = ProtoBuf.Util.toCamelCase(name);
  4153. // see #161: Extensions use their fully qualified name as their runtime key and...
  4154. var field = new Reflect.Message.ExtensionField(this, obj, fld["rule"], fld["type"], this.ptr.fqn()+'.'+name, fld["id"], fld["options"]);
  4155. // ...are added on top of the current namespace as an extension which is used for
  4156. // resolving their type later on (the extension always keeps the original name to
  4157. // prevent naming collisions)
  4158. var ext = new Reflect.Extension(this, this.ptr, fld["name"], field);
  4159. field.extension = ext;
  4160. this.ptr.addChild(ext);
  4161. obj.addChild(field);
  4162. }, this);
  4163. } else if (!/\.?google\.protobuf\./.test(def["ref"])) // Silently skip internal extensions
  4164. throw Error("extended message "+def["ref"]+" is not defined");
  4165. } else
  4166. throw Error("not a valid definition: "+JSON.stringify(def));
  4167. def = null;
  4168. obj = null;
  4169. }
  4170. // Break goes here
  4171. defs = null;
  4172. this.ptr = this.ptr.parent; // Namespace done, continue at parent
  4173. }
  4174. this.resolved = false; // Require re-resolve
  4175. this.result = null; // Require re-build
  4176. return this;
  4177. };
  4178. /**
  4179. * Propagates syntax to all children.
  4180. * @param {!Object} parent
  4181. * @inner
  4182. */
  4183. function propagateSyntax(parent) {
  4184. if (parent['messages']) {
  4185. parent['messages'].forEach(function(child) {
  4186. child["syntax"] = parent["syntax"];
  4187. propagateSyntax(child);
  4188. });
  4189. }
  4190. if (parent['enums']) {
  4191. parent['enums'].forEach(function(child) {
  4192. child["syntax"] = parent["syntax"];
  4193. });
  4194. }
  4195. }
  4196. /**
  4197. * Imports another definition into this builder.
  4198. * @param {Object.<string,*>} json Parsed import
  4199. * @param {(string|{root: string, file: string})=} filename Imported file name
  4200. * @returns {!ProtoBuf.Builder} this
  4201. * @throws {Error} If the definition or file cannot be imported
  4202. * @expose
  4203. */
  4204. BuilderPrototype["import"] = function(json, filename) {
  4205. var delim = '/';
  4206. // Make sure to skip duplicate imports
  4207. if (typeof filename === 'string') {
  4208. if (ProtoBuf.Util.IS_NODE)
  4209. filename = require("path")['resolve'](filename);
  4210. if (this.files[filename] === true)
  4211. return this.reset();
  4212. this.files[filename] = true;
  4213. } else if (typeof filename === 'object') { // Object with root, file.
  4214. var root = filename.root;
  4215. if (ProtoBuf.Util.IS_NODE)
  4216. root = require("path")['resolve'](root);
  4217. if (root.indexOf("\\") >= 0 || filename.file.indexOf("\\") >= 0)
  4218. delim = '\\';
  4219. var fname;
  4220. if (ProtoBuf.Util.IS_NODE)
  4221. fname = require("path")['join'](root, filename.file);
  4222. else
  4223. fname = root + delim + filename.file;
  4224. if (this.files[fname] === true)
  4225. return this.reset();
  4226. this.files[fname] = true;
  4227. }
  4228. // Import imports
  4229. if (json['imports'] && json['imports'].length > 0) {
  4230. var importRoot,
  4231. resetRoot = false;
  4232. if (typeof filename === 'object') { // If an import root is specified, override
  4233. this.importRoot = filename["root"]; resetRoot = true; // ... and reset afterwards
  4234. importRoot = this.importRoot;
  4235. filename = filename["file"];
  4236. if (importRoot.indexOf("\\") >= 0 || filename.indexOf("\\") >= 0)
  4237. delim = '\\';
  4238. } else if (typeof filename === 'string') {
  4239. if (this.importRoot) // If import root is overridden, use it
  4240. importRoot = this.importRoot;
  4241. else { // Otherwise compute from filename
  4242. if (filename.indexOf("/") >= 0) { // Unix
  4243. importRoot = filename.replace(/\/[^\/]*$/, "");
  4244. if (/* /file.proto */ importRoot === "")
  4245. importRoot = "/";
  4246. } else if (filename.indexOf("\\") >= 0) { // Windows
  4247. importRoot = filename.replace(/\\[^\\]*$/, "");
  4248. delim = '\\';
  4249. } else
  4250. importRoot = ".";
  4251. }
  4252. } else
  4253. importRoot = null;
  4254. for (var i=0; i<json['imports'].length; i++) {
  4255. if (typeof json['imports'][i] === 'string') { // Import file
  4256. if (!importRoot)
  4257. throw Error("cannot determine import root");
  4258. var importFilename = json['imports'][i];
  4259. if (importFilename === "google/protobuf/descriptor.proto")
  4260. continue; // Not needed and therefore not used
  4261. if (ProtoBuf.Util.IS_NODE)
  4262. importFilename = require("path")['join'](importRoot, importFilename);
  4263. else
  4264. importFilename = importRoot + delim + importFilename;
  4265. if (this.files[importFilename] === true)
  4266. continue; // Already imported
  4267. if (/\.proto$/i.test(importFilename) && !ProtoBuf.DotProto) // If this is a light build
  4268. importFilename = importFilename.replace(/\.proto$/, ".json"); // always load the JSON file
  4269. var contents = ProtoBuf.Util.fetch(importFilename);
  4270. if (contents === null)
  4271. throw Error("failed to import '"+importFilename+"' in '"+filename+"': file not found");
  4272. if (/\.json$/i.test(importFilename)) // Always possible
  4273. this["import"](JSON.parse(contents+""), importFilename); // May throw
  4274. else
  4275. this["import"](ProtoBuf.DotProto.Parser.parse(contents), importFilename); // May throw
  4276. } else // Import structure
  4277. if (!filename)
  4278. this["import"](json['imports'][i]);
  4279. else if (/\.(\w+)$/.test(filename)) // With extension: Append _importN to the name portion to make it unique
  4280. this["import"](json['imports'][i], filename.replace(/^(.+)\.(\w+)$/, function($0, $1, $2) { return $1+"_import"+i+"."+$2; }));
  4281. else // Without extension: Append _importN to make it unique
  4282. this["import"](json['imports'][i], filename+"_import"+i);
  4283. }
  4284. if (resetRoot) // Reset import root override when all imports are done
  4285. this.importRoot = null;
  4286. }
  4287. // Import structures
  4288. if (json['package'])
  4289. this.define(json['package']);
  4290. if (json['syntax'])
  4291. propagateSyntax(json);
  4292. var base = this.ptr;
  4293. if (json['options'])
  4294. Object.keys(json['options']).forEach(function(key) {
  4295. base.options[key] = json['options'][key];
  4296. });
  4297. if (json['messages'])
  4298. this.create(json['messages']),
  4299. this.ptr = base;
  4300. if (json['enums'])
  4301. this.create(json['enums']),
  4302. this.ptr = base;
  4303. if (json['services'])
  4304. this.create(json['services']),
  4305. this.ptr = base;
  4306. if (json['extends'])
  4307. this.create(json['extends']);
  4308. return this.reset();
  4309. };
  4310. /**
  4311. * Resolves all namespace objects.
  4312. * @throws {Error} If a type cannot be resolved
  4313. * @returns {!ProtoBuf.Builder} this
  4314. * @expose
  4315. */
  4316. BuilderPrototype.resolveAll = function() {
  4317. // Resolve all reflected objects
  4318. var res;
  4319. if (this.ptr == null || typeof this.ptr.type === 'object')
  4320. return this; // Done (already resolved)
  4321. if (this.ptr instanceof Reflect.Namespace) { // Resolve children
  4322. this.ptr.children.forEach(function(child) {
  4323. this.ptr = child;
  4324. this.resolveAll();
  4325. }, this);
  4326. } else if (this.ptr instanceof Reflect.Message.Field) { // Resolve type
  4327. if (!Lang.TYPE.test(this.ptr.type)) {
  4328. if (!Lang.TYPEREF.test(this.ptr.type))
  4329. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4330. res = (this.ptr instanceof Reflect.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, true);
  4331. if (!res)
  4332. throw Error("unresolvable type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4333. this.ptr.resolvedType = res;
  4334. if (res instanceof Reflect.Enum) {
  4335. this.ptr.type = ProtoBuf.TYPES["enum"];
  4336. if (this.ptr.syntax === 'proto3' && res.syntax !== 'proto3')
  4337. throw Error("proto3 message cannot reference proto2 enum");
  4338. }
  4339. else if (res instanceof Reflect.Message)
  4340. this.ptr.type = res.isGroup ? ProtoBuf.TYPES["group"] : ProtoBuf.TYPES["message"];
  4341. else
  4342. throw Error("illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.type);
  4343. } else
  4344. this.ptr.type = ProtoBuf.TYPES[this.ptr.type];
  4345. // If it's a map field, also resolve the key type. The key type can be only a numeric, string, or bool type
  4346. // (i.e., no enums or messages), so we don't need to resolve against the current namespace.
  4347. if (this.ptr.map) {
  4348. if (!Lang.TYPE.test(this.ptr.keyType))
  4349. throw Error("illegal key type for map field in "+this.ptr.toString(true)+": "+this.ptr.keyType);
  4350. this.ptr.keyType = ProtoBuf.TYPES[this.ptr.keyType];
  4351. }
  4352. // If it's a repeated and packable field then proto3 mandates it should be packed by
  4353. // default
  4354. if (
  4355. this.ptr.syntax === 'proto3' &&
  4356. this.ptr.repeated && this.ptr.options.packed === undefined &&
  4357. ProtoBuf.PACKABLE_WIRE_TYPES.indexOf(this.ptr.type.wireType) !== -1
  4358. ) {
  4359. this.ptr.options.packed = true;
  4360. }
  4361. } else if (this.ptr instanceof ProtoBuf.Reflect.Service.Method) {
  4362. if (this.ptr instanceof ProtoBuf.Reflect.Service.RPCMethod) {
  4363. res = this.ptr.parent.resolve(this.ptr.requestName, true);
  4364. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  4365. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.requestName);
  4366. this.ptr.resolvedRequestType = res;
  4367. res = this.ptr.parent.resolve(this.ptr.responseName, true);
  4368. if (!res || !(res instanceof ProtoBuf.Reflect.Message))
  4369. throw Error("Illegal type reference in "+this.ptr.toString(true)+": "+this.ptr.responseName);
  4370. this.ptr.resolvedResponseType = res;
  4371. } else // Should not happen as nothing else is implemented
  4372. throw Error("illegal service type in "+this.ptr.toString(true));
  4373. } else if (
  4374. !(this.ptr instanceof ProtoBuf.Reflect.Message.OneOf) && // Not built
  4375. !(this.ptr instanceof ProtoBuf.Reflect.Extension) && // Not built
  4376. !(this.ptr instanceof ProtoBuf.Reflect.Enum.Value) // Built in enum
  4377. )
  4378. throw Error("illegal object in namespace: "+typeof(this.ptr)+": "+this.ptr);
  4379. return this.reset();
  4380. };
  4381. /**
  4382. * Builds the protocol. This will first try to resolve all definitions and, if this has been successful,
  4383. * return the built package.
  4384. * @param {(string|Array.<string>)=} path Specifies what to return. If omitted, the entire namespace will be returned.
  4385. * @returns {!ProtoBuf.Builder.Message|!Object.<string,*>}
  4386. * @throws {Error} If a type could not be resolved
  4387. * @expose
  4388. */
  4389. BuilderPrototype.build = function(path) {
  4390. this.reset();
  4391. if (!this.resolved)
  4392. this.resolveAll(),
  4393. this.resolved = true,
  4394. this.result = null; // Require re-build
  4395. if (this.result === null) // (Re-)Build
  4396. this.result = this.ns.build();
  4397. if (!path)
  4398. return this.result;
  4399. var part = typeof path === 'string' ? path.split(".") : path,
  4400. ptr = this.result; // Build namespace pointer (no hasChild etc.)
  4401. for (var i=0; i<part.length; i++)
  4402. if (ptr[part[i]])
  4403. ptr = ptr[part[i]];
  4404. else {
  4405. ptr = null;
  4406. break;
  4407. }
  4408. return ptr;
  4409. };
  4410. /**
  4411. * Similar to {@link ProtoBuf.Builder#build}, but looks up the internal reflection descriptor.
  4412. * @param {string=} path Specifies what to return. If omitted, the entire namespace wiil be returned.
  4413. * @param {boolean=} excludeNonNamespace Excludes non-namespace types like fields, defaults to `false`
  4414. * @returns {?ProtoBuf.Reflect.T} Reflection descriptor or `null` if not found
  4415. */
  4416. BuilderPrototype.lookup = function(path, excludeNonNamespace) {
  4417. return path ? this.ns.resolve(path, excludeNonNamespace) : this.ns;
  4418. };
  4419. /**
  4420. * Returns a string representation of this object.
  4421. * @return {string} String representation as of "Builder"
  4422. * @expose
  4423. */
  4424. BuilderPrototype.toString = function() {
  4425. return "Builder";
  4426. };
  4427. // ----- Base classes -----
  4428. // Exist for the sole purpose of being able to "... instanceof ProtoBuf.Builder.Message" etc.
  4429. /**
  4430. * @alias ProtoBuf.Builder.Message
  4431. */
  4432. Builder.Message = function() {};
  4433. /**
  4434. * @alias ProtoBuf.Builder.Enum
  4435. */
  4436. Builder.Enum = function() {};
  4437. /**
  4438. * @alias ProtoBuf.Builder.Message
  4439. */
  4440. Builder.Service = function() {};
  4441. return Builder;
  4442. })(ProtoBuf, ProtoBuf.Lang, ProtoBuf.Reflect);
  4443. /**
  4444. * @alias ProtoBuf.Map
  4445. * @expose
  4446. */
  4447. ProtoBuf.Map = (function(ProtoBuf, Reflect) {
  4448. "use strict";
  4449. /**
  4450. * Constructs a new Map. A Map is a container that is used to implement map
  4451. * fields on message objects. It closely follows the ES6 Map API; however,
  4452. * it is distinct because we do not want to depend on external polyfills or
  4453. * on ES6 itself.
  4454. *
  4455. * @exports ProtoBuf.Map
  4456. * @param {!ProtoBuf.Reflect.Field} field Map field
  4457. * @param {Object.<string,*>=} contents Initial contents
  4458. * @constructor
  4459. */
  4460. var Map = function(field, contents) {
  4461. if (!field.map)
  4462. throw Error("field is not a map");
  4463. /**
  4464. * The field corresponding to this map.
  4465. * @type {!ProtoBuf.Reflect.Field}
  4466. */
  4467. this.field = field;
  4468. /**
  4469. * Element instance corresponding to key type.
  4470. * @type {!ProtoBuf.Reflect.Element}
  4471. */
  4472. this.keyElem = new Reflect.Element(field.keyType, null, true, field.syntax);
  4473. /**
  4474. * Element instance corresponding to value type.
  4475. * @type {!ProtoBuf.Reflect.Element}
  4476. */
  4477. this.valueElem = new Reflect.Element(field.type, field.resolvedType, false, field.syntax);
  4478. /**
  4479. * Internal map: stores mapping of (string form of key) -> (key, value)
  4480. * pair.
  4481. *
  4482. * We provide map semantics for arbitrary key types, but we build on top
  4483. * of an Object, which has only string keys. In order to avoid the need
  4484. * to convert a string key back to its native type in many situations,
  4485. * we store the native key value alongside the value. Thus, we only need
  4486. * a one-way mapping from a key type to its string form that guarantees
  4487. * uniqueness and equality (i.e., str(K1) === str(K2) if and only if K1
  4488. * === K2).
  4489. *
  4490. * @type {!Object<string, {key: *, value: *}>}
  4491. */
  4492. this.map = {};
  4493. /**
  4494. * Returns the number of elements in the map.
  4495. */
  4496. Object.defineProperty(this, "size", {
  4497. get: function() { return Object.keys(this.map).length; }
  4498. });
  4499. // Fill initial contents from a raw object.
  4500. if (contents) {
  4501. var keys = Object.keys(contents);
  4502. for (var i = 0; i < keys.length; i++) {
  4503. var key = this.keyElem.valueFromString(keys[i]);
  4504. var val = this.valueElem.verifyValue(contents[keys[i]]);
  4505. this.map[this.keyElem.valueToString(key)] =
  4506. { key: key, value: val };
  4507. }
  4508. }
  4509. };
  4510. var MapPrototype = Map.prototype;
  4511. /**
  4512. * Helper: return an iterator over an array.
  4513. * @param {!Array<*>} arr the array
  4514. * @returns {!Object} an iterator
  4515. * @inner
  4516. */
  4517. function arrayIterator(arr) {
  4518. var idx = 0;
  4519. return {
  4520. next: function() {
  4521. if (idx < arr.length)
  4522. return { done: false, value: arr[idx++] };
  4523. return { done: true };
  4524. }
  4525. }
  4526. }
  4527. /**
  4528. * Clears the map.
  4529. */
  4530. MapPrototype.clear = function() {
  4531. this.map = {};
  4532. };
  4533. /**
  4534. * Deletes a particular key from the map.
  4535. * @returns {boolean} Whether any entry with this key was deleted.
  4536. */
  4537. MapPrototype["delete"] = function(key) {
  4538. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4539. var hadKey = keyValue in this.map;
  4540. delete this.map[keyValue];
  4541. return hadKey;
  4542. };
  4543. /**
  4544. * Returns an iterator over [key, value] pairs in the map.
  4545. * @returns {Object} The iterator
  4546. */
  4547. MapPrototype.entries = function() {
  4548. var entries = [];
  4549. var strKeys = Object.keys(this.map);
  4550. for (var i = 0, entry; i < strKeys.length; i++)
  4551. entries.push([(entry=this.map[strKeys[i]]).key, entry.value]);
  4552. return arrayIterator(entries);
  4553. };
  4554. /**
  4555. * Returns an iterator over keys in the map.
  4556. * @returns {Object} The iterator
  4557. */
  4558. MapPrototype.keys = function() {
  4559. var keys = [];
  4560. var strKeys = Object.keys(this.map);
  4561. for (var i = 0; i < strKeys.length; i++)
  4562. keys.push(this.map[strKeys[i]].key);
  4563. return arrayIterator(keys);
  4564. };
  4565. /**
  4566. * Returns an iterator over values in the map.
  4567. * @returns {!Object} The iterator
  4568. */
  4569. MapPrototype.values = function() {
  4570. var values = [];
  4571. var strKeys = Object.keys(this.map);
  4572. for (var i = 0; i < strKeys.length; i++)
  4573. values.push(this.map[strKeys[i]].value);
  4574. return arrayIterator(values);
  4575. };
  4576. /**
  4577. * Iterates over entries in the map, calling a function on each.
  4578. * @param {function(this:*, *, *, *)} cb The callback to invoke with value, key, and map arguments.
  4579. * @param {Object=} thisArg The `this` value for the callback
  4580. */
  4581. MapPrototype.forEach = function(cb, thisArg) {
  4582. var strKeys = Object.keys(this.map);
  4583. for (var i = 0, entry; i < strKeys.length; i++)
  4584. cb.call(thisArg, (entry=this.map[strKeys[i]]).value, entry.key, this);
  4585. };
  4586. /**
  4587. * Sets a key in the map to the given value.
  4588. * @param {*} key The key
  4589. * @param {*} value The value
  4590. * @returns {!ProtoBuf.Map} The map instance
  4591. */
  4592. MapPrototype.set = function(key, value) {
  4593. var keyValue = this.keyElem.verifyValue(key);
  4594. var valValue = this.valueElem.verifyValue(value);
  4595. this.map[this.keyElem.valueToString(keyValue)] =
  4596. { key: keyValue, value: valValue };
  4597. return this;
  4598. };
  4599. /**
  4600. * Gets the value corresponding to a key in the map.
  4601. * @param {*} key The key
  4602. * @returns {*|undefined} The value, or `undefined` if key not present
  4603. */
  4604. MapPrototype.get = function(key) {
  4605. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4606. if (!(keyValue in this.map))
  4607. return undefined;
  4608. return this.map[keyValue].value;
  4609. };
  4610. /**
  4611. * Determines whether the given key is present in the map.
  4612. * @param {*} key The key
  4613. * @returns {boolean} `true` if the key is present
  4614. */
  4615. MapPrototype.has = function(key) {
  4616. var keyValue = this.keyElem.valueToString(this.keyElem.verifyValue(key));
  4617. return (keyValue in this.map);
  4618. };
  4619. return Map;
  4620. })(ProtoBuf, ProtoBuf.Reflect);
  4621. /**
  4622. * Loads a .proto string and returns the Builder.
  4623. * @param {string} proto .proto file contents
  4624. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  4625. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4626. * @return {ProtoBuf.Builder} Builder to create new messages
  4627. * @throws {Error} If the definition cannot be parsed or built
  4628. * @expose
  4629. */
  4630. ProtoBuf.loadProto = function(proto, builder, filename) {
  4631. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  4632. filename = builder,
  4633. builder = undefined;
  4634. return ProtoBuf.loadJson(ProtoBuf.DotProto.Parser.parse(proto), builder, filename);
  4635. };
  4636. /**
  4637. * Loads a .proto string and returns the Builder. This is an alias of {@link ProtoBuf.loadProto}.
  4638. * @function
  4639. * @param {string} proto .proto file contents
  4640. * @param {(ProtoBuf.Builder|string)=} builder Builder to append to. Will create a new one if omitted.
  4641. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4642. * @return {ProtoBuf.Builder} Builder to create new messages
  4643. * @throws {Error} If the definition cannot be parsed or built
  4644. * @expose
  4645. */
  4646. ProtoBuf.protoFromString = ProtoBuf.loadProto; // Legacy
  4647. /**
  4648. * Loads a .proto file and returns the Builder.
  4649. * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
  4650. * an overridden 'root' path for all imported files.
  4651. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4652. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4653. * file will be read synchronously and this function will return the Builder.
  4654. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4655. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4656. * request has failed), else undefined
  4657. * @expose
  4658. */
  4659. ProtoBuf.loadProtoFile = function(filename, callback, builder) {
  4660. if (callback && typeof callback === 'object')
  4661. builder = callback,
  4662. callback = null;
  4663. else if (!callback || typeof callback !== 'function')
  4664. callback = null;
  4665. if (callback)
  4666. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  4667. if (contents === null) {
  4668. callback(Error("Failed to fetch file"));
  4669. return;
  4670. }
  4671. try {
  4672. callback(null, ProtoBuf.loadProto(contents, builder, filename));
  4673. } catch (e) {
  4674. callback(e);
  4675. }
  4676. });
  4677. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  4678. return contents === null ? null : ProtoBuf.loadProto(contents, builder, filename);
  4679. };
  4680. /**
  4681. * Loads a .proto file and returns the Builder. This is an alias of {@link ProtoBuf.loadProtoFile}.
  4682. * @function
  4683. * @param {string|{root: string, file: string}} filename Path to proto file or an object specifying 'file' with
  4684. * an overridden 'root' path for all imported files.
  4685. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4686. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4687. * file will be read synchronously and this function will return the Builder.
  4688. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4689. * @return {!ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4690. * request has failed), else undefined
  4691. * @expose
  4692. */
  4693. ProtoBuf.protoFromFile = ProtoBuf.loadProtoFile; // Legacy
  4694. /**
  4695. * Constructs a new empty Builder.
  4696. * @param {Object.<string,*>=} options Builder options, defaults to global options set on ProtoBuf
  4697. * @return {!ProtoBuf.Builder} Builder
  4698. * @expose
  4699. */
  4700. ProtoBuf.newBuilder = function(options) {
  4701. options = options || {};
  4702. if (typeof options['convertFieldsToCamelCase'] === 'undefined')
  4703. options['convertFieldsToCamelCase'] = ProtoBuf.convertFieldsToCamelCase;
  4704. if (typeof options['populateAccessors'] === 'undefined')
  4705. options['populateAccessors'] = ProtoBuf.populateAccessors;
  4706. return new ProtoBuf.Builder(options);
  4707. };
  4708. /**
  4709. * Loads a .json definition and returns the Builder.
  4710. * @param {!*|string} json JSON definition
  4711. * @param {(ProtoBuf.Builder|string|{root: string, file: string})=} builder Builder to append to. Will create a new one if omitted.
  4712. * @param {(string|{root: string, file: string})=} filename The corresponding file name if known. Must be specified for imports.
  4713. * @return {ProtoBuf.Builder} Builder to create new messages
  4714. * @throws {Error} If the definition cannot be parsed or built
  4715. * @expose
  4716. */
  4717. ProtoBuf.loadJson = function(json, builder, filename) {
  4718. if (typeof builder === 'string' || (builder && typeof builder["file"] === 'string' && typeof builder["root"] === 'string'))
  4719. filename = builder,
  4720. builder = null;
  4721. if (!builder || typeof builder !== 'object')
  4722. builder = ProtoBuf.newBuilder();
  4723. if (typeof json === 'string')
  4724. json = JSON.parse(json);
  4725. builder["import"](json, filename);
  4726. builder.resolveAll();
  4727. return builder;
  4728. };
  4729. /**
  4730. * Loads a .json file and returns the Builder.
  4731. * @param {string|!{root: string, file: string}} filename Path to json file or an object specifying 'file' with
  4732. * an overridden 'root' path for all imported files.
  4733. * @param {function(?Error, !ProtoBuf.Builder=)=} callback Callback that will receive `null` as the first and
  4734. * the Builder as its second argument on success, otherwise the error as its first argument. If omitted, the
  4735. * file will be read synchronously and this function will return the Builder.
  4736. * @param {ProtoBuf.Builder=} builder Builder to append to. Will create a new one if omitted.
  4737. * @return {?ProtoBuf.Builder|undefined} The Builder if synchronous (no callback specified, will be NULL if the
  4738. * request has failed), else undefined
  4739. * @expose
  4740. */
  4741. ProtoBuf.loadJsonFile = function(filename, callback, builder) {
  4742. if (callback && typeof callback === 'object')
  4743. builder = callback,
  4744. callback = null;
  4745. else if (!callback || typeof callback !== 'function')
  4746. callback = null;
  4747. if (callback)
  4748. return ProtoBuf.Util.fetch(typeof filename === 'string' ? filename : filename["root"]+"/"+filename["file"], function(contents) {
  4749. if (contents === null) {
  4750. callback(Error("Failed to fetch file"));
  4751. return;
  4752. }
  4753. try {
  4754. callback(null, ProtoBuf.loadJson(JSON.parse(contents), builder, filename));
  4755. } catch (e) {
  4756. callback(e);
  4757. }
  4758. });
  4759. var contents = ProtoBuf.Util.fetch(typeof filename === 'object' ? filename["root"]+"/"+filename["file"] : filename);
  4760. return contents === null ? null : ProtoBuf.loadJson(JSON.parse(contents), builder, filename);
  4761. };
  4762. return ProtoBuf;
  4763. });