Best JavaScript code snippet using appium-xcuitest-driver
bundle.js
Source:bundle.js
1(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){2"use strict";3Object.defineProperty(exports, "__esModule", { value: true });4var pb = require("protobufjs");5var protos = null;6function GetEventHandler(req, res) {7 console.log("GetEventHandler");8 return "GetEventHandler";9}10exports.GetEventHandler = GetEventHandler;11;12function LookupUserHandler(req, res) {13 console.log("LookupUserHandler");14 return "LookupUserHandler";15}16exports.LookupUserHandler = LookupUserHandler;17;18function SearchUsersHandler(req, res) {19 console.log("SearchUsersHandler");20 return "SearchUsersHandler";21}22exports.SearchUsersHandler = SearchUsersHandler;23;24function CreateUserHandler(req, res) {25 console.log("CreateUserHandler");26 return "CreateUserHandler";27}28exports.CreateUserHandler = CreateUserHandler;29;30function UpdateUserHandler(req, res) {31 console.log("UpdateUserHandler");32 return "UpdateUserHandler";33}34exports.UpdateUserHandler = UpdateUserHandler;35;36function SetUserContactAddressHandler(req, res) {37 console.log("SetUserContactAddressHandler");38 return "SetUserContactAddressHandler";39}40exports.SetUserContactAddressHandler = SetUserContactAddressHandler;41;42function SetUserAccessHandler(req, res) {43 console.log("SetUserAccessHandler");44 return "SetUserAccessHandler";45}46exports.SetUserAccessHandler = SetUserAccessHandler;47;48function SetUserLoginStatusHandler(req, res) {49 console.log("SetUserLoginStatusHandler");50 return "SetUserLoginStatusHandler";51}52exports.SetUserLoginStatusHandler = SetUserLoginStatusHandler;53;54function ResetUserPasswordHandler(req, res) {55 console.log("ResetUserPasswordHandler");56 return "ResetUserPasswordHandler";57}58exports.ResetUserPasswordHandler = ResetUserPasswordHandler;59;60function NukeHandleHandler(req, res) {61 console.log("NukeHandleHandler");62 return "NukeHandleHandler";63}64exports.NukeHandleHandler = NukeHandleHandler;65;66function GetHandleHistoryHandler(req, res) {67 console.log("GetHandleHistoryHandler");68 return "GetHandleHistoryHandler";69}70exports.GetHandleHistoryHandler = GetHandleHistoryHandler;71;72function SendUserEmailNotificationHandler(req, res) {73 console.log("SendUserEmailNotificationHandler");74 return "SendUserEmailNotificationHandler";75}76exports.SendUserEmailNotificationHandler = SendUserEmailNotificationHandler;77;78function SearchAuditHistoryHandler(req, res) {79 console.log("SearchAuditHistoryHandler");80 return "SearchAuditHistoryHandler";81}82exports.SearchAuditHistoryHandler = SearchAuditHistoryHandler;83;84function GetAppConfigHandler(req, res) {85 console.log("GetAppConfigHandler");86 return "GetAppConfigHandler";87}88exports.GetAppConfigHandler = GetAppConfigHandler;89;90function GetGlobalConfigHandler(req, res) {91 console.log("GetGlobalConfigHandler");92 return "GetGlobalConfigHandler";93}94exports.GetGlobalConfigHandler = GetGlobalConfigHandler;95;96function SetGlobalConfigHandler(req, res) {97 console.log("SetGlobalConfigHandler");98 return "SetGlobalConfigHandler";99}100exports.SetGlobalConfigHandler = SetGlobalConfigHandler;101;102function GetMatchQueueConfigHandler(req, res) {103 console.log("GetMatchQueueConfigHandler");104 return "GetMatchQueueConfigHandler";105}106exports.GetMatchQueueConfigHandler = GetMatchQueueConfigHandler;107;108function SetMatchQueueConfigHandler(req, res) {109 console.log("SetMatchQueueConfigHandler");110 return "SetMatchQueueConfigHandler";111}112exports.SetMatchQueueConfigHandler = SetMatchQueueConfigHandler;113;114function GetMatchUserConfigHandler(req, res) {115 console.log("GetMatchUserConfigHandler");116 return "GetMatchUserConfigHandler";117}118exports.GetMatchUserConfigHandler = GetMatchUserConfigHandler;119;120function SetMatchUserConfigHandler(req, res) {121 console.log("SetMatchUserConfigHandler");122 return "SetMatchUserConfigHandler";123}124exports.SetMatchUserConfigHandler = SetMatchUserConfigHandler;125;126function GetLobbyConfigHandler(req, res) {127 console.log("GetLobbyConfigHandler");128 return "GetLobbyConfigHandler";129}130exports.GetLobbyConfigHandler = GetLobbyConfigHandler;131;132function SetLobbyConfigHandler(req, res) {133 console.log("SetLobbyConfigHandler");134 return "SetLobbyConfigHandler";135}136exports.SetLobbyConfigHandler = SetLobbyConfigHandler;137;138function ListFeatureDefinitionsHandler(req, res) {139 console.log("ListFeatureDefinitionsHandler");140 return "ListFeatureDefinitionsHandler";141}142exports.ListFeatureDefinitionsHandler = ListFeatureDefinitionsHandler;143;144function SetFeatureDefinitionHandler(req, res) {145 console.log("SetFeatureDefinitionHandler");146 return "SetFeatureDefinitionHandler";147}148exports.SetFeatureDefinitionHandler = SetFeatureDefinitionHandler;149;150function DeleteFeatureDefinitionHandler(req, res) {151 console.log("DeleteFeatureDefinitionHandler");152 return "DeleteFeatureDefinitionHandler";153}154exports.DeleteFeatureDefinitionHandler = DeleteFeatureDefinitionHandler;155;156function ListFeatureRulesHandler(req, res) {157 console.log("ListFeatureRulesHandler");158 return "ListFeatureRulesHandler";159}160exports.ListFeatureRulesHandler = ListFeatureRulesHandler;161;162function GetActiveFeaturesHandler(req, res) {163 console.log("GetActiveFeaturesHandler");164 return "GetActiveFeaturesHandler";165}166exports.GetActiveFeaturesHandler = GetActiveFeaturesHandler;167;168function CreateFeatureRuleHandler(req, res) {169 console.log("CreateFeatureRuleHandler");170 return "CreateFeatureRuleHandler";171}172exports.CreateFeatureRuleHandler = CreateFeatureRuleHandler;173;174function UpdateFeatureRuleHandler(req, res) {175 console.log("UpdateFeatureRuleHandler");176 return "UpdateFeatureRuleHandler";177}178exports.UpdateFeatureRuleHandler = UpdateFeatureRuleHandler;179;180function DeleteFeatureRuleHandler(req, res) {181 console.log("DeleteFeatureRuleHandler");182 return "DeleteFeatureRuleHandler";183}184exports.DeleteFeatureRuleHandler = DeleteFeatureRuleHandler;185;186function GetMatchQueueUsersHandler(req, res) {187 console.log("GetMatchQueueUsersHandler");188 return "GetMatchQueueUsersHandler";189}190exports.GetMatchQueueUsersHandler = GetMatchQueueUsersHandler;191;192function GetLobbiesHandler(req, res) {193 console.log("GetLobbiesHandler");194 return "GetLobbiesHandler";195}196exports.GetLobbiesHandler = GetLobbiesHandler;197;198function GetLobbyHandler(req, res) {199 console.log("GetLobbyHandler");200 return "GetLobbyHandler";201}202exports.GetLobbyHandler = GetLobbyHandler;203;204function GetActiveMatchesHandler(req, res) {205 console.log("GetActiveMatchesHandler");206 return "GetActiveMatchesHandler";207}208exports.GetActiveMatchesHandler = GetActiveMatchesHandler;209;210function GetActiveMatchHandler(req, res) {211 console.log("GetActiveMatchHandler");212 return "GetActiveMatchHandler";213}214exports.GetActiveMatchHandler = GetActiveMatchHandler;215;216function GetRecentMatchesHandler(req, res) {217 console.log("GetRecentMatchesHandler");218 return "GetRecentMatchesHandler";219}220exports.GetRecentMatchesHandler = GetRecentMatchesHandler;221;222function GetMatchDetailHandler(req, res) {223 console.log("GetMatchDetailHandler");224 return "GetMatchDetailHandler";225}226exports.GetMatchDetailHandler = GetMatchDetailHandler;227;228function GetPlayerDetailHandler(req, res) {229 console.log("GetPlayerDetailHandler");230 return "GetPlayerDetailHandler";231}232exports.GetPlayerDetailHandler = GetPlayerDetailHandler;233;234function ListDesyncsHandler(req, res) {235 console.log("ListDesyncsHandler");236 return "ListDesyncsHandler";237}238exports.ListDesyncsHandler = ListDesyncsHandler;239;240function ListCrashesHandler(req, res) {241 console.log("ListCrashesHandler");242 return "ListCrashesHandler";243}244exports.ListCrashesHandler = ListCrashesHandler;245;246function ListCrashBuildIdentifiersHandler(req, res) {247 console.log("ListCrashBuildIdentifiersHandler");248 return "ListCrashBuildIdentifiersHandler";249}250exports.ListCrashBuildIdentifiersHandler = ListCrashBuildIdentifiersHandler;251;252function ListCrashCollectionsHandler(req, res) {253 console.log("ListCrashCollectionsHandler");254 return "ListCrashCollectionsHandler";255}256exports.ListCrashCollectionsHandler = ListCrashCollectionsHandler;257;258function SearchPurchaseOrdersHandler(req, res) {259 console.log("SearchPurchaseOrdersHandler");260 return "SearchPurchaseOrdersHandler";261}262exports.SearchPurchaseOrdersHandler = SearchPurchaseOrdersHandler;263;264function SyncPurchaseOrderHandler(req, res) {265 console.log("SyncPurchaseOrderHandler");266 return "SyncPurchaseOrderHandler";267}268exports.SyncPurchaseOrderHandler = SyncPurchaseOrderHandler;269;270function VoidPurchaseOrderHandler(req, res) {271 console.log("VoidPurchaseOrderHandler");272 return "VoidPurchaseOrderHandler";273}274exports.VoidPurchaseOrderHandler = VoidPurchaseOrderHandler;275;276function RefundPurchaseOrderHandler(req, res) {277 console.log("RefundPurchaseOrderHandler");278 return "RefundPurchaseOrderHandler";279}280exports.RefundPurchaseOrderHandler = RefundPurchaseOrderHandler;281;282function CountUsersHandler(req, res) {283 console.log("CountUsersHandler");284 return "CountUsersHandler";285}286exports.CountUsersHandler = CountUsersHandler;287;288function GetSessionsHandler(req, res) {289 console.log("GetSessionsHandler");290 return "GetSessionsHandler";291}292exports.GetSessionsHandler = GetSessionsHandler;293;294function GetCharacterUsageHandler(req, res) {295 console.log("GetCharacterUsageHandler");296 return "GetCharacterUsageHandler";297}298exports.GetCharacterUsageHandler = GetCharacterUsageHandler;299;300function CheckHandleHandler(req, res) {301 console.log("CheckHandleHandler");302 return "CheckHandleHandler";303}304exports.CheckHandleHandler = CheckHandleHandler;305;306function RegisterUserHandler(req, res) {307 console.log("RegisterUserHandler");308 return "RegisterUserHandler";309}310exports.RegisterUserHandler = RegisterUserHandler;311;312function ValidateUserHandler(req, res) {313 console.log("ValidateUserHandler");314 return "ValidateUserHandler";315}316exports.ValidateUserHandler = ValidateUserHandler;317;318function GetSecretQuestionHandler(req, res) {319 console.log("GetSecretQuestionHandler");320 return "GetSecretQuestionHandler";321}322exports.GetSecretQuestionHandler = GetSecretQuestionHandler;323;324function SendPasswordResetEmailHandler(req, res) {325 console.log("SendPasswordResetEmailHandler");326 return "SendPasswordResetEmailHandler";327}328exports.SendPasswordResetEmailHandler = SendPasswordResetEmailHandler;329;330function VerifyResetPasswordCodeHandler(req, res) {331 console.log("VerifyResetPasswordCodeHandler");332 return "VerifyResetPasswordCodeHandler";333}334exports.VerifyResetPasswordCodeHandler = VerifyResetPasswordCodeHandler;335;336function ResetPasswordHandler(req, res) {337 console.log("ResetPasswordHandler");338 return "ResetPasswordHandler";339}340exports.ResetPasswordHandler = ResetPasswordHandler;341;342function GetUserInfoHandler(req, res) {343 console.log("GetUserInfoHandler");344 return "GetUserInfoHandler";345}346exports.GetUserInfoHandler = GetUserInfoHandler;347;348function ResendValidationEmailHandler(req, res) {349 console.log("ResendValidationEmailHandler");350 return "ResendValidationEmailHandler";351}352exports.ResendValidationEmailHandler = ResendValidationEmailHandler;353;354function SetLocaleHandler(req, res) {355 console.log("SetLocaleHandler");356 return "SetLocaleHandler";357}358exports.SetLocaleHandler = SetLocaleHandler;359;360function SetContactAddressHandler(req, res) {361 console.log("SetContactAddressHandler");362 return "SetContactAddressHandler";363}364exports.SetContactAddressHandler = SetContactAddressHandler;365;366function GetUserPrefsHandler(req, res) {367 console.log("GetUserPrefsHandler");368 return "GetUserPrefsHandler";369}370exports.GetUserPrefsHandler = GetUserPrefsHandler;371;372function SetUserPrefsHandler(req, res) {373 console.log("SetUserPrefsHandler");374 return "SetUserPrefsHandler";375}376exports.SetUserPrefsHandler = SetUserPrefsHandler;377;378function ChangePasswordHandler(req, res) {379 console.log("ChangePasswordHandler");380 return "ChangePasswordHandler";381}382exports.ChangePasswordHandler = ChangePasswordHandler;383;384function ChangeEmailAddressHandler(req, res) {385 console.log("ChangeEmailAddressHandler");386 return "ChangeEmailAddressHandler";387}388exports.ChangeEmailAddressHandler = ChangeEmailAddressHandler;389;390function RedeemAccessCodeHandler(req, res) {391 console.log("RedeemAccessCodeHandler");392 return "RedeemAccessCodeHandler";393}394exports.RedeemAccessCodeHandler = RedeemAccessCodeHandler;395;396function CrashReportHandler(req, res) {397 console.log("CrashReportHandler");398 return "CrashReportHandler";399}400exports.CrashReportHandler = CrashReportHandler;401;402function EventPingHandler(req, res) {403 console.log("EventPingHandler");404 return "EventPingHandler";405}406exports.EventPingHandler = EventPingHandler;407;408function CreateLobbyHandler(req, res) {409 console.log("CreateLobbyHandler");410 return "CreateLobbyHandler";411}412exports.CreateLobbyHandler = CreateLobbyHandler;413;414function GetLobbyJoinCodeHandler(req, res) {415 console.log("GetLobbyJoinCodeHandler");416 return "GetLobbyJoinCodeHandler";417}418exports.GetLobbyJoinCodeHandler = GetLobbyJoinCodeHandler;419;420function JoinLobbyByCodeHandler(req, res) {421 console.log("JoinLobbyByCodeHandler");422 return "JoinLobbyByCodeHandler";423}424exports.JoinLobbyByCodeHandler = JoinLobbyByCodeHandler;425;426function LeaveLobbyHandler(req, res) {427 console.log("LeaveLobbyHandler");428 return "LeaveLobbyHandler";429}430exports.LeaveLobbyHandler = LeaveLobbyHandler;431;432function LobbySetReadyHandler(req, res) {433 console.log("LobbySetReadyHandler");434 return "LobbySetReadyHandler";435}436exports.LobbySetReadyHandler = LobbySetReadyHandler;437;438function LobbySetOwnerHandler(req, res) {439 console.log("LobbySetOwnerHandler");440 return "LobbySetOwnerHandler";441}442exports.LobbySetOwnerHandler = LobbySetOwnerHandler;443;444function LobbySetGameOptionsHandler(req, res) {445 console.log("LobbySetGameOptionsHandler");446 return "LobbySetGameOptionsHandler";447}448exports.LobbySetGameOptionsHandler = LobbySetGameOptionsHandler;449;450function LobbyBanUserHandler(req, res) {451 console.log("LobbyBanUserHandler");452 return "LobbyBanUserHandler";453}454exports.LobbyBanUserHandler = LobbyBanUserHandler;455;456function LobbyRemoveUserHandler(req, res) {457 console.log("LobbyRemoveUserHandler");458 return "LobbyRemoveUserHandler";459}460exports.LobbyRemoveUserHandler = LobbyRemoveUserHandler;461;462function GetGameProfileHandler(req, res) {463 console.log("GetGameProfileHandler");464 return "GetGameProfileHandler";465}466exports.GetGameProfileHandler = GetGameProfileHandler;467;468function PingTestHandler(req, res) {469 console.log("PingTestHandler");470 return "PingTestHandler";471}472exports.PingTestHandler = PingTestHandler;473;474function GetMatchHandler(req, res) {475 console.log("GetMatchHandler");476 return "GetMatchHandler";477}478exports.GetMatchHandler = GetMatchHandler;479;480function ResumeGetMatchHandler(req, res) {481 console.log("ResumeGetMatchHandler");482 return "ResumeGetMatchHandler";483}484exports.ResumeGetMatchHandler = ResumeGetMatchHandler;485;486function CancelGetMatchHandler(req, res) {487 console.log("CancelGetMatchHandler");488 return "CancelGetMatchHandler";489}490exports.CancelGetMatchHandler = CancelGetMatchHandler;491;492function ResetGameHandler(req, res) {493 console.log("ResetGameHandler");494 return "ResetGameHandler";495}496exports.ResetGameHandler = ResetGameHandler;497;498function GetGameReplayRecordHandler(req, res) {499 console.log("GetGameReplayRecordHandler");500 return "GetGameReplayRecordHandler";501}502exports.GetGameReplayRecordHandler = GetGameReplayRecordHandler;503;504function DesyncReportHandler(req, res) {505 console.log("DesyncReportHandler");506 return "DesyncReportHandler";507}508exports.DesyncReportHandler = DesyncReportHandler;509;510function UpdatePlayerPreferencesHandler(req, res) {511 console.log("UpdatePlayerPreferencesHandler");512 return "UpdatePlayerPreferencesHandler";513}514exports.UpdatePlayerPreferencesHandler = UpdatePlayerPreferencesHandler;515;516function GetPlayerStatsHandler(req, res) {517 console.log("GetPlayerStatsHandler");518 return "GetPlayerStatsHandler";519}520exports.GetPlayerStatsHandler = GetPlayerStatsHandler;521;522function GetRecentGamesHandler(req, res) {523 console.log("GetRecentGamesHandler");524 return "GetRecentGamesHandler";525}526exports.GetRecentGamesHandler = GetRecentGamesHandler;527;528function LoginHandler(req, res) {529 res.json()530 .then(function (data) {531 console.log(data);532 var r = new pb.Reader(data);533 console.log(r);534 var x = protos.messages.Result.decode(r);535 console.log(x);536 })537 .catch(function (e) { return console.error(e); });538 console.log("LoginHandler");539 return "LoginHandler";540}541exports.LoginHandler = LoginHandler;542;543function GetGameSessionTicketHandler(req, res) {544 console.log("GetGameSessionTicketHandler");545 return "GetGameSessionTicketHandler";546}547exports.GetGameSessionTicketHandler = GetGameSessionTicketHandler;548;549function RedeemGameSessionTicketHandler(req, res) {550 console.log("RedeemGameSessionTicketHandler");551 return "RedeemGameSessionTicketHandler";552}553exports.RedeemGameSessionTicketHandler = RedeemGameSessionTicketHandler;554;555function LogoutHandler(req, res) {556 console.log("LogoutHandler");557 return "LogoutHandler";558}559exports.LogoutHandler = LogoutHandler;560;561function GetStoredPaymentMethodsHandler(req, res) {562 console.log("GetStoredPaymentMethodsHandler");563 return "GetStoredPaymentMethodsHandler";564}565exports.GetStoredPaymentMethodsHandler = GetStoredPaymentMethodsHandler;566;567function CreateStoredPaymentMethodHandler(req, res) {568 console.log("CreateStoredPaymentMethodHandler");569 return "CreateStoredPaymentMethodHandler";570}571exports.CreateStoredPaymentMethodHandler = CreateStoredPaymentMethodHandler;572;573function UpdateStoredPaymentMethodHandler(req, res) {574 console.log("UpdateStoredPaymentMethodHandler");575 return "UpdateStoredPaymentMethodHandler";576}577exports.UpdateStoredPaymentMethodHandler = UpdateStoredPaymentMethodHandler;578;579function SetDefaultStoredPaymentMethodHandler(req, res) {580 console.log("SetDefaultStoredPaymentMethodHandler");581 return "SetDefaultStoredPaymentMethodHandler";582}583exports.SetDefaultStoredPaymentMethodHandler = SetDefaultStoredPaymentMethodHandler;584;585function RemoveStoredPaymentMethodHandler(req, res) {586 console.log("RemoveStoredPaymentMethodHandler");587 return "RemoveStoredPaymentMethodHandler";588}589exports.RemoveStoredPaymentMethodHandler = RemoveStoredPaymentMethodHandler;590;591function SubmitPurchaseOrderHandler(req, res) {592 console.log("SubmitPurchaseOrderHandler");593 return "SubmitPurchaseOrderHandler";594}595exports.SubmitPurchaseOrderHandler = SubmitPurchaseOrderHandler;596;597function GetPurchaseOrderHandler(req, res) {598 console.log("GetPurchaseOrderHandler");599 return "GetPurchaseOrderHandler";600}601exports.GetPurchaseOrderHandler = GetPurchaseOrderHandler;602;603function GetAccountOrderHistoryHandler(req, res) {604 console.log("GetAccountOrderHistoryHandler");605 return "GetAccountOrderHistoryHandler";606}607exports.GetAccountOrderHistoryHandler = GetAccountOrderHistoryHandler;608;609function GetAccountBalanceHistoryHandler(req, res) {610 console.log("GetAccountBalanceHistoryHandler");611 return "GetAccountBalanceHistoryHandler";612}613exports.GetAccountBalanceHistoryHandler = GetAccountBalanceHistoryHandler;614;615function GetAccountBalanceHandler(req, res) {616 console.log("GetAccountBalanceHandler");617 return "GetAccountBalanceHandler";618}619exports.GetAccountBalanceHandler = GetAccountBalanceHandler;620;621function GetUserCountHandler(req, res) {622 console.log("GetUserCountHandler");623 return "GetUserCountHandler";624}625exports.GetUserCountHandler = GetUserCountHandler;626;627function GetUsersInRankedCountHandler(req, res) {628 console.log("GetUsersInRankedCountHandler");629 return "GetUsersInRankedCountHandler";630}631exports.GetUsersInRankedCountHandler = GetUsersInRankedCountHandler;632;633function InitHandlers(p) {634 protos = p;635}636exports.default = InitHandlers;637},{"protobufjs":16}],2:[function(require,module,exports){638"use strict";639Object.defineProperty(exports, "__esModule", { value: true });640var routes_1 = require("./routes");641var pb = require("./pb-handlers");642exports.protos = new pb.Protos();643exports.protos.onProtosLoad = function () {644 run();645};646function run() {647 routes_1.default(exports.protos);648 populateTestRoutesUI();649}650function populateTestRoutesUI() {651 routes_1.listOfRoutes.map(function (route) { return document.querySelector(".list-of-test-routes")652 .appendChild(generateHTML(route)); });653}654function generateHTML(route) {655 var container = document.createElement("div");656 container.className = "route-container";657 do {658 var padder = document.createElement("div");659 padder.className = "padder";660 container.appendChild(padder);661 do {662 var info = document.createElement("div");663 info.className = "route-info";664 padder.appendChild(info);665 do {666 var url = document.createElement("label");667 url.className = "route-info-url";668 url.innerText = "URL: " + route.url;669 info.appendChild(url);670 var code = document.createElement("pre");671 code.className = "route-info-code";672 console.log(route.data);673 code.innerText = "" + JSON.stringify(route.data);674 info.appendChild(code);675 } while (false);676 var actions = document.createElement("div");677 actions.className = "route-actions";678 padder.appendChild(actions);679 do {680 var allowExecution = document.createElement("input");681 allowExecution.type = "checkbox";682 actions.appendChild(allowExecution);683 var executeRoute = document.createElement("button");684 executeRoute.innerText = "Run Route";685 executeRoute.addEventListener("click", function () {686 routes_1.request(route);687 });688 actions.appendChild(executeRoute);689 } while (false);690 } while (false);691 } while (false);692 return container;693}694},{"./pb-handlers":3,"./routes":4}],3:[function(require,module,exports){695"use strict";696Object.defineProperty(exports, "__esModule", { value: true });697var pb = require("protobufjs");698var Protos = /** @class */ (function () {699 function Protos() {700 var _this = this;701 var root = new pb.Root({702 root: "/proto3 versions",703 });704 root.resolvePath = function (origin, file) {705 var str = this.options.root + "/" + file;706 // console.log(`Origin: "${origin}"; String: "${str}"`);707 return str;708 };709 pb.load([710 "tbui/tbcharacter.proto",711 "tbmatch/event.proto",712 "tbmatch/match.proto",713 "tbportal/portal.proto",714 "tbrpc/tbrpc.proto",715 "tbmatch/session.proto",716 ], root)717 .then(function (root) { return root.resolveAll(); })718 .then(function (root) {719 _this.messages = {720 Empty: root.lookupType(["tbrpc", "Empty"]),721 WaitMatchProgressEvent: root.lookupType(["tbmatch", "WaitMatchProgressEvent"]),722 Result: root.lookupType(["tbrpc", "Result"]),723 PingTestResult: root.lookupType(["tbmatch", "PingTestResult"]),724 GameEndpointConfig: root.lookupType(["tbmatch", "GameEndpointConfig"]),725 NetworkAddr: root.lookupType(["tbmatch", "NetworkAddr"]),726 LoginRequest: root.lookupType(["tbmatch", "LoginRequest"]),727 GetGameSessionTicketRequest: root.lookupType(["tbmatch", "GetGameSessionTicketRequest"]),728 GetGameSessionTicketResult: root.lookupType(["tbmatch", "GetGameSessionTicketResult"]),729 RedeemGameSessionTicketRequest: root.lookupType(["tbmatch", "RedeemGameSessionTicketRequest"]),730 GetMatchRequest: root.lookupType(["tbmatch", "GetMatchRequest"]),731 CreateLobbyRequest: root.lookupType(["tbmatch", "CreateLobbyRequest"]),732 GetLobbyJoinCodeRequest: root.lookupType(["tbmatch", "GetLobbyJoinCodeRequest"]),733 GetEventResult: root.lookupType(["tbmatch", "GetEventResult"]),734 Event: root.lookupType(["tbmatch", "Event"]),735 GetEventRequest: root.lookupType(["tbmatch", "GetEventRequest"]),736 PingTestCompleteEvent: root.lookupType(["tbmatch", "PingTestCompleteEvent"]),737 GameProfile: root.lookupType(["tbmatch", "GameProfile"]),738 PlayerStats: root.lookupType(["tbmatch", "PlayerStats"]),739 CharacterStats: root.lookupType(["tbmatch", "CharacterStats"]),740 PlayerPreferences: root.lookupType(["tbmatch", "PlayerPreferences"]),741 ClientFeatureSet: root.lookupType(["tbmatch", "ClientFeatureSet"]),742 FeatureValue: root.lookupType(["tbmatch", "FeatureValue"]),743 MatchCreatedEvent: root.lookupType(["tbmatch", "MatchCreatedEvent"]),744 GameConfig: root.lookupType(["tbmatch", "GameConfig"]),745 Player: root.lookupType(["tbmatch", "GameConfig", "Player"]),746 GameOptions: root.lookupType(["tbmatch", "GameOptions"]),747 CharacterSpec: root.lookupType(["tbmatch", "CharacterSpec"]),748 VariantSpec: root.lookupType(["tbmatch", "VariantSpec"]),749 LocMsg: root.lookupType(["tbrpc", "LocMsg"]),750 MsgParam: root.lookupType(["tbrpc", "MsgParam"]),751 GameSessionRequest: root.lookupType(["tbportal", "GameSessionRequest"]),752 ClientSpec: root.lookupType(["tbportal", "ClientSpec"]),753 };754 _this.enums = {755 Status: root.lookupEnum(["tbrpc", "Status"]),756 GameType: root.lookupEnum(["tbmatch", "GameType"]),757 };758 _this.onProtosLoad();759 })760 .catch(function (e) { return console.error("Problem loading protos: " + e); });761 }762 return Protos;763}());764exports.Protos = Protos;765},{"protobufjs":16}],4:[function(require,module,exports){766"use strict";767Object.defineProperty(exports, "__esModule", { value: true });768var node_fetch_1 = require("node-fetch");769var handlers_1 = require("./handlers"), handlers = handlers_1;770var protos = null;771function InitRoutes(p) {772 protos = p;773 onProtosLoad();774 handlers_1.default(p);775}776exports.default = InitRoutes;777var RouteListItem = /** @class */ (function () {778 function RouteListItem(url, data, handler) {779 this.url = url;780 this.data = data;781 this.handler = handler;782 }783 return RouteListItem;784}());785exports.RouteListItem = RouteListItem;786exports.listOfRoutes = [];787function onProtosLoad() {788 exports.listOfRoutes = [789 new RouteListItem("/ryzthn/rpc/GetEvent", protos.messages.Empty.create({}), handlers.GetEventHandler),790 new RouteListItem("/ryzthn/rpc/LookupUser", protos.messages.UserInfo.create({}), handlers.LookupUserHandler),791 new RouteListItem("/ryzthn/rpc/SearchUsers", protos.messages.SearchUsersResult.create({}), handlers.SearchUsersHandler),792 new RouteListItem("/ryzthn/rpc/CreateUser", protos.messages.CreateUserResult.create({}), handlers.CreateUserHandler),793 new RouteListItem("/ryzthn/rpc/UpdateUser", protos.messages.Empty.create({}), handlers.UpdateUserHandler),794 new RouteListItem("/ryzthn/rpc/SetUserContactAddress", protos.messages.Empty.create({}), handlers.SetUserContactAddressHandler),795 new RouteListItem("/ryzthn/rpc/SetUserAccess", protos.messages.Empty.create({}), handlers.SetUserAccessHandler),796 new RouteListItem("/ryzthn/rpc/SetUserLoginStatus", protos.messages.Empty.create({}), handlers.SetUserLoginStatusHandler),797 new RouteListItem("/ryzthn/rpc/ResetUserPassword", protos.messages.Empty.create({}), handlers.ResetUserPasswordHandler),798 new RouteListItem("/ryzthn/rpc/NukeHandle", protos.messages.NukeHandleResult.create({}), handlers.NukeHandleHandler),799 new RouteListItem("/ryzthn/rpc/GetHandleHistory", protos.messages.GetHandleHistoryResult.create({}), handlers.GetHandleHistoryHandler),800 new RouteListItem("/ryzthn/rpc/SendUserEmailNotification", protos.messages.Empty.create({}), handlers.SendUserEmailNotificationHandler),801 new RouteListItem("/ryzthn/rpc/SearchAuditHistory", protos.messages.SearchAuditHistoryResult.create({}), handlers.SearchAuditHistoryHandler),802 new RouteListItem("/ryzthn/rpc/GetAppConfig", protos.messages.AppConfig.create({}), handlers.GetAppConfigHandler),803 new RouteListItem("/ryzthn/rpc/GetGlobalConfig", protos.messages.GetGlobalConfigResult.create({}), handlers.GetGlobalConfigHandler),804 new RouteListItem("/ryzthn/rpc/SetGlobalConfig", protos.messages.Empty.create({}), handlers.SetGlobalConfigHandler),805 new RouteListItem("/ryzthn/rpc/GetMatchQueueConfig", protos.messages.GetMatchQueueConfigResult.create({}), handlers.GetMatchQueueConfigHandler),806 new RouteListItem("/ryzthn/rpc/SetMatchQueueConfig", protos.messages.Empty.create({}), handlers.SetMatchQueueConfigHandler),807 new RouteListItem("/ryzthn/rpc/GetMatchUserConfig", protos.messages.GetMatchUserConfigResult.create({}), handlers.GetMatchUserConfigHandler),808 new RouteListItem("/ryzthn/rpc/SetMatchUserConfig", protos.messages.Empty.create({}), handlers.SetMatchUserConfigHandler),809 new RouteListItem("/ryzthn/rpc/GetLobbyConfig", protos.messages.GetLobbyConfigResult.create({}), handlers.GetLobbyConfigHandler),810 new RouteListItem("/ryzthn/rpc/SetLobbyConfig", protos.messages.Empty.create({}), handlers.SetLobbyConfigHandler),811 new RouteListItem("/ryzthn/rpc/ListFeatureDefinitions", protos.messages.ListFeatureDefinitionsResult.create({}), handlers.ListFeatureDefinitionsHandler),812 new RouteListItem("/ryzthn/rpc/SetFeatureDefinition", protos.messages.Empty.create({}), handlers.SetFeatureDefinitionHandler),813 new RouteListItem("/ryzthn/rpc/DeleteFeatureDefinition", protos.messages.Empty.create({}), handlers.DeleteFeatureDefinitionHandler),814 new RouteListItem("/ryzthn/rpc/ListFeatureRules", protos.messages.ListFeatureRulesResult.create({}), handlers.ListFeatureRulesHandler),815 new RouteListItem("/ryzthn/rpc/GetActiveFeatures", protos.messages.GetActiveFeaturesResult.create({}), handlers.GetActiveFeaturesHandler),816 new RouteListItem("/ryzthn/rpc/CreateFeatureRule", protos.messages.Empty.create({}), handlers.CreateFeatureRuleHandler),817 new RouteListItem("/ryzthn/rpc/UpdateFeatureRule", protos.messages.Empty.create({}), handlers.UpdateFeatureRuleHandler),818 new RouteListItem("/ryzthn/rpc/DeleteFeatureRule", protos.messages.Empty.create({}), handlers.DeleteFeatureRuleHandler),819 new RouteListItem("/ryzthn/rpc/GetMatchQueueUsers", protos.messages.GetMatchQueueUsersResult.create({}), handlers.GetMatchQueueUsersHandler),820 new RouteListItem("/ryzthn/rpc/GetLobbies", protos.messages.GetLobbiesResult.create({}), handlers.GetLobbiesHandler),821 new RouteListItem("/ryzthn/rpc/GetLobby", protos.messages.GetLobbyResult.create({}), handlers.GetLobbyHandler),822 new RouteListItem("/ryzthn/rpc/GetActiveMatches", protos.messages.GetActiveMatchesResult.create({}), handlers.GetActiveMatchesHandler),823 new RouteListItem("/ryzthn/rpc/GetActiveMatch", protos.messages.GetActiveMatchResult.create({}), handlers.GetActiveMatchHandler),824 new RouteListItem("/ryzthn/rpc/GetRecentMatches", protos.messages.GetRecentMatchesResult.create({}), handlers.GetRecentMatchesHandler),825 new RouteListItem("/ryzthn/rpc/GetMatchDetail", protos.messages.GetMatchDetailResult.create({}), handlers.GetMatchDetailHandler),826 new RouteListItem("/ryzthn/rpc/GetPlayerDetail", protos.messages.GetPlayerDetailResult.create({}), handlers.GetPlayerDetailHandler),827 new RouteListItem("/ryzthn/rpc/ListDesyncs", protos.messages.ListDesyncsResult.create({}), handlers.ListDesyncsHandler),828 new RouteListItem("/ryzthn/rpc/ListCrashes", protos.messages.ListCrashesResult.create({}), handlers.ListCrashesHandler),829 new RouteListItem("/ryzthn/rpc/ListCrashBuildIdentifiers", protos.messages.ListCrashBuildIdentifiersResult.create({}), handlers.ListCrashBuildIdentifiersHandler),830 new RouteListItem("/ryzthn/rpc/ListCrashCollections", protos.messages.ListCrashCollectionsResult.create({}), handlers.ListCrashCollectionsHandler),831 new RouteListItem("/ryzthn/rpc/SearchPurchaseOrders", protos.messages.SearchPurchaseOrdersResult.create({}), handlers.SearchPurchaseOrdersHandler),832 new RouteListItem("/ryzthn/rpc/SyncPurchaseOrder", protos.messages.Empty.create({}), handlers.SyncPurchaseOrderHandler),833 new RouteListItem("/ryzthn/rpc/VoidPurchaseOrder", protos.messages.Empty.create({}), handlers.VoidPurchaseOrderHandler),834 new RouteListItem("/ryzthn/rpc/RefundPurchaseOrder", protos.messages.Empty.create({}), handlers.RefundPurchaseOrderHandler),835 new RouteListItem("/ryzthn/rpc/CountUsers", protos.messages.UserCountStats.create({}), handlers.CountUsersHandler),836 new RouteListItem("/ryzthn/rpc/GetSessions", protos.messages.GetSessionsResult.create({}), handlers.GetSessionsHandler),837 new RouteListItem("/ryzthn/rpc/GetCharacterUsage", protos.messages.GetCharacterUsageResult.create({}), handlers.GetCharacterUsageHandler),838 new RouteListItem("/ryzthn/rpc/CheckHandle", protos.messages.Empty.create({}), handlers.CheckHandleHandler),839 new RouteListItem("/ryzthn/rpc/RegisterUser", protos.messages.Empty.create({}), handlers.RegisterUserHandler),840 new RouteListItem("/ryzthn/rpc/ValidateUser", protos.messages.UserInfo.create({}), handlers.ValidateUserHandler),841 new RouteListItem("/ryzthn/rpc/GetSecretQuestion", protos.messages.GetSecretQuestionResult.create({}), handlers.GetSecretQuestionHandler),842 new RouteListItem("/ryzthn/rpc/SendPasswordResetEmail", protos.messages.Empty.create({}), handlers.SendPasswordResetEmailHandler),843 new RouteListItem("/ryzthn/rpc/VerifyResetPasswordCode", protos.messages.Empty.create({}), handlers.VerifyResetPasswordCodeHandler),844 new RouteListItem("/ryzthn/rpc/ResetPassword", protos.messages.Empty.create({}), handlers.ResetPasswordHandler),845 new RouteListItem("/ryzthn/rpc/GetUserInfo", protos.messages.UserInfo.create({}), handlers.GetUserInfoHandler),846 new RouteListItem("/ryzthn/rpc/ResendValidationEmail", protos.messages.Empty.create({}), handlers.ResendValidationEmailHandler),847 new RouteListItem("/ryzthn/rpc/SetLocale", protos.messages.Empty.create({}), handlers.SetLocaleHandler),848 new RouteListItem("/ryzthn/rpc/SetContactAddress", protos.messages.Empty.create({}), handlers.SetContactAddressHandler),849 new RouteListItem("/ryzthn/rpc/GetUserPrefs", protos.messages.UserPrefs.create({}), handlers.GetUserPrefsHandler),850 new RouteListItem("/ryzthn/rpc/SetUserPrefs", protos.messages.Empty.create({}), handlers.SetUserPrefsHandler),851 new RouteListItem("/ryzthn/rpc/ChangePassword", protos.messages.Empty.create({}), handlers.ChangePasswordHandler),852 new RouteListItem("/ryzthn/rpc/ChangeEmailAddress", protos.messages.Empty.create({}), handlers.ChangeEmailAddressHandler),853 new RouteListItem("/ryzthn/rpc/RedeemAccessCode", protos.messages.Empty.create({}), handlers.RedeemAccessCodeHandler),854 new RouteListItem("/ryzthn/rpc/CrashReport", protos.messages.Empty.create({}), handlers.CrashReportHandler),855 new RouteListItem("/ryzthn/rpc/EventPing", protos.messages.Empty.create({}), handlers.EventPingHandler),856 new RouteListItem("/ryzthn/rpc/CreateLobby", protos.messages.Empty.create({}), handlers.CreateLobbyHandler),857 new RouteListItem("/ryzthn/rpc/GetLobbyJoinCode", protos.messages.GetLobbyJoinCodeResult.create({}), handlers.GetLobbyJoinCodeHandler),858 new RouteListItem("/ryzthn/rpc/JoinLobbyByCode", protos.messages.Empty.create({}), handlers.JoinLobbyByCodeHandler),859 new RouteListItem("/ryzthn/rpc/LeaveLobby", protos.messages.Empty.create({}), handlers.LeaveLobbyHandler),860 new RouteListItem("/ryzthn/rpc/LobbySetReady", protos.messages.Empty.create({}), handlers.LobbySetReadyHandler),861 new RouteListItem("/ryzthn/rpc/LobbySetOwner", protos.messages.Empty.create({}), handlers.LobbySetOwnerHandler),862 new RouteListItem("/ryzthn/rpc/LobbySetGameOptions", protos.messages.Empty.create({}), handlers.LobbySetGameOptionsHandler),863 new RouteListItem("/ryzthn/rpc/LobbyBanUser", protos.messages.Empty.create({}), handlers.LobbyBanUserHandler),864 new RouteListItem("/ryzthn/rpc/LobbyRemoveUser", protos.messages.Empty.create({}), handlers.LobbyRemoveUserHandler),865 new RouteListItem("/ryzthn/rpc/GetGameProfile", protos.messages.GameProfile.create({}), handlers.GetGameProfileHandler),866 new RouteListItem("/ryzthn/rpc/PingTest", protos.messages.PingTestResult.create({}), handlers.PingTestHandler),867 new RouteListItem("/ryzthn/rpc/GetMatch", protos.messages.Empty.create({}), handlers.GetMatchHandler),868 new RouteListItem("/ryzthn/rpc/ResumeGetMatch", protos.messages.Empty.create({}), handlers.ResumeGetMatchHandler),869 new RouteListItem("/ryzthn/rpc/CancelGetMatch", protos.messages.Empty.create({}), handlers.CancelGetMatchHandler),870 new RouteListItem("/ryzthn/rpc/ResetGame", protos.messages.Empty.create({}), handlers.ResetGameHandler),871 new RouteListItem("/ryzthn/rpc/GetGameReplayRecord", protos.messages.GetGameReplayRecordResult.create({}), handlers.GetGameReplayRecordHandler),872 new RouteListItem("/ryzthn/rpc/DesyncReport", protos.messages.Empty.create({}), handlers.DesyncReportHandler),873 new RouteListItem("/ryzthn/rpc/UpdatePlayerPreferences", protos.messages.Empty.create({}), handlers.UpdatePlayerPreferencesHandler),874 new RouteListItem("/ryzthn/rpc/GetPlayerStats", protos.messages.GetPlayerStatsResult.create({}), handlers.GetPlayerStatsHandler),875 new RouteListItem("/ryzthn/rpc/GetRecentGames", protos.messages.GetRecentGamesResult.create({}), handlers.GetRecentGamesHandler),876 new RouteListItem("/ryzthn/rpc/Login", protos.messages.LoginRequest.create({877 // Either handle or e-mail address can be used.878 login: "1",879 password: "2",880 // Client build. May require certain version to login.881 buildVersion: "5",882 }), handlers.LoginHandler),883 new RouteListItem("/ryzthn/rpc/GetGameSessionTicket", protos.messages.GetGameSessionTicketResult.create({}), handlers.GetGameSessionTicketHandler),884 new RouteListItem("/ryzthn/rpc/RedeemGameSessionTicket", protos.messages.Empty.create({}), handlers.RedeemGameSessionTicketHandler),885 new RouteListItem("/ryzthn/rpc/Logout", protos.messages.Empty.create({}), handlers.LogoutHandler),886 new RouteListItem("/ryzthn/rpc/GetStoredPaymentMethods", protos.messages.GetStoredPaymentMethodsResult.create({}), handlers.GetStoredPaymentMethodsHandler),887 new RouteListItem("/ryzthn/rpc/CreateStoredPaymentMethod", protos.messages.Empty.create({}), handlers.CreateStoredPaymentMethodHandler),888 new RouteListItem("/ryzthn/rpc/UpdateStoredPaymentMethod", protos.messages.Empty.create({}), handlers.UpdateStoredPaymentMethodHandler),889 new RouteListItem("/ryzthn/rpc/SetDefaultStoredPaymentMethod", protos.messages.Empty.create({}), handlers.SetDefaultStoredPaymentMethodHandler),890 new RouteListItem("/ryzthn/rpc/RemoveStoredPaymentMethod", protos.messages.Empty.create({}), handlers.RemoveStoredPaymentMethodHandler),891 new RouteListItem("/ryzthn/rpc/SubmitPurchaseOrder", protos.messages.SubmitPurchaseOrderResult.create({}), handlers.SubmitPurchaseOrderHandler),892 new RouteListItem("/ryzthn/rpc/GetPurchaseOrder", protos.messages.PurchaseOrder.create({}), handlers.GetPurchaseOrderHandler),893 new RouteListItem("/ryzthn/rpc/GetAccountOrderHistory", protos.messages.GetAccountOrderHistoryResult.create({}), handlers.GetAccountOrderHistoryHandler),894 new RouteListItem("/ryzthn/rpc/GetAccountBalanceHistory", protos.messages.GetAccountBalanceHistoryResult.create({}), handlers.GetAccountBalanceHistoryHandler),895 new RouteListItem("/ryzthn/rpc/GetAccountBalance", protos.messages.GetAccountBalanceResult.create({}), handlers.GetAccountBalanceHandler),896 ];897}898exports.onProtosLoad = onProtosLoad;899function request(route) {900 console.log(route.data);901 // const final = createResultPayload(route.data.$type.encode(route.data).finish());902 var final = route.data.$type.encode(route.data).finish();903 node_fetch_1.default("https://localhost:" + (getPort() || 8000) + route.url, {904 "method": "POST",905 "body": JSON.stringify(Array.from(final))906 })907 .then(function (res) { return route.handler(res); })908 .catch(function (e) {909 console.error("Could not complete the request. " + e);910 });911}912exports.request = request;913function createResultPayload(mainDataEncoded) {914 var ResultPayload = {915 result: protos.enums.Status.values.S_SUCCESS,916 content: mainDataEncoded917 };918 var err = protos.messages.Result.verify(ResultPayload);919 if (err) {920 console.error(err);921 return;922 }923 var resultData = protos.messages.Result.create(ResultPayload);924 var final = protos.messages.Result.encode(resultData).finish();925 return final;926}927function parseURLSearch() {928 var searchValues = {};929 location.search.replace(/^./, "")930 .split("&")931 .map(function (pair) {932 var pairArray = pair.split("=");933 searchValues[pairArray[0]] = pairArray[1];934 });935 return searchValues;936}937function getPort() {938 return document.querySelector(".port-input").value;939}940},{"./handlers":1,"node-fetch":15}],5:[function(require,module,exports){941"use strict";942module.exports = asPromise;943/**944 * Callback as used by {@link util.asPromise}.945 * @typedef asPromiseCallback946 * @type {function}947 * @param {Error|null} error Error, if any948 * @param {...*} params Additional arguments949 * @returns {undefined}950 */951/**952 * Returns a promise from a node-style callback function.953 * @memberof util954 * @param {asPromiseCallback} fn Function to call955 * @param {*} ctx Function context956 * @param {...*} params Function arguments957 * @returns {Promise<*>} Promisified function958 */959function asPromise(fn, ctx/*, varargs */) {960 var params = new Array(arguments.length - 1),961 offset = 0,962 index = 2,963 pending = true;964 while (index < arguments.length)965 params[offset++] = arguments[index++];966 return new Promise(function executor(resolve, reject) {967 params[offset] = function callback(err/*, varargs */) {968 if (pending) {969 pending = false;970 if (err)971 reject(err);972 else {973 var params = new Array(arguments.length - 1),974 offset = 0;975 while (offset < params.length)976 params[offset++] = arguments[offset];977 resolve.apply(null, params);978 }979 }980 };981 try {982 fn.apply(ctx || null, params);983 } catch (err) {984 if (pending) {985 pending = false;986 reject(err);987 }988 }989 });990}991},{}],6:[function(require,module,exports){992"use strict";993/**994 * A minimal base64 implementation for number arrays.995 * @memberof util996 * @namespace997 */998var base64 = exports;999/**1000 * Calculates the byte length of a base64 encoded string.1001 * @param {string} string Base64 encoded string1002 * @returns {number} Byte length1003 */1004base64.length = function length(string) {1005 var p = string.length;1006 if (!p)1007 return 0;1008 var n = 0;1009 while (--p % 4 > 1 && string.charAt(p) === "=")1010 ++n;1011 return Math.ceil(string.length * 3) / 4 - n;1012};1013// Base64 encoding table1014var b64 = new Array(64);1015// Base64 decoding table1016var s64 = new Array(123);1017// 65..90, 97..122, 48..57, 43, 471018for (var i = 0; i < 64;)1019 s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;1020/**1021 * Encodes a buffer to a base64 encoded string.1022 * @param {Uint8Array} buffer Source buffer1023 * @param {number} start Source start1024 * @param {number} end Source end1025 * @returns {string} Base64 encoded string1026 */1027base64.encode = function encode(buffer, start, end) {1028 var parts = null,1029 chunk = [];1030 var i = 0, // output index1031 j = 0, // goto index1032 t; // temporary1033 while (start < end) {1034 var b = buffer[start++];1035 switch (j) {1036 case 0:1037 chunk[i++] = b64[b >> 2];1038 t = (b & 3) << 4;1039 j = 1;1040 break;1041 case 1:1042 chunk[i++] = b64[t | b >> 4];1043 t = (b & 15) << 2;1044 j = 2;1045 break;1046 case 2:1047 chunk[i++] = b64[t | b >> 6];1048 chunk[i++] = b64[b & 63];1049 j = 0;1050 break;1051 }1052 if (i > 8191) {1053 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));1054 i = 0;1055 }1056 }1057 if (j) {1058 chunk[i++] = b64[t];1059 chunk[i++] = 61;1060 if (j === 1)1061 chunk[i++] = 61;1062 }1063 if (parts) {1064 if (i)1065 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));1066 return parts.join("");1067 }1068 return String.fromCharCode.apply(String, chunk.slice(0, i));1069};1070var invalidEncoding = "invalid encoding";1071/**1072 * Decodes a base64 encoded string to a buffer.1073 * @param {string} string Source string1074 * @param {Uint8Array} buffer Destination buffer1075 * @param {number} offset Destination offset1076 * @returns {number} Number of bytes written1077 * @throws {Error} If encoding is invalid1078 */1079base64.decode = function decode(string, buffer, offset) {1080 var start = offset;1081 var j = 0, // goto index1082 t; // temporary1083 for (var i = 0; i < string.length;) {1084 var c = string.charCodeAt(i++);1085 if (c === 61 && j > 1)1086 break;1087 if ((c = s64[c]) === undefined)1088 throw Error(invalidEncoding);1089 switch (j) {1090 case 0:1091 t = c;1092 j = 1;1093 break;1094 case 1:1095 buffer[offset++] = t << 2 | (c & 48) >> 4;1096 t = c;1097 j = 2;1098 break;1099 case 2:1100 buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;1101 t = c;1102 j = 3;1103 break;1104 case 3:1105 buffer[offset++] = (t & 3) << 6 | c;1106 j = 0;1107 break;1108 }1109 }1110 if (j === 1)1111 throw Error(invalidEncoding);1112 return offset - start;1113};1114/**1115 * Tests if the specified string appears to be base64 encoded.1116 * @param {string} string String to test1117 * @returns {boolean} `true` if probably base64 encoded, otherwise false1118 */1119base64.test = function test(string) {1120 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);1121};1122},{}],7:[function(require,module,exports){1123"use strict";1124module.exports = codegen;1125/**1126 * Begins generating a function.1127 * @memberof util1128 * @param {string[]} functionParams Function parameter names1129 * @param {string} [functionName] Function name if not anonymous1130 * @returns {Codegen} Appender that appends code to the function's body1131 */1132function codegen(functionParams, functionName) {1133 /* istanbul ignore if */1134 if (typeof functionParams === "string") {1135 functionName = functionParams;1136 functionParams = undefined;1137 }1138 var body = [];1139 /**1140 * Appends code to the function's body or finishes generation.1141 * @typedef Codegen1142 * @type {function}1143 * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any1144 * @param {...*} [formatParams] Format parameters1145 * @returns {Codegen|Function} Itself or the generated function if finished1146 * @throws {Error} If format parameter counts do not match1147 */1148 function Codegen(formatStringOrScope) {1149 // note that explicit array handling below makes this ~50% faster1150 // finish the function1151 if (typeof formatStringOrScope !== "string") {1152 var source = toString();1153 if (codegen.verbose)1154 console.log("codegen: " + source); // eslint-disable-line no-console1155 source = "return " + source;1156 if (formatStringOrScope) {1157 var scopeKeys = Object.keys(formatStringOrScope),1158 scopeParams = new Array(scopeKeys.length + 1),1159 scopeValues = new Array(scopeKeys.length),1160 scopeOffset = 0;1161 while (scopeOffset < scopeKeys.length) {1162 scopeParams[scopeOffset] = scopeKeys[scopeOffset];1163 scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];1164 }1165 scopeParams[scopeOffset] = source;1166 return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func1167 }1168 return Function(source)(); // eslint-disable-line no-new-func1169 }1170 // otherwise append to body1171 var formatParams = new Array(arguments.length - 1),1172 formatOffset = 0;1173 while (formatOffset < formatParams.length)1174 formatParams[formatOffset] = arguments[++formatOffset];1175 formatOffset = 0;1176 formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {1177 var value = formatParams[formatOffset++];1178 switch ($1) {1179 case "d": case "f": return String(Number(value));1180 case "i": return String(Math.floor(value));1181 case "j": return JSON.stringify(value);1182 case "s": return String(value);1183 }1184 return "%";1185 });1186 if (formatOffset !== formatParams.length)1187 throw Error("parameter count mismatch");1188 body.push(formatStringOrScope);1189 return Codegen;1190 }1191 function toString(functionNameOverride) {1192 return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";1193 }1194 Codegen.toString = toString;1195 return Codegen;1196}1197/**1198 * Begins generating a function.1199 * @memberof util1200 * @function codegen1201 * @param {string} [functionName] Function name if not anonymous1202 * @returns {Codegen} Appender that appends code to the function's body1203 * @variation 21204 */1205/**1206 * When set to `true`, codegen will log generated code to console. Useful for debugging.1207 * @name util.codegen.verbose1208 * @type {boolean}1209 */1210codegen.verbose = false;1211},{}],8:[function(require,module,exports){1212"use strict";1213module.exports = EventEmitter;1214/**1215 * Constructs a new event emitter instance.1216 * @classdesc A minimal event emitter.1217 * @memberof util1218 * @constructor1219 */1220function EventEmitter() {1221 /**1222 * Registered listeners.1223 * @type {Object.<string,*>}1224 * @private1225 */1226 this._listeners = {};1227}1228/**1229 * Registers an event listener.1230 * @param {string} evt Event name1231 * @param {function} fn Listener1232 * @param {*} [ctx] Listener context1233 * @returns {util.EventEmitter} `this`1234 */1235EventEmitter.prototype.on = function on(evt, fn, ctx) {1236 (this._listeners[evt] || (this._listeners[evt] = [])).push({1237 fn : fn,1238 ctx : ctx || this1239 });1240 return this;1241};1242/**1243 * Removes an event listener or any matching listeners if arguments are omitted.1244 * @param {string} [evt] Event name. Removes all listeners if omitted.1245 * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.1246 * @returns {util.EventEmitter} `this`1247 */1248EventEmitter.prototype.off = function off(evt, fn) {1249 if (evt === undefined)1250 this._listeners = {};1251 else {1252 if (fn === undefined)1253 this._listeners[evt] = [];1254 else {1255 var listeners = this._listeners[evt];1256 for (var i = 0; i < listeners.length;)1257 if (listeners[i].fn === fn)1258 listeners.splice(i, 1);1259 else1260 ++i;1261 }1262 }1263 return this;1264};1265/**1266 * Emits an event by calling its listeners with the specified arguments.1267 * @param {string} evt Event name1268 * @param {...*} args Arguments1269 * @returns {util.EventEmitter} `this`1270 */1271EventEmitter.prototype.emit = function emit(evt) {1272 var listeners = this._listeners[evt];1273 if (listeners) {1274 var args = [],1275 i = 1;1276 for (; i < arguments.length;)1277 args.push(arguments[i++]);1278 for (i = 0; i < listeners.length;)1279 listeners[i].fn.apply(listeners[i++].ctx, args);1280 }1281 return this;1282};1283},{}],9:[function(require,module,exports){1284"use strict";1285module.exports = fetch;1286var asPromise = require("@protobufjs/aspromise"),1287 inquire = require("@protobufjs/inquire");1288var fs = inquire("fs");1289/**1290 * Node-style callback as used by {@link util.fetch}.1291 * @typedef FetchCallback1292 * @type {function}1293 * @param {?Error} error Error, if any, otherwise `null`1294 * @param {string} [contents] File contents, if there hasn't been an error1295 * @returns {undefined}1296 */1297/**1298 * Options as used by {@link util.fetch}.1299 * @typedef FetchOptions1300 * @type {Object}1301 * @property {boolean} [binary=false] Whether expecting a binary response1302 * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest1303 */1304/**1305 * Fetches the contents of a file.1306 * @memberof util1307 * @param {string} filename File path or url1308 * @param {FetchOptions} options Fetch options1309 * @param {FetchCallback} callback Callback function1310 * @returns {undefined}1311 */1312function fetch(filename, options, callback) {1313 if (typeof options === "function") {1314 callback = options;1315 options = {};1316 } else if (!options)1317 options = {};1318 if (!callback)1319 return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this1320 // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.1321 if (!options.xhr && fs && fs.readFile)1322 return fs.readFile(filename, function fetchReadFileCallback(err, contents) {1323 return err && typeof XMLHttpRequest !== "undefined"1324 ? fetch.xhr(filename, options, callback)1325 : err1326 ? callback(err)1327 : callback(null, options.binary ? contents : contents.toString("utf8"));1328 });1329 // use the XHR version otherwise.1330 return fetch.xhr(filename, options, callback);1331}1332/**1333 * Fetches the contents of a file.1334 * @name util.fetch1335 * @function1336 * @param {string} path File path or url1337 * @param {FetchCallback} callback Callback function1338 * @returns {undefined}1339 * @variation 21340 */1341/**1342 * Fetches the contents of a file.1343 * @name util.fetch1344 * @function1345 * @param {string} path File path or url1346 * @param {FetchOptions} [options] Fetch options1347 * @returns {Promise<string|Uint8Array>} Promise1348 * @variation 31349 */1350/**/1351fetch.xhr = function fetch_xhr(filename, options, callback) {1352 var xhr = new XMLHttpRequest();1353 xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {1354 if (xhr.readyState !== 4)1355 return undefined;1356 // local cors security errors return status 0 / empty string, too. afaik this cannot be1357 // reliably distinguished from an actually empty file for security reasons. feel free1358 // to send a pull request if you are aware of a solution.1359 if (xhr.status !== 0 && xhr.status !== 200)1360 return callback(Error("status " + xhr.status));1361 // if binary data is expected, make sure that some sort of array is returned, even if1362 // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.1363 if (options.binary) {1364 var buffer = xhr.response;1365 if (!buffer) {1366 buffer = [];1367 for (var i = 0; i < xhr.responseText.length; ++i)1368 buffer.push(xhr.responseText.charCodeAt(i) & 255);1369 }1370 return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);1371 }1372 return callback(null, xhr.responseText);1373 };1374 if (options.binary) {1375 // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers1376 if ("overrideMimeType" in xhr)1377 xhr.overrideMimeType("text/plain; charset=x-user-defined");1378 xhr.responseType = "arraybuffer";1379 }1380 xhr.open("GET", filename);1381 xhr.send();1382};1383},{"@protobufjs/aspromise":5,"@protobufjs/inquire":11}],10:[function(require,module,exports){1384"use strict";1385module.exports = factory(factory);1386/**1387 * Reads / writes floats / doubles from / to buffers.1388 * @name util.float1389 * @namespace1390 */1391/**1392 * Writes a 32 bit float to a buffer using little endian byte order.1393 * @name util.float.writeFloatLE1394 * @function1395 * @param {number} val Value to write1396 * @param {Uint8Array} buf Target buffer1397 * @param {number} pos Target buffer offset1398 * @returns {undefined}1399 */1400/**1401 * Writes a 32 bit float to a buffer using big endian byte order.1402 * @name util.float.writeFloatBE1403 * @function1404 * @param {number} val Value to write1405 * @param {Uint8Array} buf Target buffer1406 * @param {number} pos Target buffer offset1407 * @returns {undefined}1408 */1409/**1410 * Reads a 32 bit float from a buffer using little endian byte order.1411 * @name util.float.readFloatLE1412 * @function1413 * @param {Uint8Array} buf Source buffer1414 * @param {number} pos Source buffer offset1415 * @returns {number} Value read1416 */1417/**1418 * Reads a 32 bit float from a buffer using big endian byte order.1419 * @name util.float.readFloatBE1420 * @function1421 * @param {Uint8Array} buf Source buffer1422 * @param {number} pos Source buffer offset1423 * @returns {number} Value read1424 */1425/**1426 * Writes a 64 bit double to a buffer using little endian byte order.1427 * @name util.float.writeDoubleLE1428 * @function1429 * @param {number} val Value to write1430 * @param {Uint8Array} buf Target buffer1431 * @param {number} pos Target buffer offset1432 * @returns {undefined}1433 */1434/**1435 * Writes a 64 bit double to a buffer using big endian byte order.1436 * @name util.float.writeDoubleBE1437 * @function1438 * @param {number} val Value to write1439 * @param {Uint8Array} buf Target buffer1440 * @param {number} pos Target buffer offset1441 * @returns {undefined}1442 */1443/**1444 * Reads a 64 bit double from a buffer using little endian byte order.1445 * @name util.float.readDoubleLE1446 * @function1447 * @param {Uint8Array} buf Source buffer1448 * @param {number} pos Source buffer offset1449 * @returns {number} Value read1450 */1451/**1452 * Reads a 64 bit double from a buffer using big endian byte order.1453 * @name util.float.readDoubleBE1454 * @function1455 * @param {Uint8Array} buf Source buffer1456 * @param {number} pos Source buffer offset1457 * @returns {number} Value read1458 */1459// Factory function for the purpose of node-based testing in modified global environments1460function factory(exports) {1461 // float: typed array1462 if (typeof Float32Array !== "undefined") (function() {1463 var f32 = new Float32Array([ -0 ]),1464 f8b = new Uint8Array(f32.buffer),1465 le = f8b[3] === 128;1466 function writeFloat_f32_cpy(val, buf, pos) {1467 f32[0] = val;1468 buf[pos ] = f8b[0];1469 buf[pos + 1] = f8b[1];1470 buf[pos + 2] = f8b[2];1471 buf[pos + 3] = f8b[3];1472 }1473 function writeFloat_f32_rev(val, buf, pos) {1474 f32[0] = val;1475 buf[pos ] = f8b[3];1476 buf[pos + 1] = f8b[2];1477 buf[pos + 2] = f8b[1];1478 buf[pos + 3] = f8b[0];1479 }1480 /* istanbul ignore next */1481 exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;1482 /* istanbul ignore next */1483 exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;1484 function readFloat_f32_cpy(buf, pos) {1485 f8b[0] = buf[pos ];1486 f8b[1] = buf[pos + 1];1487 f8b[2] = buf[pos + 2];1488 f8b[3] = buf[pos + 3];1489 return f32[0];1490 }1491 function readFloat_f32_rev(buf, pos) {1492 f8b[3] = buf[pos ];1493 f8b[2] = buf[pos + 1];1494 f8b[1] = buf[pos + 2];1495 f8b[0] = buf[pos + 3];1496 return f32[0];1497 }1498 /* istanbul ignore next */1499 exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;1500 /* istanbul ignore next */1501 exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;1502 // float: ieee7541503 })(); else (function() {1504 function writeFloat_ieee754(writeUint, val, buf, pos) {1505 var sign = val < 0 ? 1 : 0;1506 if (sign)1507 val = -val;1508 if (val === 0)1509 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);1510 else if (isNaN(val))1511 writeUint(2143289344, buf, pos);1512 else if (val > 3.4028234663852886e+38) // +-Infinity1513 writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);1514 else if (val < 1.1754943508222875e-38) // denormal1515 writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);1516 else {1517 var exponent = Math.floor(Math.log(val) / Math.LN2),1518 mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;1519 writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);1520 }1521 }1522 exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);1523 exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);1524 function readFloat_ieee754(readUint, buf, pos) {1525 var uint = readUint(buf, pos),1526 sign = (uint >> 31) * 2 + 1,1527 exponent = uint >>> 23 & 255,1528 mantissa = uint & 8388607;1529 return exponent === 2551530 ? mantissa1531 ? NaN1532 : sign * Infinity1533 : exponent === 0 // denormal1534 ? sign * 1.401298464324817e-45 * mantissa1535 : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);1536 }1537 exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);1538 exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);1539 })();1540 // double: typed array1541 if (typeof Float64Array !== "undefined") (function() {1542 var f64 = new Float64Array([-0]),1543 f8b = new Uint8Array(f64.buffer),1544 le = f8b[7] === 128;1545 function writeDouble_f64_cpy(val, buf, pos) {1546 f64[0] = val;1547 buf[pos ] = f8b[0];1548 buf[pos + 1] = f8b[1];1549 buf[pos + 2] = f8b[2];1550 buf[pos + 3] = f8b[3];1551 buf[pos + 4] = f8b[4];1552 buf[pos + 5] = f8b[5];1553 buf[pos + 6] = f8b[6];1554 buf[pos + 7] = f8b[7];1555 }1556 function writeDouble_f64_rev(val, buf, pos) {1557 f64[0] = val;1558 buf[pos ] = f8b[7];1559 buf[pos + 1] = f8b[6];1560 buf[pos + 2] = f8b[5];1561 buf[pos + 3] = f8b[4];1562 buf[pos + 4] = f8b[3];1563 buf[pos + 5] = f8b[2];1564 buf[pos + 6] = f8b[1];1565 buf[pos + 7] = f8b[0];1566 }1567 /* istanbul ignore next */1568 exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;1569 /* istanbul ignore next */1570 exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;1571 function readDouble_f64_cpy(buf, pos) {1572 f8b[0] = buf[pos ];1573 f8b[1] = buf[pos + 1];1574 f8b[2] = buf[pos + 2];1575 f8b[3] = buf[pos + 3];1576 f8b[4] = buf[pos + 4];1577 f8b[5] = buf[pos + 5];1578 f8b[6] = buf[pos + 6];1579 f8b[7] = buf[pos + 7];1580 return f64[0];1581 }1582 function readDouble_f64_rev(buf, pos) {1583 f8b[7] = buf[pos ];1584 f8b[6] = buf[pos + 1];1585 f8b[5] = buf[pos + 2];1586 f8b[4] = buf[pos + 3];1587 f8b[3] = buf[pos + 4];1588 f8b[2] = buf[pos + 5];1589 f8b[1] = buf[pos + 6];1590 f8b[0] = buf[pos + 7];1591 return f64[0];1592 }1593 /* istanbul ignore next */1594 exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;1595 /* istanbul ignore next */1596 exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;1597 // double: ieee7541598 })(); else (function() {1599 function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {1600 var sign = val < 0 ? 1 : 0;1601 if (sign)1602 val = -val;1603 if (val === 0) {1604 writeUint(0, buf, pos + off0);1605 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);1606 } else if (isNaN(val)) {1607 writeUint(0, buf, pos + off0);1608 writeUint(2146959360, buf, pos + off1);1609 } else if (val > 1.7976931348623157e+308) { // +-Infinity1610 writeUint(0, buf, pos + off0);1611 writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);1612 } else {1613 var mantissa;1614 if (val < 2.2250738585072014e-308) { // denormal1615 mantissa = val / 5e-324;1616 writeUint(mantissa >>> 0, buf, pos + off0);1617 writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);1618 } else {1619 var exponent = Math.floor(Math.log(val) / Math.LN2);1620 if (exponent === 1024)1621 exponent = 1023;1622 mantissa = val * Math.pow(2, -exponent);1623 writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);1624 writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);1625 }1626 }1627 }1628 exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);1629 exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);1630 function readDouble_ieee754(readUint, off0, off1, buf, pos) {1631 var lo = readUint(buf, pos + off0),1632 hi = readUint(buf, pos + off1);1633 var sign = (hi >> 31) * 2 + 1,1634 exponent = hi >>> 20 & 2047,1635 mantissa = 4294967296 * (hi & 1048575) + lo;1636 return exponent === 20471637 ? mantissa1638 ? NaN1639 : sign * Infinity1640 : exponent === 0 // denormal1641 ? sign * 5e-324 * mantissa1642 : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);1643 }1644 exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);1645 exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);1646 })();1647 return exports;1648}1649// uint helpers1650function writeUintLE(val, buf, pos) {1651 buf[pos ] = val & 255;1652 buf[pos + 1] = val >>> 8 & 255;1653 buf[pos + 2] = val >>> 16 & 255;1654 buf[pos + 3] = val >>> 24;1655}1656function writeUintBE(val, buf, pos) {1657 buf[pos ] = val >>> 24;1658 buf[pos + 1] = val >>> 16 & 255;1659 buf[pos + 2] = val >>> 8 & 255;1660 buf[pos + 3] = val & 255;1661}1662function readUintLE(buf, pos) {1663 return (buf[pos ]1664 | buf[pos + 1] << 81665 | buf[pos + 2] << 161666 | buf[pos + 3] << 24) >>> 0;1667}1668function readUintBE(buf, pos) {1669 return (buf[pos ] << 241670 | buf[pos + 1] << 161671 | buf[pos + 2] << 81672 | buf[pos + 3]) >>> 0;1673}1674},{}],11:[function(require,module,exports){1675"use strict";1676module.exports = inquire;1677/**1678 * Requires a module only if available.1679 * @memberof util1680 * @param {string} moduleName Module to require1681 * @returns {?Object} Required module if available and not empty, otherwise `null`1682 */1683function inquire(moduleName) {1684 try {1685 var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval1686 if (mod && (mod.length || Object.keys(mod).length))1687 return mod;1688 } catch (e) {} // eslint-disable-line no-empty1689 return null;1690}1691},{}],12:[function(require,module,exports){1692"use strict";1693/**1694 * A minimal path module to resolve Unix, Windows and URL paths alike.1695 * @memberof util1696 * @namespace1697 */1698var path = exports;1699var isAbsolute =1700/**1701 * Tests if the specified path is absolute.1702 * @param {string} path Path to test1703 * @returns {boolean} `true` if path is absolute1704 */1705path.isAbsolute = function isAbsolute(path) {1706 return /^(?:\/|\w+:)/.test(path);1707};1708var normalize =1709/**1710 * Normalizes the specified path.1711 * @param {string} path Path to normalize1712 * @returns {string} Normalized path1713 */1714path.normalize = function normalize(path) {1715 path = path.replace(/\\/g, "/")1716 .replace(/\/{2,}/g, "/");1717 var parts = path.split("/"),1718 absolute = isAbsolute(path),1719 prefix = "";1720 if (absolute)1721 prefix = parts.shift() + "/";1722 for (var i = 0; i < parts.length;) {1723 if (parts[i] === "..") {1724 if (i > 0 && parts[i - 1] !== "..")1725 parts.splice(--i, 2);1726 else if (absolute)1727 parts.splice(i, 1);1728 else1729 ++i;1730 } else if (parts[i] === ".")1731 parts.splice(i, 1);1732 else1733 ++i;1734 }1735 return prefix + parts.join("/");1736};1737/**1738 * Resolves the specified include path against the specified origin path.1739 * @param {string} originPath Path to the origin file1740 * @param {string} includePath Include path relative to origin path1741 * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized1742 * @returns {string} Path to the include file1743 */1744path.resolve = function resolve(originPath, includePath, alreadyNormalized) {1745 if (!alreadyNormalized)1746 includePath = normalize(includePath);1747 if (isAbsolute(includePath))1748 return includePath;1749 if (!alreadyNormalized)1750 originPath = normalize(originPath);1751 return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;1752};1753},{}],13:[function(require,module,exports){1754"use strict";1755module.exports = pool;1756/**1757 * An allocator as used by {@link util.pool}.1758 * @typedef PoolAllocator1759 * @type {function}1760 * @param {number} size Buffer size1761 * @returns {Uint8Array} Buffer1762 */1763/**1764 * A slicer as used by {@link util.pool}.1765 * @typedef PoolSlicer1766 * @type {function}1767 * @param {number} start Start offset1768 * @param {number} end End offset1769 * @returns {Uint8Array} Buffer slice1770 * @this {Uint8Array}1771 */1772/**1773 * A general purpose buffer pool.1774 * @memberof util1775 * @function1776 * @param {PoolAllocator} alloc Allocator1777 * @param {PoolSlicer} slice Slicer1778 * @param {number} [size=8192] Slab size1779 * @returns {PoolAllocator} Pooled allocator1780 */1781function pool(alloc, slice, size) {1782 var SIZE = size || 8192;1783 var MAX = SIZE >>> 1;1784 var slab = null;1785 var offset = SIZE;1786 return function pool_alloc(size) {1787 if (size < 1 || size > MAX)1788 return alloc(size);1789 if (offset + size > SIZE) {1790 slab = alloc(SIZE);1791 offset = 0;1792 }1793 var buf = slice.call(slab, offset, offset += size);1794 if (offset & 7) // align to 32 bit1795 offset = (offset | 7) + 1;1796 return buf;1797 };1798}1799},{}],14:[function(require,module,exports){1800"use strict";1801/**1802 * A minimal UTF8 implementation for number arrays.1803 * @memberof util1804 * @namespace1805 */1806var utf8 = exports;1807/**1808 * Calculates the UTF8 byte length of a string.1809 * @param {string} string String1810 * @returns {number} Byte length1811 */1812utf8.length = function utf8_length(string) {1813 var len = 0,1814 c = 0;1815 for (var i = 0; i < string.length; ++i) {1816 c = string.charCodeAt(i);1817 if (c < 128)1818 len += 1;1819 else if (c < 2048)1820 len += 2;1821 else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {1822 ++i;1823 len += 4;1824 } else1825 len += 3;1826 }1827 return len;1828};1829/**1830 * Reads UTF8 bytes as a string.1831 * @param {Uint8Array} buffer Source buffer1832 * @param {number} start Source start1833 * @param {number} end Source end1834 * @returns {string} String read1835 */1836utf8.read = function utf8_read(buffer, start, end) {1837 var len = end - start;1838 if (len < 1)1839 return "";1840 var parts = null,1841 chunk = [],1842 i = 0, // char offset1843 t; // temporary1844 while (start < end) {1845 t = buffer[start++];1846 if (t < 128)1847 chunk[i++] = t;1848 else if (t > 191 && t < 224)1849 chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;1850 else if (t > 239 && t < 365) {1851 t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;1852 chunk[i++] = 0xD800 + (t >> 10);1853 chunk[i++] = 0xDC00 + (t & 1023);1854 } else1855 chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;1856 if (i > 8191) {1857 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));1858 i = 0;1859 }1860 }1861 if (parts) {1862 if (i)1863 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));1864 return parts.join("");1865 }1866 return String.fromCharCode.apply(String, chunk.slice(0, i));1867};1868/**1869 * Writes a string as UTF8 bytes.1870 * @param {string} string Source string1871 * @param {Uint8Array} buffer Destination buffer1872 * @param {number} offset Destination offset1873 * @returns {number} Bytes written1874 */1875utf8.write = function utf8_write(string, buffer, offset) {1876 var start = offset,1877 c1, // character 11878 c2; // character 21879 for (var i = 0; i < string.length; ++i) {1880 c1 = string.charCodeAt(i);1881 if (c1 < 128) {1882 buffer[offset++] = c1;1883 } else if (c1 < 2048) {1884 buffer[offset++] = c1 >> 6 | 192;1885 buffer[offset++] = c1 & 63 | 128;1886 } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {1887 c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);1888 ++i;1889 buffer[offset++] = c1 >> 18 | 240;1890 buffer[offset++] = c1 >> 12 & 63 | 128;1891 buffer[offset++] = c1 >> 6 & 63 | 128;1892 buffer[offset++] = c1 & 63 | 128;1893 } else {1894 buffer[offset++] = c1 >> 12 | 224;1895 buffer[offset++] = c1 >> 6 & 63 | 128;1896 buffer[offset++] = c1 & 63 | 128;1897 }1898 }1899 return offset - start;1900};1901},{}],15:[function(require,module,exports){1902"use strict";1903// ref: https://github.com/tc39/proposal-global1904var getGlobal = function () {1905 // the only reliable means to get the global object is1906 // `Function('return this')()`1907 // However, this causes CSP violations in Chrome apps.1908 if (typeof self !== 'undefined') { return self; }1909 if (typeof window !== 'undefined') { return window; }1910 if (typeof global !== 'undefined') { return global; }1911 throw new Error('unable to locate global object');1912}1913var global = getGlobal();1914module.exports = exports = global.fetch;1915// Needed for TypeScript and Webpack.1916exports.default = global.fetch.bind(global);1917exports.Headers = global.Headers;1918exports.Request = global.Request;1919exports.Response = global.Response;1920},{}],16:[function(require,module,exports){1921// full library entry point.1922"use strict";1923module.exports = require("./src/index");1924},{"./src/index":25}],17:[function(require,module,exports){1925"use strict";1926module.exports = common;1927var commonRe = /\/|\./;1928/**1929 * Provides common type definitions.1930 * Can also be used to provide additional google types or your own custom types.1931 * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name1932 * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition1933 * @returns {undefined}1934 * @property {INamespace} google/protobuf/any.proto Any1935 * @property {INamespace} google/protobuf/duration.proto Duration1936 * @property {INamespace} google/protobuf/empty.proto Empty1937 * @property {INamespace} google/protobuf/field_mask.proto FieldMask1938 * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue1939 * @property {INamespace} google/protobuf/timestamp.proto Timestamp1940 * @property {INamespace} google/protobuf/wrappers.proto Wrappers1941 * @example1942 * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)1943 * protobuf.common("descriptor", descriptorJson);1944 *1945 * // manually provides a custom definition (uses my.foo namespace)1946 * protobuf.common("my/foo/bar.proto", myFooBarJson);1947 */1948function common(name, json) {1949 if (!commonRe.test(name)) {1950 name = "google/protobuf/" + name + ".proto";1951 json = { nested: { google: { nested: { protobuf: { nested: json } } } } };1952 }1953 common[name] = json;1954}1955// Not provided because of limited use (feel free to discuss or to provide yourself):1956//1957// google/protobuf/descriptor.proto1958// google/protobuf/source_context.proto1959// google/protobuf/type.proto1960//1961// Stripped and pre-parsed versions of these non-bundled files are instead available as part of1962// the repository or package within the google/protobuf directory.1963common("any", {1964 /**1965 * Properties of a google.protobuf.Any message.1966 * @interface IAny1967 * @type {Object}1968 * @property {string} [typeUrl]1969 * @property {Uint8Array} [bytes]1970 * @memberof common1971 */1972 Any: {1973 fields: {1974 type_url: {1975 type: "string",1976 id: 11977 },1978 value: {1979 type: "bytes",1980 id: 21981 }1982 }1983 }1984});1985var timeType;1986common("duration", {1987 /**1988 * Properties of a google.protobuf.Duration message.1989 * @interface IDuration1990 * @type {Object}1991 * @property {number|Long} [seconds]1992 * @property {number} [nanos]1993 * @memberof common1994 */1995 Duration: timeType = {1996 fields: {1997 seconds: {1998 type: "int64",1999 id: 12000 },2001 nanos: {2002 type: "int32",2003 id: 22004 }2005 }2006 }2007});2008common("timestamp", {2009 /**2010 * Properties of a google.protobuf.Timestamp message.2011 * @interface ITimestamp2012 * @type {Object}2013 * @property {number|Long} [seconds]2014 * @property {number} [nanos]2015 * @memberof common2016 */2017 Timestamp: timeType2018});2019common("empty", {2020 /**2021 * Properties of a google.protobuf.Empty message.2022 * @interface IEmpty2023 * @memberof common2024 */2025 Empty: {2026 fields: {}2027 }2028});2029common("struct", {2030 /**2031 * Properties of a google.protobuf.Struct message.2032 * @interface IStruct2033 * @type {Object}2034 * @property {Object.<string,IValue>} [fields]2035 * @memberof common2036 */2037 Struct: {2038 fields: {2039 fields: {2040 keyType: "string",2041 type: "Value",2042 id: 12043 }2044 }2045 },2046 /**2047 * Properties of a google.protobuf.Value message.2048 * @interface IValue2049 * @type {Object}2050 * @property {string} [kind]2051 * @property {0} [nullValue]2052 * @property {number} [numberValue]2053 * @property {string} [stringValue]2054 * @property {boolean} [boolValue]2055 * @property {IStruct} [structValue]2056 * @property {IListValue} [listValue]2057 * @memberof common2058 */2059 Value: {2060 oneofs: {2061 kind: {2062 oneof: [2063 "nullValue",2064 "numberValue",2065 "stringValue",2066 "boolValue",2067 "structValue",2068 "listValue"2069 ]2070 }2071 },2072 fields: {2073 nullValue: {2074 type: "NullValue",2075 id: 12076 },2077 numberValue: {2078 type: "double",2079 id: 22080 },2081 stringValue: {2082 type: "string",2083 id: 32084 },2085 boolValue: {2086 type: "bool",2087 id: 42088 },2089 structValue: {2090 type: "Struct",2091 id: 52092 },2093 listValue: {2094 type: "ListValue",2095 id: 62096 }2097 }2098 },2099 NullValue: {2100 values: {2101 NULL_VALUE: 02102 }2103 },2104 /**2105 * Properties of a google.protobuf.ListValue message.2106 * @interface IListValue2107 * @type {Object}2108 * @property {Array.<IValue>} [values]2109 * @memberof common2110 */2111 ListValue: {2112 fields: {2113 values: {2114 rule: "repeated",2115 type: "Value",2116 id: 12117 }2118 }2119 }2120});2121common("wrappers", {2122 /**2123 * Properties of a google.protobuf.DoubleValue message.2124 * @interface IDoubleValue2125 * @type {Object}2126 * @property {number} [value]2127 * @memberof common2128 */2129 DoubleValue: {2130 fields: {2131 value: {2132 type: "double",2133 id: 12134 }2135 }2136 },2137 /**2138 * Properties of a google.protobuf.FloatValue message.2139 * @interface IFloatValue2140 * @type {Object}2141 * @property {number} [value]2142 * @memberof common2143 */2144 FloatValue: {2145 fields: {2146 value: {2147 type: "float",2148 id: 12149 }2150 }2151 },2152 /**2153 * Properties of a google.protobuf.Int64Value message.2154 * @interface IInt64Value2155 * @type {Object}2156 * @property {number|Long} [value]2157 * @memberof common2158 */2159 Int64Value: {2160 fields: {2161 value: {2162 type: "int64",2163 id: 12164 }2165 }2166 },2167 /**2168 * Properties of a google.protobuf.UInt64Value message.2169 * @interface IUInt64Value2170 * @type {Object}2171 * @property {number|Long} [value]2172 * @memberof common2173 */2174 UInt64Value: {2175 fields: {2176 value: {2177 type: "uint64",2178 id: 12179 }2180 }2181 },2182 /**2183 * Properties of a google.protobuf.Int32Value message.2184 * @interface IInt32Value2185 * @type {Object}2186 * @property {number} [value]2187 * @memberof common2188 */2189 Int32Value: {2190 fields: {2191 value: {2192 type: "int32",2193 id: 12194 }2195 }2196 },2197 /**2198 * Properties of a google.protobuf.UInt32Value message.2199 * @interface IUInt32Value2200 * @type {Object}2201 * @property {number} [value]2202 * @memberof common2203 */2204 UInt32Value: {2205 fields: {2206 value: {2207 type: "uint32",2208 id: 12209 }2210 }2211 },2212 /**2213 * Properties of a google.protobuf.BoolValue message.2214 * @interface IBoolValue2215 * @type {Object}2216 * @property {boolean} [value]2217 * @memberof common2218 */2219 BoolValue: {2220 fields: {2221 value: {2222 type: "bool",2223 id: 12224 }2225 }2226 },2227 /**2228 * Properties of a google.protobuf.StringValue message.2229 * @interface IStringValue2230 * @type {Object}2231 * @property {string} [value]2232 * @memberof common2233 */2234 StringValue: {2235 fields: {2236 value: {2237 type: "string",2238 id: 12239 }2240 }2241 },2242 /**2243 * Properties of a google.protobuf.BytesValue message.2244 * @interface IBytesValue2245 * @type {Object}2246 * @property {Uint8Array} [value]2247 * @memberof common2248 */2249 BytesValue: {2250 fields: {2251 value: {2252 type: "bytes",2253 id: 12254 }2255 }2256 }2257});2258common("field_mask", {2259 /**2260 * Properties of a google.protobuf.FieldMask message.2261 * @interface IDoubleValue2262 * @type {Object}2263 * @property {number} [value]2264 * @memberof common2265 */2266 FieldMask: {2267 fields: {2268 paths: {2269 rule: "repeated",2270 type: "string",2271 id: 12272 }2273 }2274 }2275});2276/**2277 * Gets the root definition of the specified common proto file.2278 *2279 * Bundled definitions are:2280 * - google/protobuf/any.proto2281 * - google/protobuf/duration.proto2282 * - google/protobuf/empty.proto2283 * - google/protobuf/field_mask.proto2284 * - google/protobuf/struct.proto2285 * - google/protobuf/timestamp.proto2286 * - google/protobuf/wrappers.proto2287 *2288 * @param {string} file Proto file name2289 * @returns {INamespace|null} Root definition or `null` if not defined2290 */2291common.get = function get(file) {2292 return common[file] || null;2293};2294},{}],18:[function(require,module,exports){2295"use strict";2296/**2297 * Runtime message from/to plain object converters.2298 * @namespace2299 */2300var converter = exports;2301var Enum = require("./enum"),2302 util = require("./util");2303/**2304 * Generates a partial value fromObject conveter.2305 * @param {Codegen} gen Codegen instance2306 * @param {Field} field Reflected field2307 * @param {number} fieldIndex Field index2308 * @param {string} prop Property reference2309 * @returns {Codegen} Codegen instance2310 * @ignore2311 */2312function genValuePartial_fromObject(gen, field, fieldIndex, prop) {2313 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */2314 if (field.resolvedType) {2315 if (field.resolvedType instanceof Enum) { gen2316 ("switch(d%s){", prop);2317 for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {2318 if (field.repeated && values[keys[i]] === field.typeDefault) gen2319 ("default:");2320 gen2321 ("case%j:", keys[i])2322 ("case %i:", values[keys[i]])2323 ("m%s=%j", prop, values[keys[i]])2324 ("break");2325 } gen2326 ("}");2327 } else gen2328 ("if(typeof d%s!==\"object\")", prop)2329 ("throw TypeError(%j)", field.fullName + ": object expected")2330 ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);2331 } else {2332 var isUnsigned = false;2333 switch (field.type) {2334 case "double":2335 case "float": gen2336 ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"2337 break;2338 case "uint32":2339 case "fixed32": gen2340 ("m%s=d%s>>>0", prop, prop);2341 break;2342 case "int32":2343 case "sint32":2344 case "sfixed32": gen2345 ("m%s=d%s|0", prop, prop);2346 break;2347 case "uint64":2348 isUnsigned = true;2349 // eslint-disable-line no-fallthrough2350 case "int64":2351 case "sint64":2352 case "fixed64":2353 case "sfixed64": gen2354 ("if(util.Long)")2355 ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)2356 ("else if(typeof d%s===\"string\")", prop)2357 ("m%s=parseInt(d%s,10)", prop, prop)2358 ("else if(typeof d%s===\"number\")", prop)2359 ("m%s=d%s", prop, prop)2360 ("else if(typeof d%s===\"object\")", prop)2361 ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");2362 break;2363 case "bytes": gen2364 ("if(typeof d%s===\"string\")", prop)2365 ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)2366 ("else if(d%s.length)", prop)2367 ("m%s=d%s", prop, prop);2368 break;2369 case "string": gen2370 ("m%s=String(d%s)", prop, prop);2371 break;2372 case "bool": gen2373 ("m%s=Boolean(d%s)", prop, prop);2374 break;2375 /* default: gen2376 ("m%s=d%s", prop, prop);2377 break; */2378 }2379 }2380 return gen;2381 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */2382}2383/**2384 * Generates a plain object to runtime message converter specific to the specified message type.2385 * @param {Type} mtype Message type2386 * @returns {Codegen} Codegen instance2387 */2388converter.fromObject = function fromObject(mtype) {2389 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */2390 var fields = mtype.fieldsArray;2391 var gen = util.codegen(["d"], mtype.name + "$fromObject")2392 ("if(d instanceof this.ctor)")2393 ("return d");2394 if (!fields.length) return gen2395 ("return new this.ctor");2396 gen2397 ("var m=new this.ctor");2398 for (var i = 0; i < fields.length; ++i) {2399 var field = fields[i].resolve(),2400 prop = util.safeProp(field.name);2401 // Map fields2402 if (field.map) { gen2403 ("if(d%s){", prop)2404 ("if(typeof d%s!==\"object\")", prop)2405 ("throw TypeError(%j)", field.fullName + ": object expected")2406 ("m%s={}", prop)2407 ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);2408 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")2409 ("}")2410 ("}");2411 // Repeated fields2412 } else if (field.repeated) { gen2413 ("if(d%s){", prop)2414 ("if(!Array.isArray(d%s))", prop)2415 ("throw TypeError(%j)", field.fullName + ": array expected")2416 ("m%s=[]", prop)2417 ("for(var i=0;i<d%s.length;++i){", prop);2418 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")2419 ("}")2420 ("}");2421 // Non-repeated fields2422 } else {2423 if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)2424 ("if(d%s!=null){", prop); // !== undefined && !== null2425 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);2426 if (!(field.resolvedType instanceof Enum)) gen2427 ("}");2428 }2429 } return gen2430 ("return m");2431 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */2432};2433/**2434 * Generates a partial value toObject converter.2435 * @param {Codegen} gen Codegen instance2436 * @param {Field} field Reflected field2437 * @param {number} fieldIndex Field index2438 * @param {string} prop Property reference2439 * @returns {Codegen} Codegen instance2440 * @ignore2441 */2442function genValuePartial_toObject(gen, field, fieldIndex, prop) {2443 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */2444 if (field.resolvedType) {2445 if (field.resolvedType instanceof Enum) gen2446 ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);2447 else gen2448 ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);2449 } else {2450 var isUnsigned = false;2451 switch (field.type) {2452 case "double":2453 case "float": gen2454 ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);2455 break;2456 case "uint64":2457 isUnsigned = true;2458 // eslint-disable-line no-fallthrough2459 case "int64":2460 case "sint64":2461 case "fixed64":2462 case "sfixed64": gen2463 ("if(typeof m%s===\"number\")", prop)2464 ("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)2465 ("else") // Long-like2466 ("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop);2467 break;2468 case "bytes": gen2469 ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);2470 break;2471 default: gen2472 ("d%s=m%s", prop, prop);2473 break;2474 }2475 }2476 return gen;2477 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */2478}2479/**2480 * Generates a runtime message to plain object converter specific to the specified message type.2481 * @param {Type} mtype Message type2482 * @returns {Codegen} Codegen instance2483 */2484converter.toObject = function toObject(mtype) {2485 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */2486 var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);2487 if (!fields.length)2488 return util.codegen()("return {}");2489 var gen = util.codegen(["m", "o"], mtype.name + "$toObject")2490 ("if(!o)")2491 ("o={}")2492 ("var d={}");2493 var repeatedFields = [],2494 mapFields = [],2495 normalFields = [],2496 i = 0;2497 for (; i < fields.length; ++i)2498 if (!fields[i].partOf)2499 ( fields[i].resolve().repeated ? repeatedFields2500 : fields[i].map ? mapFields2501 : normalFields).push(fields[i]);2502 if (repeatedFields.length) { gen2503 ("if(o.arrays||o.defaults){");2504 for (i = 0; i < repeatedFields.length; ++i) gen2505 ("d%s=[]", util.safeProp(repeatedFields[i].name));2506 gen2507 ("}");2508 }2509 if (mapFields.length) { gen2510 ("if(o.objects||o.defaults){");2511 for (i = 0; i < mapFields.length; ++i) gen2512 ("d%s={}", util.safeProp(mapFields[i].name));2513 gen2514 ("}");2515 }2516 if (normalFields.length) { gen2517 ("if(o.defaults){");2518 for (i = 0; i < normalFields.length; ++i) {2519 var field = normalFields[i],2520 prop = util.safeProp(field.name);2521 if (field.resolvedType instanceof Enum) gen2522 ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);2523 else if (field.long) gen2524 ("if(util.Long){")2525 ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)2526 ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)2527 ("}else")2528 ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());2529 else if (field.bytes) {2530 var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]";2531 gen2532 ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault))2533 ("else{")2534 ("d%s=%s", prop, arrayDefault)2535 ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop)2536 ("}");2537 } else gen2538 ("d%s=%j", prop, field.typeDefault); // also messages (=null)2539 } gen2540 ("}");2541 }2542 var hasKs2 = false;2543 for (i = 0; i < fields.length; ++i) {2544 var field = fields[i],2545 index = mtype._fieldsArray.indexOf(field),2546 prop = util.safeProp(field.name);2547 if (field.map) {2548 if (!hasKs2) { hasKs2 = true; gen2549 ("var ks2");2550 } gen2551 ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)2552 ("d%s={}", prop)2553 ("for(var j=0;j<ks2.length;++j){");2554 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]")2555 ("}");2556 } else if (field.repeated) { gen2557 ("if(m%s&&m%s.length){", prop, prop)2558 ("d%s=[]", prop)2559 ("for(var j=0;j<m%s.length;++j){", prop);2560 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")2561 ("}");2562 } else { gen2563 ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name); // !== undefined && !== null2564 genValuePartial_toObject(gen, field, /* sorted */ index, prop);2565 if (field.partOf) gen2566 ("if(o.oneofs)")2567 ("d%s=%j", util.safeProp(field.partOf.name), field.name);2568 }2569 gen2570 ("}");2571 }2572 return gen2573 ("return d");2574 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */2575};2576},{"./enum":21,"./util":43}],19:[function(require,module,exports){2577"use strict";2578module.exports = decoder;2579var Enum = require("./enum"),2580 types = require("./types"),2581 util = require("./util");2582function missing(field) {2583 return "missing required '" + field.name + "'";2584}2585/**2586 * Generates a decoder specific to the specified message type.2587 * @param {Type} mtype Message type2588 * @returns {Codegen} Codegen instance2589 */2590function decoder(mtype) {2591 /* eslint-disable no-unexpected-multiline */2592 var gen = util.codegen(["r", "l"], mtype.name + "$decode")2593 ("if(!(r instanceof Reader))")2594 ("r=Reader.create(r)")2595 ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k" : ""))2596 ("while(r.pos<c){")2597 ("var t=r.uint32()");2598 if (mtype.group) gen2599 ("if((t&7)===4)")2600 ("break");2601 gen2602 ("switch(t>>>3){");2603 var i = 0;2604 for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {2605 var field = mtype._fieldsArray[i].resolve(),2606 type = field.resolvedType instanceof Enum ? "int32" : field.type,2607 ref = "m" + util.safeProp(field.name); gen2608 ("case %i:", field.id);2609 // Map fields2610 if (field.map) { gen2611 ("r.skip().pos++") // assumes id 1 + key wireType2612 ("if(%s===util.emptyObject)", ref)2613 ("%s={}", ref)2614 ("k=r.%s()", field.keyType)2615 ("r.pos++"); // assumes id 2 + value wireType2616 if (types.long[field.keyType] !== undefined) {2617 if (types.basic[type] === undefined) gen2618 ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups2619 else gen2620 ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type);2621 } else {2622 if (types.basic[type] === undefined) gen2623 ("%s[k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups2624 else gen2625 ("%s[k]=r.%s()", ref, type);2626 }2627 // Repeated fields2628 } else if (field.repeated) { gen2629 ("if(!(%s&&%s.length))", ref, ref)2630 ("%s=[]", ref);2631 // Packable (always check for forward and backward compatiblity)2632 if (types.packed[type] !== undefined) gen2633 ("if((t&7)===2){")2634 ("var c2=r.uint32()+r.pos")2635 ("while(r.pos<c2)")2636 ("%s.push(r.%s())", ref, type)2637 ("}else");2638 // Non-packed2639 if (types.basic[type] === undefined) gen(field.resolvedType.group2640 ? "%s.push(types[%i].decode(r))"2641 : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);2642 else gen2643 ("%s.push(r.%s())", ref, type);2644 // Non-repeated2645 } else if (types.basic[type] === undefined) gen(field.resolvedType.group2646 ? "%s=types[%i].decode(r)"2647 : "%s=types[%i].decode(r,r.uint32())", ref, i);2648 else gen2649 ("%s=r.%s()", ref, type);2650 gen2651 ("break");2652 // Unknown fields2653 } gen2654 ("default:")2655 ("r.skipType(t&7)")2656 ("break")2657 ("}")2658 ("}");2659 // Field presence2660 for (i = 0; i < mtype._fieldsArray.length; ++i) {2661 var rfield = mtype._fieldsArray[i];2662 if (rfield.required) gen2663 ("if(!m.hasOwnProperty(%j))", rfield.name)2664 ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));2665 }2666 return gen2667 ("return m");2668 /* eslint-enable no-unexpected-multiline */2669}2670},{"./enum":21,"./types":42,"./util":43}],20:[function(require,module,exports){2671"use strict";2672module.exports = encoder;2673var Enum = require("./enum"),2674 types = require("./types"),2675 util = require("./util");2676/**2677 * Generates a partial message type encoder.2678 * @param {Codegen} gen Codegen instance2679 * @param {Field} field Reflected field2680 * @param {number} fieldIndex Field index2681 * @param {string} ref Variable reference2682 * @returns {Codegen} Codegen instance2683 * @ignore2684 */2685function genTypePartial(gen, field, fieldIndex, ref) {2686 return field.resolvedType.group2687 ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)2688 : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);2689}2690/**2691 * Generates an encoder specific to the specified message type.2692 * @param {Type} mtype Message type2693 * @returns {Codegen} Codegen instance2694 */2695function encoder(mtype) {2696 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */2697 var gen = util.codegen(["m", "w"], mtype.name + "$encode")2698 ("if(!w)")2699 ("w=Writer.create()");2700 var i, ref;2701 // "when a message is serialized its known fields should be written sequentially by field number"2702 var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);2703 for (var i = 0; i < fields.length; ++i) {2704 var field = fields[i].resolve(),2705 index = mtype._fieldsArray.indexOf(field),2706 type = field.resolvedType instanceof Enum ? "int32" : field.type,2707 wireType = types.basic[type];2708 ref = "m" + util.safeProp(field.name);2709 // Map fields2710 if (field.map) {2711 gen2712 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name) // !== undefined && !== null2713 ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)2714 ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);2715 if (wireType === undefined) gen2716 ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups2717 else gen2718 (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);2719 gen2720 ("}")2721 ("}");2722 // Repeated fields2723 } else if (field.repeated) { gen2724 ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null2725 // Packed repeated2726 if (field.packed && types.packed[type] !== undefined) { gen2727 ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)2728 ("for(var i=0;i<%s.length;++i)", ref)2729 ("w.%s(%s[i])", type, ref)2730 ("w.ldelim()");2731 // Non-packed2732 } else { gen2733 ("for(var i=0;i<%s.length;++i)", ref);2734 if (wireType === undefined)2735 genTypePartial(gen, field, index, ref + "[i]");2736 else gen2737 ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);2738 } gen2739 ("}");2740 // Non-repeated2741 } else {2742 if (field.optional) gen2743 ("if(%s!=null&&m.hasOwnProperty(%j))", ref, field.name); // !== undefined && !== null2744 if (wireType === undefined)2745 genTypePartial(gen, field, index, ref);2746 else gen2747 ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);2748 }2749 }2750 return gen2751 ("return w");2752 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */2753}2754},{"./enum":21,"./types":42,"./util":43}],21:[function(require,module,exports){2755"use strict";2756module.exports = Enum;2757// extends ReflectionObject2758var ReflectionObject = require("./object");2759((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";2760var Namespace = require("./namespace"),2761 util = require("./util");2762/**2763 * Constructs a new enum instance.2764 * @classdesc Reflected enum.2765 * @extends ReflectionObject2766 * @constructor2767 * @param {string} name Unique name within its namespace2768 * @param {Object.<string,number>} [values] Enum values as an object, by name2769 * @param {Object.<string,*>} [options] Declared options2770 * @param {string} [comment] The comment for this enum2771 * @param {Object.<string,string>} [comments] The value comments for this enum2772 */2773function Enum(name, values, options, comment, comments) {2774 ReflectionObject.call(this, name, options);2775 if (values && typeof values !== "object")2776 throw TypeError("values must be an object");2777 /**2778 * Enum values by id.2779 * @type {Object.<number,string>}2780 */2781 this.valuesById = {};2782 /**2783 * Enum values by name.2784 * @type {Object.<string,number>}2785 */2786 this.values = Object.create(this.valuesById); // toJSON, marker2787 /**2788 * Enum comment text.2789 * @type {string|null}2790 */2791 this.comment = comment;2792 /**2793 * Value comment texts, if any.2794 * @type {Object.<string,string>}2795 */2796 this.comments = comments || {};2797 /**2798 * Reserved ranges, if any.2799 * @type {Array.<number[]|string>}2800 */2801 this.reserved = undefined; // toJSON2802 // Note that values inherit valuesById on their prototype which makes them a TypeScript-2803 // compatible enum. This is used by pbts to write actual enum definitions that work for2804 // static and reflection code alike instead of emitting generic object definitions.2805 if (values)2806 for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)2807 if (typeof values[keys[i]] === "number") // use forward entries only2808 this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];2809}2810/**2811 * Enum descriptor.2812 * @interface IEnum2813 * @property {Object.<string,number>} values Enum values2814 * @property {Object.<string,*>} [options] Enum options2815 */2816/**2817 * Constructs an enum from an enum descriptor.2818 * @param {string} name Enum name2819 * @param {IEnum} json Enum descriptor2820 * @returns {Enum} Created enum2821 * @throws {TypeError} If arguments are invalid2822 */2823Enum.fromJSON = function fromJSON(name, json) {2824 var enm = new Enum(name, json.values, json.options, json.comment, json.comments);2825 enm.reserved = json.reserved;2826 return enm;2827};2828/**2829 * Converts this enum to an enum descriptor.2830 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options2831 * @returns {IEnum} Enum descriptor2832 */2833Enum.prototype.toJSON = function toJSON(toJSONOptions) {2834 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;2835 return util.toObject([2836 "options" , this.options,2837 "values" , this.values,2838 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,2839 "comment" , keepComments ? this.comment : undefined,2840 "comments" , keepComments ? this.comments : undefined2841 ]);2842};2843/**2844 * Adds a value to this enum.2845 * @param {string} name Value name2846 * @param {number} id Value id2847 * @param {string} [comment] Comment, if any2848 * @returns {Enum} `this`2849 * @throws {TypeError} If arguments are invalid2850 * @throws {Error} If there is already a value with this name or id2851 */2852Enum.prototype.add = function add(name, id, comment) {2853 // utilized by the parser but not by .fromJSON2854 if (!util.isString(name))2855 throw TypeError("name must be a string");2856 if (!util.isInteger(id))2857 throw TypeError("id must be an integer");2858 if (this.values[name] !== undefined)2859 throw Error("duplicate name '" + name + "' in " + this);2860 if (this.isReservedId(id))2861 throw Error("id " + id + " is reserved in " + this);2862 if (this.isReservedName(name))2863 throw Error("name '" + name + "' is reserved in " + this);2864 if (this.valuesById[id] !== undefined) {2865 if (!(this.options && this.options.allow_alias))2866 throw Error("duplicate id " + id + " in " + this);2867 this.values[name] = id;2868 } else2869 this.valuesById[this.values[name] = id] = name;2870 this.comments[name] = comment || null;2871 return this;2872};2873/**2874 * Removes a value from this enum2875 * @param {string} name Value name2876 * @returns {Enum} `this`2877 * @throws {TypeError} If arguments are invalid2878 * @throws {Error} If `name` is not a name of this enum2879 */2880Enum.prototype.remove = function remove(name) {2881 if (!util.isString(name))2882 throw TypeError("name must be a string");2883 var val = this.values[name];2884 if (val == null)2885 throw Error("name '" + name + "' does not exist in " + this);2886 delete this.valuesById[val];2887 delete this.values[name];2888 delete this.comments[name];2889 return this;2890};2891/**2892 * Tests if the specified id is reserved.2893 * @param {number} id Id to test2894 * @returns {boolean} `true` if reserved, otherwise `false`2895 */2896Enum.prototype.isReservedId = function isReservedId(id) {2897 return Namespace.isReservedId(this.reserved, id);2898};2899/**2900 * Tests if the specified name is reserved.2901 * @param {string} name Name to test2902 * @returns {boolean} `true` if reserved, otherwise `false`2903 */2904Enum.prototype.isReservedName = function isReservedName(name) {2905 return Namespace.isReservedName(this.reserved, name);2906};2907},{"./namespace":29,"./object":30,"./util":43}],22:[function(require,module,exports){2908"use strict";2909module.exports = Field;2910// extends ReflectionObject2911var ReflectionObject = require("./object");2912((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";2913var Enum = require("./enum"),2914 types = require("./types"),2915 util = require("./util");2916var Type; // cyclic2917var ruleRe = /^required|optional|repeated$/;2918/**2919 * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.2920 * @name Field2921 * @classdesc Reflected message field.2922 * @extends FieldBase2923 * @constructor2924 * @param {string} name Unique name within its namespace2925 * @param {number} id Unique id within its namespace2926 * @param {string} type Value type2927 * @param {string|Object.<string,*>} [rule="optional"] Field rule2928 * @param {string|Object.<string,*>} [extend] Extended type if different from parent2929 * @param {Object.<string,*>} [options] Declared options2930 */2931/**2932 * Constructs a field from a field descriptor.2933 * @param {string} name Field name2934 * @param {IField} json Field descriptor2935 * @returns {Field} Created field2936 * @throws {TypeError} If arguments are invalid2937 */2938Field.fromJSON = function fromJSON(name, json) {2939 return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);2940};2941/**2942 * Not an actual constructor. Use {@link Field} instead.2943 * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.2944 * @exports FieldBase2945 * @extends ReflectionObject2946 * @constructor2947 * @param {string} name Unique name within its namespace2948 * @param {number} id Unique id within its namespace2949 * @param {string} type Value type2950 * @param {string|Object.<string,*>} [rule="optional"] Field rule2951 * @param {string|Object.<string,*>} [extend] Extended type if different from parent2952 * @param {Object.<string,*>} [options] Declared options2953 * @param {string} [comment] Comment associated with this field2954 */2955function Field(name, id, type, rule, extend, options, comment) {2956 if (util.isObject(rule)) {2957 comment = extend;2958 options = rule;2959 rule = extend = undefined;2960 } else if (util.isObject(extend)) {2961 comment = options;2962 options = extend;2963 extend = undefined;2964 }2965 ReflectionObject.call(this, name, options);2966 if (!util.isInteger(id) || id < 0)2967 throw TypeError("id must be a non-negative integer");2968 if (!util.isString(type))2969 throw TypeError("type must be a string");2970 if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))2971 throw TypeError("rule must be a string rule");2972 if (extend !== undefined && !util.isString(extend))2973 throw TypeError("extend must be a string");2974 /**2975 * Field rule, if any.2976 * @type {string|undefined}2977 */2978 this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON2979 /**2980 * Field type.2981 * @type {string}2982 */2983 this.type = type; // toJSON2984 /**2985 * Unique field id.2986 * @type {number}2987 */2988 this.id = id; // toJSON, marker2989 /**2990 * Extended type if different from parent.2991 * @type {string|undefined}2992 */2993 this.extend = extend || undefined; // toJSON2994 /**2995 * Whether this field is required.2996 * @type {boolean}2997 */2998 this.required = rule === "required";2999 /**3000 * Whether this field is optional.3001 * @type {boolean}3002 */3003 this.optional = !this.required;3004 /**3005 * Whether this field is repeated.3006 * @type {boolean}3007 */3008 this.repeated = rule === "repeated";3009 /**3010 * Whether this field is a map or not.3011 * @type {boolean}3012 */3013 this.map = false;3014 /**3015 * Message this field belongs to.3016 * @type {Type|null}3017 */3018 this.message = null;3019 /**3020 * OneOf this field belongs to, if any,3021 * @type {OneOf|null}3022 */3023 this.partOf = null;3024 /**3025 * The field type's default value.3026 * @type {*}3027 */3028 this.typeDefault = null;3029 /**3030 * The field's default value on prototypes.3031 * @type {*}3032 */3033 this.defaultValue = null;3034 /**3035 * Whether this field's value should be treated as a long.3036 * @type {boolean}3037 */3038 this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;3039 /**3040 * Whether this field's value is a buffer.3041 * @type {boolean}3042 */3043 this.bytes = type === "bytes";3044 /**3045 * Resolved type if not a basic type.3046 * @type {Type|Enum|null}3047 */3048 this.resolvedType = null;3049 /**3050 * Sister-field within the extended type if a declaring extension field.3051 * @type {Field|null}3052 */3053 this.extensionField = null;3054 /**3055 * Sister-field within the declaring namespace if an extended field.3056 * @type {Field|null}3057 */3058 this.declaringField = null;3059 /**3060 * Internally remembers whether this field is packed.3061 * @type {boolean|null}3062 * @private3063 */3064 this._packed = null;3065 /**3066 * Comment for this field.3067 * @type {string|null}3068 */3069 this.comment = comment;3070}3071/**3072 * Determines whether this field is packed. Only relevant when repeated and working with proto2.3073 * @name Field#packed3074 * @type {boolean}3075 * @readonly3076 */3077Object.defineProperty(Field.prototype, "packed", {3078 get: function() {3079 // defaults to packed=true if not explicity set to false3080 if (this._packed === null)3081 this._packed = this.getOption("packed") !== false;3082 return this._packed;3083 }3084});3085/**3086 * @override3087 */3088Field.prototype.setOption = function setOption(name, value, ifNotSet) {3089 if (name === "packed") // clear cached before setting3090 this._packed = null;3091 return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);3092};3093/**3094 * Field descriptor.3095 * @interface IField3096 * @property {string} [rule="optional"] Field rule3097 * @property {string} type Field type3098 * @property {number} id Field id3099 * @property {Object.<string,*>} [options] Field options3100 */3101/**3102 * Extension field descriptor.3103 * @interface IExtensionField3104 * @extends IField3105 * @property {string} extend Extended type3106 */3107/**3108 * Converts this field to a field descriptor.3109 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options3110 * @returns {IField} Field descriptor3111 */3112Field.prototype.toJSON = function toJSON(toJSONOptions) {3113 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;3114 return util.toObject([3115 "rule" , this.rule !== "optional" && this.rule || undefined,3116 "type" , this.type,3117 "id" , this.id,3118 "extend" , this.extend,3119 "options" , this.options,3120 "comment" , keepComments ? this.comment : undefined3121 ]);3122};3123/**3124 * Resolves this field's type references.3125 * @returns {Field} `this`3126 * @throws {Error} If any reference cannot be resolved3127 */3128Field.prototype.resolve = function resolve() {3129 if (this.resolved)3130 return this;3131 if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it3132 this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);3133 if (this.resolvedType instanceof Type)3134 this.typeDefault = null;3135 else // instanceof Enum3136 this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined3137 }3138 // use explicitly set default value if present3139 if (this.options && this.options["default"] != null) {3140 this.typeDefault = this.options["default"];3141 if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")3142 this.typeDefault = this.resolvedType.values[this.typeDefault];3143 }3144 // remove unnecessary options3145 if (this.options) {3146 if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))3147 delete this.options.packed;3148 if (!Object.keys(this.options).length)3149 this.options = undefined;3150 }3151 // convert to internal data type if necesssary3152 if (this.long) {3153 this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");3154 /* istanbul ignore else */3155 if (Object.freeze)3156 Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)3157 } else if (this.bytes && typeof this.typeDefault === "string") {3158 var buf;3159 if (util.base64.test(this.typeDefault))3160 util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);3161 else3162 util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);3163 this.typeDefault = buf;3164 }3165 // take special care of maps and repeated fields3166 if (this.map)3167 this.defaultValue = util.emptyObject;3168 else if (this.repeated)3169 this.defaultValue = util.emptyArray;3170 else3171 this.defaultValue = this.typeDefault;3172 // ensure proper value on prototype3173 if (this.parent instanceof Type)3174 this.parent.ctor.prototype[this.name] = this.defaultValue;3175 return ReflectionObject.prototype.resolve.call(this);3176};3177/**3178 * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).3179 * @typedef FieldDecorator3180 * @type {function}3181 * @param {Object} prototype Target prototype3182 * @param {string} fieldName Field name3183 * @returns {undefined}3184 */3185/**3186 * Field decorator (TypeScript).3187 * @name Field.d3188 * @function3189 * @param {number} fieldId Field id3190 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type3191 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule3192 * @param {T} [defaultValue] Default value3193 * @returns {FieldDecorator} Decorator function3194 * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]3195 */3196Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {3197 // submessage: decorate the submessage and use its name as the type3198 if (typeof fieldType === "function")3199 fieldType = util.decorateType(fieldType).name;3200 // enum reference: create a reflected copy of the enum and keep reuseing it3201 else if (fieldType && typeof fieldType === "object")3202 fieldType = util.decorateEnum(fieldType).name;3203 return function fieldDecorator(prototype, fieldName) {3204 util.decorateType(prototype.constructor)3205 .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));3206 };3207};3208/**3209 * Field decorator (TypeScript).3210 * @name Field.d3211 * @function3212 * @param {number} fieldId Field id3213 * @param {Constructor<T>|string} fieldType Field type3214 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule3215 * @returns {FieldDecorator} Decorator function3216 * @template T extends Message<T>3217 * @variation 23218 */3219// like Field.d but without a default value3220// Sets up cyclic dependencies (called in index-light)3221Field._configure = function configure(Type_) {3222 Type = Type_;3223};3224},{"./enum":21,"./object":30,"./types":42,"./util":43}],23:[function(require,module,exports){3225"use strict";3226var protobuf = module.exports = require("./index-minimal");3227protobuf.build = "light";3228/**3229 * A node-style callback as used by {@link load} and {@link Root#load}.3230 * @typedef LoadCallback3231 * @type {function}3232 * @param {Error|null} error Error, if any, otherwise `null`3233 * @param {Root} [root] Root, if there hasn't been an error3234 * @returns {undefined}3235 */3236/**3237 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.3238 * @param {string|string[]} filename One or multiple files to load3239 * @param {Root} root Root namespace, defaults to create a new one if omitted.3240 * @param {LoadCallback} callback Callback function3241 * @returns {undefined}3242 * @see {@link Root#load}3243 */3244function load(filename, root, callback) {3245 if (typeof root === "function") {3246 callback = root;3247 root = new protobuf.Root();3248 } else if (!root)3249 root = new protobuf.Root();3250 return root.load(filename, callback);3251}3252/**3253 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.3254 * @name load3255 * @function3256 * @param {string|string[]} filename One or multiple files to load3257 * @param {LoadCallback} callback Callback function3258 * @returns {undefined}3259 * @see {@link Root#load}3260 * @variation 23261 */3262// function load(filename:string, callback:LoadCallback):undefined3263/**3264 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.3265 * @name load3266 * @function3267 * @param {string|string[]} filename One or multiple files to load3268 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.3269 * @returns {Promise<Root>} Promise3270 * @see {@link Root#load}3271 * @variation 33272 */3273// function load(filename:string, [root:Root]):Promise<Root>3274protobuf.load = load;3275/**3276 * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).3277 * @param {string|string[]} filename One or multiple files to load3278 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.3279 * @returns {Root} Root namespace3280 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid3281 * @see {@link Root#loadSync}3282 */3283function loadSync(filename, root) {3284 if (!root)3285 root = new protobuf.Root();3286 return root.loadSync(filename);3287}3288protobuf.loadSync = loadSync;3289// Serialization3290protobuf.encoder = require("./encoder");3291protobuf.decoder = require("./decoder");3292protobuf.verifier = require("./verifier");3293protobuf.converter = require("./converter");3294// Reflection3295protobuf.ReflectionObject = require("./object");3296protobuf.Namespace = require("./namespace");3297protobuf.Root = require("./root");3298protobuf.Enum = require("./enum");3299protobuf.Type = require("./type");3300protobuf.Field = require("./field");3301protobuf.OneOf = require("./oneof");3302protobuf.MapField = require("./mapfield");3303protobuf.Service = require("./service");3304protobuf.Method = require("./method");3305// Runtime3306protobuf.Message = require("./message");3307protobuf.wrappers = require("./wrappers");3308// Utility3309protobuf.types = require("./types");3310protobuf.util = require("./util");3311// Set up possibly cyclic reflection dependencies3312protobuf.ReflectionObject._configure(protobuf.Root);3313protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);3314protobuf.Root._configure(protobuf.Type);3315protobuf.Field._configure(protobuf.Type);3316},{"./converter":18,"./decoder":19,"./encoder":20,"./enum":21,"./field":22,"./index-minimal":24,"./mapfield":26,"./message":27,"./method":28,"./namespace":29,"./object":30,"./oneof":31,"./root":35,"./service":39,"./type":41,"./types":42,"./util":43,"./verifier":46,"./wrappers":47}],24:[function(require,module,exports){3317"use strict";3318var protobuf = exports;3319/**3320 * Build type, one of `"full"`, `"light"` or `"minimal"`.3321 * @name build3322 * @type {string}3323 * @const3324 */3325protobuf.build = "minimal";3326// Serialization3327protobuf.Writer = require("./writer");3328protobuf.BufferWriter = require("./writer_buffer");3329protobuf.Reader = require("./reader");3330protobuf.BufferReader = require("./reader_buffer");3331// Utility3332protobuf.util = require("./util/minimal");3333protobuf.rpc = require("./rpc");3334protobuf.roots = require("./roots");3335protobuf.configure = configure;3336/* istanbul ignore next */3337/**3338 * Reconfigures the library according to the environment.3339 * @returns {undefined}3340 */3341function configure() {3342 protobuf.Reader._configure(protobuf.BufferReader);3343 protobuf.util._configure();3344}3345// Set up buffer utility according to the environment3346protobuf.Writer._configure(protobuf.BufferWriter);3347configure();3348},{"./reader":33,"./reader_buffer":34,"./roots":36,"./rpc":37,"./util/minimal":45,"./writer":48,"./writer_buffer":49}],25:[function(require,module,exports){3349"use strict";3350var protobuf = module.exports = require("./index-light");3351protobuf.build = "full";3352// Parser3353protobuf.tokenize = require("./tokenize");3354protobuf.parse = require("./parse");3355protobuf.common = require("./common");3356// Configure parser3357protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);3358},{"./common":17,"./index-light":23,"./parse":32,"./tokenize":40}],26:[function(require,module,exports){3359"use strict";3360module.exports = MapField;3361// extends Field3362var Field = require("./field");3363((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";3364var types = require("./types"),3365 util = require("./util");3366/**3367 * Constructs a new map field instance.3368 * @classdesc Reflected map field.3369 * @extends FieldBase3370 * @constructor3371 * @param {string} name Unique name within its namespace3372 * @param {number} id Unique id within its namespace3373 * @param {string} keyType Key type3374 * @param {string} type Value type3375 * @param {Object.<string,*>} [options] Declared options3376 * @param {string} [comment] Comment associated with this field3377 */3378function MapField(name, id, keyType, type, options, comment) {3379 Field.call(this, name, id, type, undefined, undefined, options, comment);3380 /* istanbul ignore if */3381 if (!util.isString(keyType))3382 throw TypeError("keyType must be a string");3383 /**3384 * Key type.3385 * @type {string}3386 */3387 this.keyType = keyType; // toJSON, marker3388 /**3389 * Resolved key type if not a basic type.3390 * @type {ReflectionObject|null}3391 */3392 this.resolvedKeyType = null;3393 // Overrides Field#map3394 this.map = true;3395}3396/**3397 * Map field descriptor.3398 * @interface IMapField3399 * @extends {IField}3400 * @property {string} keyType Key type3401 */3402/**3403 * Extension map field descriptor.3404 * @interface IExtensionMapField3405 * @extends IMapField3406 * @property {string} extend Extended type3407 */3408/**3409 * Constructs a map field from a map field descriptor.3410 * @param {string} name Field name3411 * @param {IMapField} json Map field descriptor3412 * @returns {MapField} Created map field3413 * @throws {TypeError} If arguments are invalid3414 */3415MapField.fromJSON = function fromJSON(name, json) {3416 return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);3417};3418/**3419 * Converts this map field to a map field descriptor.3420 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options3421 * @returns {IMapField} Map field descriptor3422 */3423MapField.prototype.toJSON = function toJSON(toJSONOptions) {3424 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;3425 return util.toObject([3426 "keyType" , this.keyType,3427 "type" , this.type,3428 "id" , this.id,3429 "extend" , this.extend,3430 "options" , this.options,3431 "comment" , keepComments ? this.comment : undefined3432 ]);3433};3434/**3435 * @override3436 */3437MapField.prototype.resolve = function resolve() {3438 if (this.resolved)3439 return this;3440 // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"3441 if (types.mapKey[this.keyType] === undefined)3442 throw Error("invalid key type: " + this.keyType);3443 return Field.prototype.resolve.call(this);3444};3445/**3446 * Map field decorator (TypeScript).3447 * @name MapField.d3448 * @function3449 * @param {number} fieldId Field id3450 * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type3451 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type3452 * @returns {FieldDecorator} Decorator function3453 * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }3454 */3455MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {3456 // submessage value: decorate the submessage and use its name as the type3457 if (typeof fieldValueType === "function")3458 fieldValueType = util.decorateType(fieldValueType).name;3459 // enum reference value: create a reflected copy of the enum and keep reuseing it3460 else if (fieldValueType && typeof fieldValueType === "object")3461 fieldValueType = util.decorateEnum(fieldValueType).name;3462 return function mapFieldDecorator(prototype, fieldName) {3463 util.decorateType(prototype.constructor)3464 .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));3465 };3466};3467},{"./field":22,"./types":42,"./util":43}],27:[function(require,module,exports){3468"use strict";3469module.exports = Message;3470var util = require("./util/minimal");3471/**3472 * Constructs a new message instance.3473 * @classdesc Abstract runtime message.3474 * @constructor3475 * @param {Properties<T>} [properties] Properties to set3476 * @template T extends object = object3477 */3478function Message(properties) {3479 // not used internally3480 if (properties)3481 for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)3482 this[keys[i]] = properties[keys[i]];3483}3484/**3485 * Reference to the reflected type.3486 * @name Message.$type3487 * @type {Type}3488 * @readonly3489 */3490/**3491 * Reference to the reflected type.3492 * @name Message#$type3493 * @type {Type}3494 * @readonly3495 */3496/*eslint-disable valid-jsdoc*/3497/**3498 * Creates a new message of this type using the specified properties.3499 * @param {Object.<string,*>} [properties] Properties to set3500 * @returns {Message<T>} Message instance3501 * @template T extends Message<T>3502 * @this Constructor<T>3503 */3504Message.create = function create(properties) {3505 return this.$type.create(properties);3506};3507/**3508 * Encodes a message of this type.3509 * @param {T|Object.<string,*>} message Message to encode3510 * @param {Writer} [writer] Writer to use3511 * @returns {Writer} Writer3512 * @template T extends Message<T>3513 * @this Constructor<T>3514 */3515Message.encode = function encode(message, writer) {3516 return this.$type.encode(message, writer);3517};3518/**3519 * Encodes a message of this type preceeded by its length as a varint.3520 * @param {T|Object.<string,*>} message Message to encode3521 * @param {Writer} [writer] Writer to use3522 * @returns {Writer} Writer3523 * @template T extends Message<T>3524 * @this Constructor<T>3525 */3526Message.encodeDelimited = function encodeDelimited(message, writer) {3527 return this.$type.encodeDelimited(message, writer);3528};3529/**3530 * Decodes a message of this type.3531 * @name Message.decode3532 * @function3533 * @param {Reader|Uint8Array} reader Reader or buffer to decode3534 * @returns {T} Decoded message3535 * @template T extends Message<T>3536 * @this Constructor<T>3537 */3538Message.decode = function decode(reader) {3539 return this.$type.decode(reader);3540};3541/**3542 * Decodes a message of this type preceeded by its length as a varint.3543 * @name Message.decodeDelimited3544 * @function3545 * @param {Reader|Uint8Array} reader Reader or buffer to decode3546 * @returns {T} Decoded message3547 * @template T extends Message<T>3548 * @this Constructor<T>3549 */3550Message.decodeDelimited = function decodeDelimited(reader) {3551 return this.$type.decodeDelimited(reader);3552};3553/**3554 * Verifies a message of this type.3555 * @name Message.verify3556 * @function3557 * @param {Object.<string,*>} message Plain object to verify3558 * @returns {string|null} `null` if valid, otherwise the reason why it is not3559 */3560Message.verify = function verify(message) {3561 return this.$type.verify(message);3562};3563/**3564 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.3565 * @param {Object.<string,*>} object Plain object3566 * @returns {T} Message instance3567 * @template T extends Message<T>3568 * @this Constructor<T>3569 */3570Message.fromObject = function fromObject(object) {3571 return this.$type.fromObject(object);3572};3573/**3574 * Creates a plain object from a message of this type. Also converts values to other types if specified.3575 * @param {T} message Message instance3576 * @param {IConversionOptions} [options] Conversion options3577 * @returns {Object.<string,*>} Plain object3578 * @template T extends Message<T>3579 * @this Constructor<T>3580 */3581Message.toObject = function toObject(message, options) {3582 return this.$type.toObject(message, options);3583};3584/**3585 * Converts this message to JSON.3586 * @returns {Object.<string,*>} JSON object3587 */3588Message.prototype.toJSON = function toJSON() {3589 return this.$type.toObject(this, util.toJSONOptions);3590};3591/*eslint-enable valid-jsdoc*/3592},{"./util/minimal":45}],28:[function(require,module,exports){3593"use strict";3594module.exports = Method;3595// extends ReflectionObject3596var ReflectionObject = require("./object");3597((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";3598var util = require("./util");3599/**3600 * Constructs a new service method instance.3601 * @classdesc Reflected service method.3602 * @extends ReflectionObject3603 * @constructor3604 * @param {string} name Method name3605 * @param {string|undefined} type Method type, usually `"rpc"`3606 * @param {string} requestType Request message type3607 * @param {string} responseType Response message type3608 * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed3609 * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed3610 * @param {Object.<string,*>} [options] Declared options3611 * @param {string} [comment] The comment for this method3612 */3613function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment) {3614 /* istanbul ignore next */3615 if (util.isObject(requestStream)) {3616 options = requestStream;3617 requestStream = responseStream = undefined;3618 } else if (util.isObject(responseStream)) {3619 options = responseStream;3620 responseStream = undefined;3621 }3622 /* istanbul ignore if */3623 if (!(type === undefined || util.isString(type)))3624 throw TypeError("type must be a string");3625 /* istanbul ignore if */3626 if (!util.isString(requestType))3627 throw TypeError("requestType must be a string");3628 /* istanbul ignore if */3629 if (!util.isString(responseType))3630 throw TypeError("responseType must be a string");3631 ReflectionObject.call(this, name, options);3632 /**3633 * Method type.3634 * @type {string}3635 */3636 this.type = type || "rpc"; // toJSON3637 /**3638 * Request type.3639 * @type {string}3640 */3641 this.requestType = requestType; // toJSON, marker3642 /**3643 * Whether requests are streamed or not.3644 * @type {boolean|undefined}3645 */3646 this.requestStream = requestStream ? true : undefined; // toJSON3647 /**3648 * Response type.3649 * @type {string}3650 */3651 this.responseType = responseType; // toJSON3652 /**3653 * Whether responses are streamed or not.3654 * @type {boolean|undefined}3655 */3656 this.responseStream = responseStream ? true : undefined; // toJSON3657 /**3658 * Resolved request type.3659 * @type {Type|null}3660 */3661 this.resolvedRequestType = null;3662 /**3663 * Resolved response type.3664 * @type {Type|null}3665 */3666 this.resolvedResponseType = null;3667 /**3668 * Comment for this method3669 * @type {string|null}3670 */3671 this.comment = comment;3672}3673/**3674 * Method descriptor.3675 * @interface IMethod3676 * @property {string} [type="rpc"] Method type3677 * @property {string} requestType Request type3678 * @property {string} responseType Response type3679 * @property {boolean} [requestStream=false] Whether requests are streamed3680 * @property {boolean} [responseStream=false] Whether responses are streamed3681 * @property {Object.<string,*>} [options] Method options3682 */3683/**3684 * Constructs a method from a method descriptor.3685 * @param {string} name Method name3686 * @param {IMethod} json Method descriptor3687 * @returns {Method} Created method3688 * @throws {TypeError} If arguments are invalid3689 */3690Method.fromJSON = function fromJSON(name, json) {3691 return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment);3692};3693/**3694 * Converts this method to a method descriptor.3695 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options3696 * @returns {IMethod} Method descriptor3697 */3698Method.prototype.toJSON = function toJSON(toJSONOptions) {3699 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;3700 return util.toObject([3701 "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,3702 "requestType" , this.requestType,3703 "requestStream" , this.requestStream,3704 "responseType" , this.responseType,3705 "responseStream" , this.responseStream,3706 "options" , this.options,3707 "comment" , keepComments ? this.comment : undefined3708 ]);3709};3710/**3711 * @override3712 */3713Method.prototype.resolve = function resolve() {3714 /* istanbul ignore if */3715 if (this.resolved)3716 return this;3717 this.resolvedRequestType = this.parent.lookupType(this.requestType);3718 this.resolvedResponseType = this.parent.lookupType(this.responseType);3719 return ReflectionObject.prototype.resolve.call(this);3720};3721},{"./object":30,"./util":43}],29:[function(require,module,exports){3722"use strict";3723module.exports = Namespace;3724// extends ReflectionObject3725var ReflectionObject = require("./object");3726((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";3727var Field = require("./field"),3728 util = require("./util");3729var Type, // cyclic3730 Service,3731 Enum;3732/**3733 * Constructs a new namespace instance.3734 * @name Namespace3735 * @classdesc Reflected namespace.3736 * @extends NamespaceBase3737 * @constructor3738 * @param {string} name Namespace name3739 * @param {Object.<string,*>} [options] Declared options3740 */3741/**3742 * Constructs a namespace from JSON.3743 * @memberof Namespace3744 * @function3745 * @param {string} name Namespace name3746 * @param {Object.<string,*>} json JSON object3747 * @returns {Namespace} Created namespace3748 * @throws {TypeError} If arguments are invalid3749 */3750Namespace.fromJSON = function fromJSON(name, json) {3751 return new Namespace(name, json.options).addJSON(json.nested);3752};3753/**3754 * Converts an array of reflection objects to JSON.3755 * @memberof Namespace3756 * @param {ReflectionObject[]} array Object array3757 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options3758 * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty3759 */3760function arrayToJSON(array, toJSONOptions) {3761 if (!(array && array.length))3762 return undefined;3763 var obj = {};3764 for (var i = 0; i < array.length; ++i)3765 obj[array[i].name] = array[i].toJSON(toJSONOptions);3766 return obj;3767}3768Namespace.arrayToJSON = arrayToJSON;3769/**3770 * Tests if the specified id is reserved.3771 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names3772 * @param {number} id Id to test3773 * @returns {boolean} `true` if reserved, otherwise `false`3774 */3775Namespace.isReservedId = function isReservedId(reserved, id) {3776 if (reserved)3777 for (var i = 0; i < reserved.length; ++i)3778 if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id)3779 return true;3780 return false;3781};3782/**3783 * Tests if the specified name is reserved.3784 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names3785 * @param {string} name Name to test3786 * @returns {boolean} `true` if reserved, otherwise `false`3787 */3788Namespace.isReservedName = function isReservedName(reserved, name) {3789 if (reserved)3790 for (var i = 0; i < reserved.length; ++i)3791 if (reserved[i] === name)3792 return true;3793 return false;3794};3795/**3796 * Not an actual constructor. Use {@link Namespace} instead.3797 * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.3798 * @exports NamespaceBase3799 * @extends ReflectionObject3800 * @abstract3801 * @constructor3802 * @param {string} name Namespace name3803 * @param {Object.<string,*>} [options] Declared options3804 * @see {@link Namespace}3805 */3806function Namespace(name, options) {3807 ReflectionObject.call(this, name, options);3808 /**3809 * Nested objects by name.3810 * @type {Object.<string,ReflectionObject>|undefined}3811 */3812 this.nested = undefined; // toJSON3813 /**3814 * Cached nested objects as an array.3815 * @type {ReflectionObject[]|null}3816 * @private3817 */3818 this._nestedArray = null;3819}3820function clearCache(namespace) {3821 namespace._nestedArray = null;3822 return namespace;3823}3824/**3825 * Nested objects of this namespace as an array for iteration.3826 * @name NamespaceBase#nestedArray3827 * @type {ReflectionObject[]}3828 * @readonly3829 */3830Object.defineProperty(Namespace.prototype, "nestedArray", {3831 get: function() {3832 return this._nestedArray || (this._nestedArray = util.toArray(this.nested));3833 }3834});3835/**3836 * Namespace descriptor.3837 * @interface INamespace3838 * @property {Object.<string,*>} [options] Namespace options3839 * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors3840 */3841/**3842 * Any extension field descriptor.3843 * @typedef AnyExtensionField3844 * @type {IExtensionField|IExtensionMapField}3845 */3846/**3847 * Any nested object descriptor.3848 * @typedef AnyNestedObject3849 * @type {IEnum|IType|IService|AnyExtensionField|INamespace}3850 */3851// ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)3852/**3853 * Converts this namespace to a namespace descriptor.3854 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options3855 * @returns {INamespace} Namespace descriptor3856 */3857Namespace.prototype.toJSON = function toJSON(toJSONOptions) {3858 return util.toObject([3859 "options" , this.options,3860 "nested" , arrayToJSON(this.nestedArray, toJSONOptions)3861 ]);3862};3863/**3864 * Adds nested objects to this namespace from nested object descriptors.3865 * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors3866 * @returns {Namespace} `this`3867 */3868Namespace.prototype.addJSON = function addJSON(nestedJson) {3869 var ns = this;3870 /* istanbul ignore else */3871 if (nestedJson) {3872 for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {3873 nested = nestedJson[names[i]];3874 ns.add( // most to least likely3875 ( nested.fields !== undefined3876 ? Type.fromJSON3877 : nested.values !== undefined3878 ? Enum.fromJSON3879 : nested.methods !== undefined3880 ? Service.fromJSON3881 : nested.id !== undefined3882 ? Field.fromJSON3883 : Namespace.fromJSON )(names[i], nested)3884 );3885 }3886 }3887 return this;3888};3889/**3890 * Gets the nested object of the specified name.3891 * @param {string} name Nested object name3892 * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist3893 */3894Namespace.prototype.get = function get(name) {3895 return this.nested && this.nested[name]3896 || null;3897};3898/**3899 * Gets the values of the nested {@link Enum|enum} of the specified name.3900 * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.3901 * @param {string} name Nested enum name3902 * @returns {Object.<string,number>} Enum values3903 * @throws {Error} If there is no such enum3904 */3905Namespace.prototype.getEnum = function getEnum(name) {3906 if (this.nested && this.nested[name] instanceof Enum)3907 return this.nested[name].values;3908 throw Error("no such enum: " + name);3909};3910/**3911 * Adds a nested object to this namespace.3912 * @param {ReflectionObject} object Nested object to add3913 * @returns {Namespace} `this`3914 * @throws {TypeError} If arguments are invalid3915 * @throws {Error} If there is already a nested object with this name3916 */3917Namespace.prototype.add = function add(object) {3918 if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))3919 throw TypeError("object must be a valid nested object");3920 if (!this.nested)3921 this.nested = {};3922 else {3923 var prev = this.get(object.name);3924 if (prev) {3925 if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {3926 // replace plain namespace but keep existing nested elements and options3927 var nested = prev.nestedArray;3928 for (var i = 0; i < nested.length; ++i)3929 object.add(nested[i]);3930 this.remove(prev);3931 if (!this.nested)3932 this.nested = {};3933 object.setOptions(prev.options, true);3934 } else3935 throw Error("duplicate name '" + object.name + "' in " + this);3936 }3937 }3938 this.nested[object.name] = object;3939 object.onAdd(this);3940 return clearCache(this);3941};3942/**3943 * Removes a nested object from this namespace.3944 * @param {ReflectionObject} object Nested object to remove3945 * @returns {Namespace} `this`3946 * @throws {TypeError} If arguments are invalid3947 * @throws {Error} If `object` is not a member of this namespace3948 */3949Namespace.prototype.remove = function remove(object) {3950 if (!(object instanceof ReflectionObject))3951 throw TypeError("object must be a ReflectionObject");3952 if (object.parent !== this)3953 throw Error(object + " is not a member of " + this);3954 delete this.nested[object.name];3955 if (!Object.keys(this.nested).length)3956 this.nested = undefined;3957 object.onRemove(this);3958 return clearCache(this);3959};3960/**3961 * Defines additial namespaces within this one if not yet existing.3962 * @param {string|string[]} path Path to create3963 * @param {*} [json] Nested types to create from JSON3964 * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty3965 */3966Namespace.prototype.define = function define(path, json) {3967 if (util.isString(path))3968 path = path.split(".");3969 else if (!Array.isArray(path))3970 throw TypeError("illegal path");3971 if (path && path.length && path[0] === "")3972 throw Error("path must be relative");3973 var ptr = this;3974 while (path.length > 0) {3975 var part = path.shift();3976 if (ptr.nested && ptr.nested[part]) {3977 ptr = ptr.nested[part];3978 if (!(ptr instanceof Namespace))3979 throw Error("path conflicts with non-namespace objects");3980 } else3981 ptr.add(ptr = new Namespace(part));3982 }3983 if (json)3984 ptr.addJSON(json);3985 return ptr;3986};3987/**3988 * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.3989 * @returns {Namespace} `this`3990 */3991Namespace.prototype.resolveAll = function resolveAll() {3992 var nested = this.nestedArray, i = 0;3993 while (i < nested.length)3994 if (nested[i] instanceof Namespace)3995 nested[i++].resolveAll();3996 else3997 nested[i++].resolve();3998 return this.resolve();3999};4000/**4001 * Recursively looks up the reflection object matching the specified path in the scope of this namespace.4002 * @param {string|string[]} path Path to look up4003 * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.4004 * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked4005 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found4006 */4007Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {4008 /* istanbul ignore next */4009 if (typeof filterTypes === "boolean") {4010 parentAlreadyChecked = filterTypes;4011 filterTypes = undefined;4012 } else if (filterTypes && !Array.isArray(filterTypes))4013 filterTypes = [ filterTypes ];4014 if (util.isString(path) && path.length) {4015 if (path === ".")4016 return this.root;4017 path = path.split(".");4018 } else if (!path.length)4019 return this;4020 // Start at root if path is absolute4021 if (path[0] === "")4022 return this.root.lookup(path.slice(1), filterTypes);4023 // Test if the first part matches any nested object, and if so, traverse if path contains more4024 var found = this.get(path[0]);4025 if (found) {4026 if (path.length === 1) {4027 if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)4028 return found;4029 } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))4030 return found;4031 // Otherwise try each nested namespace4032 } else4033 for (var i = 0; i < this.nestedArray.length; ++i)4034 if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))4035 return found;4036 // If there hasn't been a match, try again at the parent4037 if (this.parent === null || parentAlreadyChecked)4038 return null;4039 return this.parent.lookup(path, filterTypes);4040};4041/**4042 * Looks up the reflection object at the specified path, relative to this namespace.4043 * @name NamespaceBase#lookup4044 * @function4045 * @param {string|string[]} path Path to look up4046 * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked4047 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found4048 * @variation 24049 */4050// lookup(path: string, [parentAlreadyChecked: boolean])4051/**4052 * Looks up the {@link Type|type} at the specified path, relative to this namespace.4053 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.4054 * @param {string|string[]} path Path to look up4055 * @returns {Type} Looked up type4056 * @throws {Error} If `path` does not point to a type4057 */4058Namespace.prototype.lookupType = function lookupType(path) {4059 var found = this.lookup(path, [ Type ]);4060 if (!found)4061 throw Error("no such type: " + path);4062 return found;4063};4064/**4065 * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.4066 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.4067 * @param {string|string[]} path Path to look up4068 * @returns {Enum} Looked up enum4069 * @throws {Error} If `path` does not point to an enum4070 */4071Namespace.prototype.lookupEnum = function lookupEnum(path) {4072 var found = this.lookup(path, [ Enum ]);4073 if (!found)4074 throw Error("no such Enum '" + path + "' in " + this);4075 return found;4076};4077/**4078 * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.4079 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.4080 * @param {string|string[]} path Path to look up4081 * @returns {Type} Looked up type or enum4082 * @throws {Error} If `path` does not point to a type or enum4083 */4084Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {4085 var found = this.lookup(path, [ Type, Enum ]);4086 if (!found)4087 throw Error("no such Type or Enum '" + path + "' in " + this);4088 return found;4089};4090/**4091 * Looks up the {@link Service|service} at the specified path, relative to this namespace.4092 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.4093 * @param {string|string[]} path Path to look up4094 * @returns {Service} Looked up service4095 * @throws {Error} If `path` does not point to a service4096 */4097Namespace.prototype.lookupService = function lookupService(path) {4098 var found = this.lookup(path, [ Service ]);4099 if (!found)4100 throw Error("no such Service '" + path + "' in " + this);4101 return found;4102};4103// Sets up cyclic dependencies (called in index-light)4104Namespace._configure = function(Type_, Service_, Enum_) {4105 Type = Type_;4106 Service = Service_;4107 Enum = Enum_;4108};4109},{"./field":22,"./object":30,"./util":43}],30:[function(require,module,exports){4110"use strict";4111module.exports = ReflectionObject;4112ReflectionObject.className = "ReflectionObject";4113var util = require("./util");4114var Root; // cyclic4115/**4116 * Constructs a new reflection object instance.4117 * @classdesc Base class of all reflection objects.4118 * @constructor4119 * @param {string} name Object name4120 * @param {Object.<string,*>} [options] Declared options4121 * @abstract4122 */4123function ReflectionObject(name, options) {4124 if (!util.isString(name))4125 throw TypeError("name must be a string");4126 if (options && !util.isObject(options))4127 throw TypeError("options must be an object");4128 /**4129 * Options.4130 * @type {Object.<string,*>|undefined}4131 */4132 this.options = options; // toJSON4133 /**4134 * Unique name within its namespace.4135 * @type {string}4136 */4137 this.name = name;4138 /**4139 * Parent namespace.4140 * @type {Namespace|null}4141 */4142 this.parent = null;4143 /**4144 * Whether already resolved or not.4145 * @type {boolean}4146 */4147 this.resolved = false;4148 /**4149 * Comment text, if any.4150 * @type {string|null}4151 */4152 this.comment = null;4153 /**4154 * Defining file name.4155 * @type {string|null}4156 */4157 this.filename = null;4158}4159Object.defineProperties(ReflectionObject.prototype, {4160 /**4161 * Reference to the root namespace.4162 * @name ReflectionObject#root4163 * @type {Root}4164 * @readonly4165 */4166 root: {4167 get: function() {4168 var ptr = this;4169 while (ptr.parent !== null)4170 ptr = ptr.parent;4171 return ptr;4172 }4173 },4174 /**4175 * Full name including leading dot.4176 * @name ReflectionObject#fullName4177 * @type {string}4178 * @readonly4179 */4180 fullName: {4181 get: function() {4182 var path = [ this.name ],4183 ptr = this.parent;4184 while (ptr) {4185 path.unshift(ptr.name);4186 ptr = ptr.parent;4187 }4188 return path.join(".");4189 }4190 }4191});4192/**4193 * Converts this reflection object to its descriptor representation.4194 * @returns {Object.<string,*>} Descriptor4195 * @abstract4196 */4197ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {4198 throw Error(); // not implemented, shouldn't happen4199};4200/**4201 * Called when this object is added to a parent.4202 * @param {ReflectionObject} parent Parent added to4203 * @returns {undefined}4204 */4205ReflectionObject.prototype.onAdd = function onAdd(parent) {4206 if (this.parent && this.parent !== parent)4207 this.parent.remove(this);4208 this.parent = parent;4209 this.resolved = false;4210 var root = parent.root;4211 if (root instanceof Root)4212 root._handleAdd(this);4213};4214/**4215 * Called when this object is removed from a parent.4216 * @param {ReflectionObject} parent Parent removed from4217 * @returns {undefined}4218 */4219ReflectionObject.prototype.onRemove = function onRemove(parent) {4220 var root = parent.root;4221 if (root instanceof Root)4222 root._handleRemove(this);4223 this.parent = null;4224 this.resolved = false;4225};4226/**4227 * Resolves this objects type references.4228 * @returns {ReflectionObject} `this`4229 */4230ReflectionObject.prototype.resolve = function resolve() {4231 if (this.resolved)4232 return this;4233 if (this.root instanceof Root)4234 this.resolved = true; // only if part of a root4235 return this;4236};4237/**4238 * Gets an option value.4239 * @param {string} name Option name4240 * @returns {*} Option value or `undefined` if not set4241 */4242ReflectionObject.prototype.getOption = function getOption(name) {4243 if (this.options)4244 return this.options[name];4245 return undefined;4246};4247/**4248 * Sets an option.4249 * @param {string} name Option name4250 * @param {*} value Option value4251 * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set4252 * @returns {ReflectionObject} `this`4253 */4254ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {4255 if (!ifNotSet || !this.options || this.options[name] === undefined)4256 (this.options || (this.options = {}))[name] = value;4257 return this;4258};4259/**4260 * Sets multiple options.4261 * @param {Object.<string,*>} options Options to set4262 * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set4263 * @returns {ReflectionObject} `this`4264 */4265ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {4266 if (options)4267 for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)4268 this.setOption(keys[i], options[keys[i]], ifNotSet);4269 return this;4270};4271/**4272 * Converts this instance to its string representation.4273 * @returns {string} Class name[, space, full name]4274 */4275ReflectionObject.prototype.toString = function toString() {4276 var className = this.constructor.className,4277 fullName = this.fullName;4278 if (fullName.length)4279 return className + " " + fullName;4280 return className;4281};4282// Sets up cyclic dependencies (called in index-light)4283ReflectionObject._configure = function(Root_) {4284 Root = Root_;4285};4286},{"./util":43}],31:[function(require,module,exports){4287"use strict";4288module.exports = OneOf;4289// extends ReflectionObject4290var ReflectionObject = require("./object");4291((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";4292var Field = require("./field"),4293 util = require("./util");4294/**4295 * Constructs a new oneof instance.4296 * @classdesc Reflected oneof.4297 * @extends ReflectionObject4298 * @constructor4299 * @param {string} name Oneof name4300 * @param {string[]|Object.<string,*>} [fieldNames] Field names4301 * @param {Object.<string,*>} [options] Declared options4302 * @param {string} [comment] Comment associated with this field4303 */4304function OneOf(name, fieldNames, options, comment) {4305 if (!Array.isArray(fieldNames)) {4306 options = fieldNames;4307 fieldNames = undefined;4308 }4309 ReflectionObject.call(this, name, options);4310 /* istanbul ignore if */4311 if (!(fieldNames === undefined || Array.isArray(fieldNames)))4312 throw TypeError("fieldNames must be an Array");4313 /**4314 * Field names that belong to this oneof.4315 * @type {string[]}4316 */4317 this.oneof = fieldNames || []; // toJSON, marker4318 /**4319 * Fields that belong to this oneof as an array for iteration.4320 * @type {Field[]}4321 * @readonly4322 */4323 this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent4324 /**4325 * Comment for this field.4326 * @type {string|null}4327 */4328 this.comment = comment;4329}4330/**4331 * Oneof descriptor.4332 * @interface IOneOf4333 * @property {Array.<string>} oneof Oneof field names4334 * @property {Object.<string,*>} [options] Oneof options4335 */4336/**4337 * Constructs a oneof from a oneof descriptor.4338 * @param {string} name Oneof name4339 * @param {IOneOf} json Oneof descriptor4340 * @returns {OneOf} Created oneof4341 * @throws {TypeError} If arguments are invalid4342 */4343OneOf.fromJSON = function fromJSON(name, json) {4344 return new OneOf(name, json.oneof, json.options, json.comment);4345};4346/**4347 * Converts this oneof to a oneof descriptor.4348 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options4349 * @returns {IOneOf} Oneof descriptor4350 */4351OneOf.prototype.toJSON = function toJSON(toJSONOptions) {4352 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;4353 return util.toObject([4354 "options" , this.options,4355 "oneof" , this.oneof,4356 "comment" , keepComments ? this.comment : undefined4357 ]);4358};4359/**4360 * Adds the fields of the specified oneof to the parent if not already done so.4361 * @param {OneOf} oneof The oneof4362 * @returns {undefined}4363 * @inner4364 * @ignore4365 */4366function addFieldsToParent(oneof) {4367 if (oneof.parent)4368 for (var i = 0; i < oneof.fieldsArray.length; ++i)4369 if (!oneof.fieldsArray[i].parent)4370 oneof.parent.add(oneof.fieldsArray[i]);4371}4372/**4373 * Adds a field to this oneof and removes it from its current parent, if any.4374 * @param {Field} field Field to add4375 * @returns {OneOf} `this`4376 */4377OneOf.prototype.add = function add(field) {4378 /* istanbul ignore if */4379 if (!(field instanceof Field))4380 throw TypeError("field must be a Field");4381 if (field.parent && field.parent !== this.parent)4382 field.parent.remove(field);4383 this.oneof.push(field.name);4384 this.fieldsArray.push(field);4385 field.partOf = this; // field.parent remains null4386 addFieldsToParent(this);4387 return this;4388};4389/**4390 * Removes a field from this oneof and puts it back to the oneof's parent.4391 * @param {Field} field Field to remove4392 * @returns {OneOf} `this`4393 */4394OneOf.prototype.remove = function remove(field) {4395 /* istanbul ignore if */4396 if (!(field instanceof Field))4397 throw TypeError("field must be a Field");4398 var index = this.fieldsArray.indexOf(field);4399 /* istanbul ignore if */4400 if (index < 0)4401 throw Error(field + " is not a member of " + this);4402 this.fieldsArray.splice(index, 1);4403 index = this.oneof.indexOf(field.name);4404 /* istanbul ignore else */4405 if (index > -1) // theoretical4406 this.oneof.splice(index, 1);4407 field.partOf = null;4408 return this;4409};4410/**4411 * @override4412 */4413OneOf.prototype.onAdd = function onAdd(parent) {4414 ReflectionObject.prototype.onAdd.call(this, parent);4415 var self = this;4416 // Collect present fields4417 for (var i = 0; i < this.oneof.length; ++i) {4418 var field = parent.get(this.oneof[i]);4419 if (field && !field.partOf) {4420 field.partOf = self;4421 self.fieldsArray.push(field);4422 }4423 }4424 // Add not yet present fields4425 addFieldsToParent(this);4426};4427/**4428 * @override4429 */4430OneOf.prototype.onRemove = function onRemove(parent) {4431 for (var i = 0, field; i < this.fieldsArray.length; ++i)4432 if ((field = this.fieldsArray[i]).parent)4433 field.parent.remove(field);4434 ReflectionObject.prototype.onRemove.call(this, parent);4435};4436/**4437 * Decorator function as returned by {@link OneOf.d} (TypeScript).4438 * @typedef OneOfDecorator4439 * @type {function}4440 * @param {Object} prototype Target prototype4441 * @param {string} oneofName OneOf name4442 * @returns {undefined}4443 */4444/**4445 * OneOf decorator (TypeScript).4446 * @function4447 * @param {...string} fieldNames Field names4448 * @returns {OneOfDecorator} Decorator function4449 * @template T extends string4450 */4451OneOf.d = function decorateOneOf() {4452 var fieldNames = new Array(arguments.length),4453 index = 0;4454 while (index < arguments.length)4455 fieldNames[index] = arguments[index++];4456 return function oneOfDecorator(prototype, oneofName) {4457 util.decorateType(prototype.constructor)4458 .add(new OneOf(oneofName, fieldNames));4459 Object.defineProperty(prototype, oneofName, {4460 get: util.oneOfGetter(fieldNames),4461 set: util.oneOfSetter(fieldNames)4462 });4463 };4464};4465},{"./field":22,"./object":30,"./util":43}],32:[function(require,module,exports){4466"use strict";4467module.exports = parse;4468parse.filename = null;4469parse.defaults = { keepCase: false };4470var tokenize = require("./tokenize"),4471 Root = require("./root"),4472 Type = require("./type"),4473 Field = require("./field"),4474 MapField = require("./mapfield"),4475 OneOf = require("./oneof"),4476 Enum = require("./enum"),4477 Service = require("./service"),4478 Method = require("./method"),4479 types = require("./types"),4480 util = require("./util");4481var base10Re = /^[1-9][0-9]*$/,4482 base10NegRe = /^-?[1-9][0-9]*$/,4483 base16Re = /^0[x][0-9a-fA-F]+$/,4484 base16NegRe = /^-?0[x][0-9a-fA-F]+$/,4485 base8Re = /^0[0-7]+$/,4486 base8NegRe = /^-?0[0-7]+$/,4487 numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,4488 nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,4489 typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,4490 fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;4491/**4492 * Result object returned from {@link parse}.4493 * @interface IParserResult4494 * @property {string|undefined} package Package name, if declared4495 * @property {string[]|undefined} imports Imports, if any4496 * @property {string[]|undefined} weakImports Weak imports, if any4497 * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`)4498 * @property {Root} root Populated root instance4499 */4500/**4501 * Options modifying the behavior of {@link parse}.4502 * @interface IParseOptions4503 * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case4504 * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.4505 */4506/**4507 * Options modifying the behavior of JSON serialization.4508 * @interface IToJSONOptions4509 * @property {boolean} [keepComments=false] Serializes comments.4510 */4511/**4512 * Parses the given .proto source and returns an object with the parsed contents.4513 * @param {string} source Source contents4514 * @param {Root} root Root to populate4515 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.4516 * @returns {IParserResult} Parser result4517 * @property {string} filename=null Currently processing file name for error reporting, if known4518 * @property {IParseOptions} defaults Default {@link IParseOptions}4519 */4520function parse(source, root, options) {4521 /* eslint-disable callback-return */4522 if (!(root instanceof Root)) {4523 options = root;4524 root = new Root();4525 }4526 if (!options)4527 options = parse.defaults;4528 var tn = tokenize(source, options.alternateCommentMode || false),4529 next = tn.next,4530 push = tn.push,4531 peek = tn.peek,4532 skip = tn.skip,4533 cmnt = tn.cmnt;4534 var head = true,4535 pkg,4536 imports,4537 weakImports,4538 syntax,4539 isProto3 = false;4540 var ptr = root;4541 var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;4542 /* istanbul ignore next */4543 function illegal(token, name, insideTryCatch) {4544 var filename = parse.filename;4545 if (!insideTryCatch)4546 parse.filename = null;4547 return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");4548 }4549 function readString() {4550 var values = [],4551 token;4552 do {4553 /* istanbul ignore if */4554 if ((token = next()) !== "\"" && token !== "'")4555 throw illegal(token);4556 values.push(next());4557 skip(token);4558 token = peek();4559 } while (token === "\"" || token === "'");4560 return values.join("");4561 }4562 function readValue(acceptTypeRef) {4563 var token = next();4564 switch (token) {4565 case "'":4566 case "\"":4567 push(token);4568 return readString();4569 case "true": case "TRUE":4570 return true;4571 case "false": case "FALSE":4572 return false;4573 }4574 try {4575 return parseNumber(token, /* insideTryCatch */ true);4576 } catch (e) {4577 /* istanbul ignore else */4578 if (acceptTypeRef && typeRefRe.test(token))4579 return token;4580 /* istanbul ignore next */4581 throw illegal(token, "value");4582 }4583 }4584 function readRanges(target, acceptStrings) {4585 var token, start;4586 do {4587 if (acceptStrings && ((token = peek()) === "\"" || token === "'"))4588 target.push(readString());4589 else4590 target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]);4591 } while (skip(",", true));4592 skip(";");4593 }4594 function parseNumber(token, insideTryCatch) {4595 var sign = 1;4596 if (token.charAt(0) === "-") {4597 sign = -1;4598 token = token.substring(1);4599 }4600 switch (token) {4601 case "inf": case "INF": case "Inf":4602 return sign * Infinity;4603 case "nan": case "NAN": case "Nan": case "NaN":4604 return NaN;4605 case "0":4606 return 0;4607 }4608 if (base10Re.test(token))4609 return sign * parseInt(token, 10);4610 if (base16Re.test(token))4611 return sign * parseInt(token, 16);4612 if (base8Re.test(token))4613 return sign * parseInt(token, 8);4614 /* istanbul ignore else */4615 if (numberRe.test(token))4616 return sign * parseFloat(token);4617 /* istanbul ignore next */4618 throw illegal(token, "number", insideTryCatch);4619 }4620 function parseId(token, acceptNegative) {4621 switch (token) {4622 case "max": case "MAX": case "Max":4623 return 536870911;4624 case "0":4625 return 0;4626 }4627 /* istanbul ignore if */4628 if (!acceptNegative && token.charAt(0) === "-")4629 throw illegal(token, "id");4630 if (base10NegRe.test(token))4631 return parseInt(token, 10);4632 if (base16NegRe.test(token))4633 return parseInt(token, 16);4634 /* istanbul ignore else */4635 if (base8NegRe.test(token))4636 return parseInt(token, 8);4637 /* istanbul ignore next */4638 throw illegal(token, "id");4639 }4640 function parsePackage() {4641 /* istanbul ignore if */4642 if (pkg !== undefined)4643 throw illegal("package");4644 pkg = next();4645 /* istanbul ignore if */4646 if (!typeRefRe.test(pkg))4647 throw illegal(pkg, "name");4648 ptr = ptr.define(pkg);4649 skip(";");4650 }4651 function parseImport() {4652 var token = peek();4653 var whichImports;4654 switch (token) {4655 case "weak":4656 whichImports = weakImports || (weakImports = []);4657 next();4658 break;4659 case "public":4660 next();4661 // eslint-disable-line no-fallthrough4662 default:4663 whichImports = imports || (imports = []);4664 break;4665 }4666 token = readString();4667 skip(";");4668 whichImports.push(token);4669 }4670 function parseSyntax() {4671 skip("=");4672 syntax = readString();4673 isProto3 = syntax === "proto3";4674 /* istanbul ignore if */4675 if (!isProto3 && syntax !== "proto2")4676 throw illegal(syntax, "syntax");4677 skip(";");4678 }4679 function parseCommon(parent, token) {4680 switch (token) {4681 case "option":4682 parseOption(parent, token);4683 skip(";");4684 return true;4685 case "message":4686 parseType(parent, token);4687 return true;4688 case "enum":4689 parseEnum(parent, token);4690 return true;4691 case "service":4692 parseService(parent, token);4693 return true;4694 case "extend":4695 parseExtension(parent, token);4696 return true;4697 }4698 return false;4699 }4700 function ifBlock(obj, fnIf, fnElse) {4701 var trailingLine = tn.line;4702 if (obj) {4703 obj.comment = cmnt(); // try block-type comment4704 obj.filename = parse.filename;4705 }4706 if (skip("{", true)) {4707 var token;4708 while ((token = next()) !== "}")4709 fnIf(token);4710 skip(";", true);4711 } else {4712 if (fnElse)4713 fnElse();4714 skip(";");4715 if (obj && typeof obj.comment !== "string")4716 obj.comment = cmnt(trailingLine); // try line-type comment if no block4717 }4718 }4719 function parseType(parent, token) {4720 /* istanbul ignore if */4721 if (!nameRe.test(token = next()))4722 throw illegal(token, "type name");4723 var type = new Type(token);4724 ifBlock(type, function parseType_block(token) {4725 if (parseCommon(type, token))4726 return;4727 switch (token) {4728 case "map":4729 parseMapField(type, token);4730 break;4731 case "required":4732 case "optional":4733 case "repeated":4734 parseField(type, token);4735 break;4736 case "oneof":4737 parseOneOf(type, token);4738 break;4739 case "extensions":4740 readRanges(type.extensions || (type.extensions = []));4741 break;4742 case "reserved":4743 readRanges(type.reserved || (type.reserved = []), true);4744 break;4745 default:4746 /* istanbul ignore if */4747 if (!isProto3 || !typeRefRe.test(token))4748 throw illegal(token);4749 push(token);4750 parseField(type, "optional");4751 break;4752 }4753 });4754 parent.add(type);4755 }4756 function parseField(parent, rule, extend) {4757 var type = next();4758 if (type === "group") {4759 parseGroup(parent, rule);4760 return;4761 }4762 /* istanbul ignore if */4763 if (!typeRefRe.test(type))4764 throw illegal(type, "type");4765 var name = next();4766 /* istanbul ignore if */4767 if (!nameRe.test(name))4768 throw illegal(name, "name");4769 name = applyCase(name);4770 skip("=");4771 var field = new Field(name, parseId(next()), type, rule, extend);4772 ifBlock(field, function parseField_block(token) {4773 /* istanbul ignore else */4774 if (token === "option") {4775 parseOption(field, token);4776 skip(";");4777 } else4778 throw illegal(token);4779 }, function parseField_line() {4780 parseInlineOptions(field);4781 });4782 parent.add(field);4783 // JSON defaults to packed=true if not set so we have to set packed=false explicity when4784 // parsing proto2 descriptors without the option, where applicable. This must be done for4785 // all known packable types and anything that could be an enum (= is not a basic type).4786 if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))4787 field.setOption("packed", false, /* ifNotSet */ true);4788 }4789 function parseGroup(parent, rule) {4790 var name = next();4791 /* istanbul ignore if */4792 if (!nameRe.test(name))4793 throw illegal(name, "name");4794 var fieldName = util.lcFirst(name);4795 if (name === fieldName)4796 name = util.ucFirst(name);4797 skip("=");4798 var id = parseId(next());4799 var type = new Type(name);4800 type.group = true;4801 var field = new Field(fieldName, id, name, rule);4802 field.filename = parse.filename;4803 ifBlock(type, function parseGroup_block(token) {4804 switch (token) {4805 case "option":4806 parseOption(type, token);4807 skip(";");4808 break;4809 case "required":4810 case "optional":4811 case "repeated":4812 parseField(type, token);4813 break;4814 /* istanbul ignore next */4815 default:4816 throw illegal(token); // there are no groups with proto3 semantics4817 }4818 });4819 parent.add(type)4820 .add(field);4821 }4822 function parseMapField(parent) {4823 skip("<");4824 var keyType = next();4825 /* istanbul ignore if */4826 if (types.mapKey[keyType] === undefined)4827 throw illegal(keyType, "type");4828 skip(",");4829 var valueType = next();4830 /* istanbul ignore if */4831 if (!typeRefRe.test(valueType))4832 throw illegal(valueType, "type");4833 skip(">");4834 var name = next();4835 /* istanbul ignore if */4836 if (!nameRe.test(name))4837 throw illegal(name, "name");4838 skip("=");4839 var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);4840 ifBlock(field, function parseMapField_block(token) {4841 /* istanbul ignore else */4842 if (token === "option") {4843 parseOption(field, token);4844 skip(";");4845 } else4846 throw illegal(token);4847 }, function parseMapField_line() {4848 parseInlineOptions(field);4849 });4850 parent.add(field);4851 }4852 function parseOneOf(parent, token) {4853 /* istanbul ignore if */4854 if (!nameRe.test(token = next()))4855 throw illegal(token, "name");4856 var oneof = new OneOf(applyCase(token));4857 ifBlock(oneof, function parseOneOf_block(token) {4858 if (token === "option") {4859 parseOption(oneof, token);4860 skip(";");4861 } else {4862 push(token);4863 parseField(oneof, "optional");4864 }4865 });4866 parent.add(oneof);4867 }4868 function parseEnum(parent, token) {4869 /* istanbul ignore if */4870 if (!nameRe.test(token = next()))4871 throw illegal(token, "name");4872 var enm = new Enum(token);4873 ifBlock(enm, function parseEnum_block(token) {4874 switch(token) {4875 case "option":4876 parseOption(enm, token);4877 skip(";");4878 break;4879 case "reserved":4880 readRanges(enm.reserved || (enm.reserved = []), true);4881 break;4882 default:4883 parseEnumValue(enm, token);4884 }4885 });4886 parent.add(enm);4887 }4888 function parseEnumValue(parent, token) {4889 /* istanbul ignore if */4890 if (!nameRe.test(token))4891 throw illegal(token, "name");4892 skip("=");4893 var value = parseId(next(), true),4894 dummy = {};4895 ifBlock(dummy, function parseEnumValue_block(token) {4896 /* istanbul ignore else */4897 if (token === "option") {4898 parseOption(dummy, token); // skip4899 skip(";");4900 } else4901 throw illegal(token);4902 }, function parseEnumValue_line() {4903 parseInlineOptions(dummy); // skip4904 });4905 parent.add(token, value, dummy.comment);4906 }4907 function parseOption(parent, token) {4908 var isCustom = skip("(", true);4909 /* istanbul ignore if */4910 if (!typeRefRe.test(token = next()))4911 throw illegal(token, "name");4912 var name = token;4913 if (isCustom) {4914 skip(")");4915 name = "(" + name + ")";4916 token = peek();4917 if (fqTypeRefRe.test(token)) {4918 name += token;4919 next();4920 }4921 }4922 skip("=");4923 parseOptionValue(parent, name);4924 }4925 function parseOptionValue(parent, name) {4926 if (skip("{", true)) { // { a: "foo" b { c: "bar" } }4927 do {4928 /* istanbul ignore if */4929 if (!nameRe.test(token = next()))4930 throw illegal(token, "name");4931 if (peek() === "{")4932 parseOptionValue(parent, name + "." + token);4933 else {4934 skip(":");4935 if (peek() === "{")4936 parseOptionValue(parent, name + "." + token);4937 else4938 setOption(parent, name + "." + token, readValue(true));4939 }4940 skip(",", true);4941 } while (!skip("}", true));4942 } else4943 setOption(parent, name, readValue(true));4944 // Does not enforce a delimiter to be universal4945 }4946 function setOption(parent, name, value) {4947 if (parent.setOption)4948 parent.setOption(name, value);4949 }4950 function parseInlineOptions(parent) {4951 if (skip("[", true)) {4952 do {4953 parseOption(parent, "option");4954 } while (skip(",", true));4955 skip("]");4956 }4957 return parent;4958 }4959 function parseService(parent, token) {4960 /* istanbul ignore if */4961 if (!nameRe.test(token = next()))4962 throw illegal(token, "service name");4963 var service = new Service(token);4964 ifBlock(service, function parseService_block(token) {4965 if (parseCommon(service, token))4966 return;4967 /* istanbul ignore else */4968 if (token === "rpc")4969 parseMethod(service, token);4970 else4971 throw illegal(token);4972 });4973 parent.add(service);4974 }4975 function parseMethod(parent, token) {4976 var type = token;4977 /* istanbul ignore if */4978 if (!nameRe.test(token = next()))4979 throw illegal(token, "name");4980 var name = token,4981 requestType, requestStream,4982 responseType, responseStream;4983 skip("(");4984 if (skip("stream", true))4985 requestStream = true;4986 /* istanbul ignore if */4987 if (!typeRefRe.test(token = next()))4988 throw illegal(token);4989 requestType = token;4990 skip(")"); skip("returns"); skip("(");4991 if (skip("stream", true))4992 responseStream = true;4993 /* istanbul ignore if */4994 if (!typeRefRe.test(token = next()))4995 throw illegal(token);4996 responseType = token;4997 skip(")");4998 var method = new Method(name, type, requestType, responseType, requestStream, responseStream);4999 ifBlock(method, function parseMethod_block(token) {5000 /* istanbul ignore else */5001 if (token === "option") {5002 parseOption(method, token);5003 skip(";");5004 } else5005 throw illegal(token);5006 });5007 parent.add(method);5008 }5009 function parseExtension(parent, token) {5010 /* istanbul ignore if */5011 if (!typeRefRe.test(token = next()))5012 throw illegal(token, "reference");5013 var reference = token;5014 ifBlock(null, function parseExtension_block(token) {5015 switch (token) {5016 case "required":5017 case "repeated":5018 case "optional":5019 parseField(parent, token, reference);5020 break;5021 default:5022 /* istanbul ignore if */5023 if (!isProto3 || !typeRefRe.test(token))5024 throw illegal(token);5025 push(token);5026 parseField(parent, "optional", reference);5027 break;5028 }5029 });5030 }5031 var token;5032 while ((token = next()) !== null) {5033 switch (token) {5034 case "package":5035 /* istanbul ignore if */5036 if (!head)5037 throw illegal(token);5038 parsePackage();5039 break;5040 case "import":5041 /* istanbul ignore if */5042 if (!head)5043 throw illegal(token);5044 parseImport();5045 break;5046 case "syntax":5047 /* istanbul ignore if */5048 if (!head)5049 throw illegal(token);5050 parseSyntax();5051 break;5052 case "option":5053 /* istanbul ignore if */5054 if (!head)5055 throw illegal(token);5056 parseOption(ptr, token);5057 skip(";");5058 break;5059 default:5060 /* istanbul ignore else */5061 if (parseCommon(ptr, token)) {5062 head = false;5063 continue;5064 }5065 /* istanbul ignore next */5066 throw illegal(token);5067 }5068 }5069 parse.filename = null;5070 return {5071 "package" : pkg,5072 "imports" : imports,5073 weakImports : weakImports,5074 syntax : syntax,5075 root : root5076 };5077}5078/**5079 * Parses the given .proto source and returns an object with the parsed contents.5080 * @name parse5081 * @function5082 * @param {string} source Source contents5083 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.5084 * @returns {IParserResult} Parser result5085 * @property {string} filename=null Currently processing file name for error reporting, if known5086 * @property {IParseOptions} defaults Default {@link IParseOptions}5087 * @variation 25088 */5089},{"./enum":21,"./field":22,"./mapfield":26,"./method":28,"./oneof":31,"./root":35,"./service":39,"./tokenize":40,"./type":41,"./types":42,"./util":43}],33:[function(require,module,exports){5090"use strict";5091module.exports = Reader;5092var util = require("./util/minimal");5093var BufferReader; // cyclic5094var LongBits = util.LongBits,5095 utf8 = util.utf8;5096/* istanbul ignore next */5097function indexOutOfRange(reader, writeLength) {5098 return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);5099}5100/**5101 * Constructs a new reader instance using the specified buffer.5102 * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.5103 * @constructor5104 * @param {Uint8Array} buffer Buffer to read from5105 */5106function Reader(buffer) {5107 /**5108 * Read buffer.5109 * @type {Uint8Array}5110 */5111 this.buf = buffer;5112 /**5113 * Read buffer position.5114 * @type {number}5115 */5116 this.pos = 0;5117 /**5118 * Read buffer length.5119 * @type {number}5120 */5121 this.len = buffer.length;5122}5123var create_array = typeof Uint8Array !== "undefined"5124 ? function create_typed_array(buffer) {5125 if (buffer instanceof Uint8Array || Array.isArray(buffer))5126 return new Reader(buffer);5127 throw Error("illegal buffer");5128 }5129 /* istanbul ignore next */5130 : function create_array(buffer) {5131 if (Array.isArray(buffer))5132 return new Reader(buffer);5133 throw Error("illegal buffer");5134 };5135/**5136 * Creates a new reader using the specified buffer.5137 * @function5138 * @param {Uint8Array|Buffer} buffer Buffer to read from5139 * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}5140 * @throws {Error} If `buffer` is not a valid buffer5141 */5142Reader.create = util.Buffer5143 ? function create_buffer_setup(buffer) {5144 return (Reader.create = function create_buffer(buffer) {5145 return util.Buffer.isBuffer(buffer)5146 ? new BufferReader(buffer)5147 /* istanbul ignore next */5148 : create_array(buffer);5149 })(buffer);5150 }5151 /* istanbul ignore next */5152 : create_array;5153Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;5154/**5155 * Reads a varint as an unsigned 32 bit value.5156 * @function5157 * @returns {number} Value read5158 */5159Reader.prototype.uint32 = (function read_uint32_setup() {5160 var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)5161 return function read_uint32() {5162 value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;5163 value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;5164 value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;5165 value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;5166 value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;5167 /* istanbul ignore if */5168 if ((this.pos += 5) > this.len) {5169 this.pos = this.len;5170 throw indexOutOfRange(this, 10);5171 }5172 return value;5173 };5174})();5175/**5176 * Reads a varint as a signed 32 bit value.5177 * @returns {number} Value read5178 */5179Reader.prototype.int32 = function read_int32() {5180 return this.uint32() | 0;5181};5182/**5183 * Reads a zig-zag encoded varint as a signed 32 bit value.5184 * @returns {number} Value read5185 */5186Reader.prototype.sint32 = function read_sint32() {5187 var value = this.uint32();5188 return value >>> 1 ^ -(value & 1) | 0;5189};5190/* eslint-disable no-invalid-this */5191function readLongVarint() {5192 // tends to deopt with local vars for octet etc.5193 var bits = new LongBits(0, 0);5194 var i = 0;5195 if (this.len - this.pos > 4) { // fast route (lo)5196 for (; i < 4; ++i) {5197 // 1st..4th5198 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;5199 if (this.buf[this.pos++] < 128)5200 return bits;5201 }5202 // 5th5203 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;5204 bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;5205 if (this.buf[this.pos++] < 128)5206 return bits;5207 i = 0;5208 } else {5209 for (; i < 3; ++i) {5210 /* istanbul ignore if */5211 if (this.pos >= this.len)5212 throw indexOutOfRange(this);5213 // 1st..3th5214 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;5215 if (this.buf[this.pos++] < 128)5216 return bits;5217 }5218 // 4th5219 bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;5220 return bits;5221 }5222 if (this.len - this.pos > 4) { // fast route (hi)5223 for (; i < 5; ++i) {5224 // 6th..10th5225 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;5226 if (this.buf[this.pos++] < 128)5227 return bits;5228 }5229 } else {5230 for (; i < 5; ++i) {5231 /* istanbul ignore if */5232 if (this.pos >= this.len)5233 throw indexOutOfRange(this);5234 // 6th..10th5235 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;5236 if (this.buf[this.pos++] < 128)5237 return bits;5238 }5239 }5240 /* istanbul ignore next */5241 throw Error("invalid varint encoding");5242}5243/* eslint-enable no-invalid-this */5244/**5245 * Reads a varint as a signed 64 bit value.5246 * @name Reader#int645247 * @function5248 * @returns {Long} Value read5249 */5250/**5251 * Reads a varint as an unsigned 64 bit value.5252 * @name Reader#uint645253 * @function5254 * @returns {Long} Value read5255 */5256/**5257 * Reads a zig-zag encoded varint as a signed 64 bit value.5258 * @name Reader#sint645259 * @function5260 * @returns {Long} Value read5261 */5262/**5263 * Reads a varint as a boolean.5264 * @returns {boolean} Value read5265 */5266Reader.prototype.bool = function read_bool() {5267 return this.uint32() !== 0;5268};5269function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`5270 return (buf[end - 4]5271 | buf[end - 3] << 85272 | buf[end - 2] << 165273 | buf[end - 1] << 24) >>> 0;5274}5275/**5276 * Reads fixed 32 bits as an unsigned 32 bit integer.5277 * @returns {number} Value read5278 */5279Reader.prototype.fixed32 = function read_fixed32() {5280 /* istanbul ignore if */5281 if (this.pos + 4 > this.len)5282 throw indexOutOfRange(this, 4);5283 return readFixed32_end(this.buf, this.pos += 4);5284};5285/**5286 * Reads fixed 32 bits as a signed 32 bit integer.5287 * @returns {number} Value read5288 */5289Reader.prototype.sfixed32 = function read_sfixed32() {5290 /* istanbul ignore if */5291 if (this.pos + 4 > this.len)5292 throw indexOutOfRange(this, 4);5293 return readFixed32_end(this.buf, this.pos += 4) | 0;5294};5295/* eslint-disable no-invalid-this */5296function readFixed64(/* this: Reader */) {5297 /* istanbul ignore if */5298 if (this.pos + 8 > this.len)5299 throw indexOutOfRange(this, 8);5300 return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));5301}5302/* eslint-enable no-invalid-this */5303/**5304 * Reads fixed 64 bits.5305 * @name Reader#fixed645306 * @function5307 * @returns {Long} Value read5308 */5309/**5310 * Reads zig-zag encoded fixed 64 bits.5311 * @name Reader#sfixed645312 * @function5313 * @returns {Long} Value read5314 */5315/**5316 * Reads a float (32 bit) as a number.5317 * @function5318 * @returns {number} Value read5319 */5320Reader.prototype.float = function read_float() {5321 /* istanbul ignore if */5322 if (this.pos + 4 > this.len)5323 throw indexOutOfRange(this, 4);5324 var value = util.float.readFloatLE(this.buf, this.pos);5325 this.pos += 4;5326 return value;5327};5328/**5329 * Reads a double (64 bit float) as a number.5330 * @function5331 * @returns {number} Value read5332 */5333Reader.prototype.double = function read_double() {5334 /* istanbul ignore if */5335 if (this.pos + 8 > this.len)5336 throw indexOutOfRange(this, 4);5337 var value = util.float.readDoubleLE(this.buf, this.pos);5338 this.pos += 8;5339 return value;5340};5341/**5342 * Reads a sequence of bytes preceeded by its length as a varint.5343 * @returns {Uint8Array} Value read5344 */5345Reader.prototype.bytes = function read_bytes() {5346 var length = this.uint32(),5347 start = this.pos,5348 end = this.pos + length;5349 /* istanbul ignore if */5350 if (end > this.len)5351 throw indexOutOfRange(this, length);5352 this.pos += length;5353 if (Array.isArray(this.buf)) // plain array5354 return this.buf.slice(start, end);5355 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 15356 ? new this.buf.constructor(0)5357 : this._slice.call(this.buf, start, end);5358};5359/**5360 * Reads a string preceeded by its byte length as a varint.5361 * @returns {string} Value read5362 */5363Reader.prototype.string = function read_string() {5364 var bytes = this.bytes();5365 return utf8.read(bytes, 0, bytes.length);5366};5367/**5368 * Skips the specified number of bytes if specified, otherwise skips a varint.5369 * @param {number} [length] Length if known, otherwise a varint is assumed5370 * @returns {Reader} `this`5371 */5372Reader.prototype.skip = function skip(length) {5373 if (typeof length === "number") {5374 /* istanbul ignore if */5375 if (this.pos + length > this.len)5376 throw indexOutOfRange(this, length);5377 this.pos += length;5378 } else {5379 do {5380 /* istanbul ignore if */5381 if (this.pos >= this.len)5382 throw indexOutOfRange(this);5383 } while (this.buf[this.pos++] & 128);5384 }5385 return this;5386};5387/**5388 * Skips the next element of the specified wire type.5389 * @param {number} wireType Wire type received5390 * @returns {Reader} `this`5391 */5392Reader.prototype.skipType = function(wireType) {5393 switch (wireType) {5394 case 0:5395 this.skip();5396 break;5397 case 1:5398 this.skip(8);5399 break;5400 case 2:5401 this.skip(this.uint32());5402 break;5403 case 3:5404 while ((wireType = this.uint32() & 7) !== 4) {5405 this.skipType(wireType);5406 }5407 break;5408 case 5:5409 this.skip(4);5410 break;5411 /* istanbul ignore next */5412 default:5413 throw Error("invalid wire type " + wireType + " at offset " + this.pos);5414 }5415 return this;5416};5417Reader._configure = function(BufferReader_) {5418 BufferReader = BufferReader_;5419 var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";5420 util.merge(Reader.prototype, {5421 int64: function read_int64() {5422 return readLongVarint.call(this)[fn](false);5423 },5424 uint64: function read_uint64() {5425 return readLongVarint.call(this)[fn](true);5426 },5427 sint64: function read_sint64() {5428 return readLongVarint.call(this).zzDecode()[fn](false);5429 },5430 fixed64: function read_fixed64() {5431 return readFixed64.call(this)[fn](true);5432 },5433 sfixed64: function read_sfixed64() {5434 return readFixed64.call(this)[fn](false);5435 }5436 });5437};5438},{"./util/minimal":45}],34:[function(require,module,exports){5439"use strict";5440module.exports = BufferReader;5441// extends Reader5442var Reader = require("./reader");5443(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;5444var util = require("./util/minimal");5445/**5446 * Constructs a new buffer reader instance.5447 * @classdesc Wire format reader using node buffers.5448 * @extends Reader5449 * @constructor5450 * @param {Buffer} buffer Buffer to read from5451 */5452function BufferReader(buffer) {5453 Reader.call(this, buffer);5454 /**5455 * Read buffer.5456 * @name BufferReader#buf5457 * @type {Buffer}5458 */5459}5460/* istanbul ignore else */5461if (util.Buffer)5462 BufferReader.prototype._slice = util.Buffer.prototype.slice;5463/**5464 * @override5465 */5466BufferReader.prototype.string = function read_string_buffer() {5467 var len = this.uint32(); // modifies pos5468 return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));5469};5470/**5471 * Reads a sequence of bytes preceeded by its length as a varint.5472 * @name BufferReader#bytes5473 * @function5474 * @returns {Buffer} Value read5475 */5476},{"./reader":33,"./util/minimal":45}],35:[function(require,module,exports){5477"use strict";5478module.exports = Root;5479// extends Namespace5480var Namespace = require("./namespace");5481((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";5482var Field = require("./field"),5483 Enum = require("./enum"),5484 OneOf = require("./oneof"),5485 util = require("./util");5486var Type, // cyclic5487 parse, // might be excluded5488 common; // "5489/**5490 * Constructs a new root namespace instance.5491 * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.5492 * @extends NamespaceBase5493 * @constructor5494 * @param {Object.<string,*>} [options] Top level options5495 */5496function Root(options) {5497 Namespace.call(this, "", options);5498 /**5499 * Deferred extension fields.5500 * @type {Field[]}5501 */5502 this.deferred = [];5503 /**5504 * Resolved file names of loaded files.5505 * @type {string[]}5506 */5507 this.files = [];5508}5509/**5510 * Loads a namespace descriptor into a root namespace.5511 * @param {INamespace} json Nameespace descriptor5512 * @param {Root} [root] Root namespace, defaults to create a new one if omitted5513 * @returns {Root} Root namespace5514 */5515Root.fromJSON = function fromJSON(json, root) {5516 if (!root)5517 root = new Root();5518 if (json.options)5519 root.setOptions(json.options);5520 return root.addJSON(json.nested);5521};5522/**5523 * Resolves the path of an imported file, relative to the importing origin.5524 * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.5525 * @function5526 * @param {string} origin The file name of the importing file5527 * @param {string} target The file name being imported5528 * @returns {string|null} Resolved path to `target` or `null` to skip the file5529 */5530Root.prototype.resolvePath = util.path.resolve;5531// A symbol-like function to safely signal synchronous loading5532/* istanbul ignore next */5533function SYNC() {} // eslint-disable-line no-empty-function5534/**5535 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.5536 * @param {string|string[]} filename Names of one or multiple files to load5537 * @param {IParseOptions} options Parse options5538 * @param {LoadCallback} callback Callback function5539 * @returns {undefined}5540 */5541Root.prototype.load = function load(filename, options, callback) {5542 if (typeof options === "function") {5543 callback = options;5544 options = undefined;5545 }5546 var self = this;5547 if (!callback)5548 return util.asPromise(load, self, filename, options);5549 var sync = callback === SYNC; // undocumented5550 // Finishes loading by calling the callback (exactly once)5551 function finish(err, root) {5552 /* istanbul ignore if */5553 if (!callback)5554 return;5555 var cb = callback;5556 callback = null;5557 if (sync)5558 throw err;5559 cb(err, root);5560 }5561 // Processes a single file5562 function process(filename, source) {5563 try {5564 if (util.isString(source) && source.charAt(0) === "{")5565 source = JSON.parse(source);5566 if (!util.isString(source))5567 self.setOptions(source.options).addJSON(source.nested);5568 else {5569 parse.filename = filename;5570 var parsed = parse(source, self, options),5571 resolved,5572 i = 0;5573 if (parsed.imports)5574 for (; i < parsed.imports.length; ++i)5575 if (resolved = self.resolvePath(filename, parsed.imports[i]))5576 fetch(resolved);5577 if (parsed.weakImports)5578 for (i = 0; i < parsed.weakImports.length; ++i)5579 if (resolved = self.resolvePath(filename, parsed.weakImports[i]))5580 fetch(resolved, true);5581 }5582 } catch (err) {5583 finish(err);5584 }5585 if (!sync && !queued)5586 finish(null, self); // only once anyway5587 }5588 // Fetches a single file5589 function fetch(filename, weak) {5590 // Strip path if this file references a bundled definition5591 var idx = filename.lastIndexOf("google/protobuf/");5592 if (idx > -1) {5593 var altname = filename.substring(idx);5594 if (altname in common)5595 filename = altname;5596 }5597 // Skip if already loaded / attempted5598 if (self.files.indexOf(filename) > -1)5599 return;5600 self.files.push(filename);5601 // Shortcut bundled definitions5602 if (filename in common) {5603 if (sync)5604 process(filename, common[filename]);5605 else {5606 ++queued;5607 setTimeout(function() {5608 --queued;5609 process(filename, common[filename]);5610 });5611 }5612 return;5613 }5614 // Otherwise fetch from disk or network5615 if (sync) {5616 var source;5617 try {5618 source = util.fs.readFileSync(filename).toString("utf8");5619 } catch (err) {5620 if (!weak)5621 finish(err);5622 return;5623 }5624 process(filename, source);5625 } else {5626 ++queued;5627 util.fetch(filename, function(err, source) {5628 --queued;5629 /* istanbul ignore if */5630 if (!callback)5631 return; // terminated meanwhile5632 if (err) {5633 /* istanbul ignore else */5634 if (!weak)5635 finish(err);5636 else if (!queued) // can't be covered reliably5637 finish(null, self);5638 return;5639 }5640 process(filename, source);5641 });5642 }5643 }5644 var queued = 0;5645 // Assembling the root namespace doesn't require working type5646 // references anymore, so we can load everything in parallel5647 if (util.isString(filename))5648 filename = [ filename ];5649 for (var i = 0, resolved; i < filename.length; ++i)5650 if (resolved = self.resolvePath("", filename[i]))5651 fetch(resolved);5652 if (sync)5653 return self;5654 if (!queued)5655 finish(null, self);5656 return undefined;5657};5658// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined5659/**5660 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.5661 * @function Root#load5662 * @param {string|string[]} filename Names of one or multiple files to load5663 * @param {LoadCallback} callback Callback function5664 * @returns {undefined}5665 * @variation 25666 */5667// function load(filename:string, callback:LoadCallback):undefined5668/**5669 * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.5670 * @function Root#load5671 * @param {string|string[]} filename Names of one or multiple files to load5672 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.5673 * @returns {Promise<Root>} Promise5674 * @variation 35675 */5676// function load(filename:string, [options:IParseOptions]):Promise<Root>5677/**5678 * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).5679 * @function Root#loadSync5680 * @param {string|string[]} filename Names of one or multiple files to load5681 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.5682 * @returns {Root} Root namespace5683 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid5684 */5685Root.prototype.loadSync = function loadSync(filename, options) {5686 if (!util.isNode)5687 throw Error("not supported");5688 return this.load(filename, options, SYNC);5689};5690/**5691 * @override5692 */5693Root.prototype.resolveAll = function resolveAll() {5694 if (this.deferred.length)5695 throw Error("unresolvable extensions: " + this.deferred.map(function(field) {5696 return "'extend " + field.extend + "' in " + field.parent.fullName;5697 }).join(", "));5698 return Namespace.prototype.resolveAll.call(this);5699};5700// only uppercased (and thus conflict-free) children are exposed, see below5701var exposeRe = /^[A-Z]/;5702/**5703 * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.5704 * @param {Root} root Root instance5705 * @param {Field} field Declaring extension field witin the declaring type5706 * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise5707 * @inner5708 * @ignore5709 */5710function tryHandleExtension(root, field) {5711 var extendedType = field.parent.lookup(field.extend);5712 if (extendedType) {5713 var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);5714 sisterField.declaringField = field;5715 field.extensionField = sisterField;5716 extendedType.add(sisterField);5717 return true;5718 }5719 return false;5720}5721/**5722 * Called when any object is added to this root or its sub-namespaces.5723 * @param {ReflectionObject} object Object added5724 * @returns {undefined}5725 * @private5726 */5727Root.prototype._handleAdd = function _handleAdd(object) {5728 if (object instanceof Field) {5729 if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)5730 if (!tryHandleExtension(this, object))5731 this.deferred.push(object);5732 } else if (object instanceof Enum) {5733 if (exposeRe.test(object.name))5734 object.parent[object.name] = object.values; // expose enum values as property of its parent5735 } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {5736 if (object instanceof Type) // Try to handle any deferred extensions5737 for (var i = 0; i < this.deferred.length;)5738 if (tryHandleExtension(this, this.deferred[i]))5739 this.deferred.splice(i, 1);5740 else5741 ++i;5742 for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace5743 this._handleAdd(object._nestedArray[j]);5744 if (exposeRe.test(object.name))5745 object.parent[object.name] = object; // expose namespace as property of its parent5746 }5747 // The above also adds uppercased (and thus conflict-free) nested types, services and enums as5748 // properties of namespaces just like static code does. This allows using a .d.ts generated for5749 // a static module with reflection-based solutions where the condition is met.5750};5751/**5752 * Called when any object is removed from this root or its sub-namespaces.5753 * @param {ReflectionObject} object Object removed5754 * @returns {undefined}5755 * @private5756 */5757Root.prototype._handleRemove = function _handleRemove(object) {5758 if (object instanceof Field) {5759 if (/* an extension field */ object.extend !== undefined) {5760 if (/* already handled */ object.extensionField) { // remove its sister field5761 object.extensionField.parent.remove(object.extensionField);5762 object.extensionField = null;5763 } else { // cancel the extension5764 var index = this.deferred.indexOf(object);5765 /* istanbul ignore else */5766 if (index > -1)5767 this.deferred.splice(index, 1);5768 }5769 }5770 } else if (object instanceof Enum) {5771 if (exposeRe.test(object.name))5772 delete object.parent[object.name]; // unexpose enum values5773 } else if (object instanceof Namespace) {5774 for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace5775 this._handleRemove(object._nestedArray[i]);5776 if (exposeRe.test(object.name))5777 delete object.parent[object.name]; // unexpose namespaces5778 }5779};5780// Sets up cyclic dependencies (called in index-light)5781Root._configure = function(Type_, parse_, common_) {5782 Type = Type_;5783 parse = parse_;5784 common = common_;5785};5786},{"./enum":21,"./field":22,"./namespace":29,"./oneof":31,"./util":43}],36:[function(require,module,exports){5787"use strict";5788module.exports = {};5789/**5790 * Named roots.5791 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).5792 * Can also be used manually to make roots available accross modules.5793 * @name roots5794 * @type {Object.<string,Root>}5795 * @example5796 * // pbjs -r myroot -o compiled.js ...5797 *5798 * // in another module:5799 * require("./compiled.js");5800 *5801 * // in any subsequent module:5802 * var root = protobuf.roots["myroot"];5803 */5804},{}],37:[function(require,module,exports){5805"use strict";5806/**5807 * Streaming RPC helpers.5808 * @namespace5809 */5810var rpc = exports;5811/**5812 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.5813 * @typedef RPCImpl5814 * @type {function}5815 * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called5816 * @param {Uint8Array} requestData Request data5817 * @param {RPCImplCallback} callback Callback function5818 * @returns {undefined}5819 * @example5820 * function rpcImpl(method, requestData, callback) {5821 * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code5822 * throw Error("no such method");5823 * asynchronouslyObtainAResponse(requestData, function(err, responseData) {5824 * callback(err, responseData);5825 * });5826 * }5827 */5828/**5829 * Node-style callback as used by {@link RPCImpl}.5830 * @typedef RPCImplCallback5831 * @type {function}5832 * @param {Error|null} error Error, if any, otherwise `null`5833 * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error5834 * @returns {undefined}5835 */5836rpc.Service = require("./rpc/service");5837},{"./rpc/service":38}],38:[function(require,module,exports){5838"use strict";5839module.exports = Service;5840var util = require("../util/minimal");5841// Extends EventEmitter5842(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;5843/**5844 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.5845 *5846 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.5847 * @typedef rpc.ServiceMethodCallback5848 * @template TRes extends Message<TRes>5849 * @type {function}5850 * @param {Error|null} error Error, if any5851 * @param {TRes} [response] Response message5852 * @returns {undefined}5853 */5854/**5855 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.5856 * @typedef rpc.ServiceMethod5857 * @template TReq extends Message<TReq>5858 * @template TRes extends Message<TRes>5859 * @type {function}5860 * @param {TReq|Properties<TReq>} request Request message or plain object5861 * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message5862 * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`5863 */5864/**5865 * Constructs a new RPC service instance.5866 * @classdesc An RPC service as returned by {@link Service#create}.5867 * @exports rpc.Service5868 * @extends util.EventEmitter5869 * @constructor5870 * @param {RPCImpl} rpcImpl RPC implementation5871 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited5872 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited5873 */5874function Service(rpcImpl, requestDelimited, responseDelimited) {5875 if (typeof rpcImpl !== "function")5876 throw TypeError("rpcImpl must be a function");5877 util.EventEmitter.call(this);5878 /**5879 * RPC implementation. Becomes `null` once the service is ended.5880 * @type {RPCImpl|null}5881 */5882 this.rpcImpl = rpcImpl;5883 /**5884 * Whether requests are length-delimited.5885 * @type {boolean}5886 */5887 this.requestDelimited = Boolean(requestDelimited);5888 /**5889 * Whether responses are length-delimited.5890 * @type {boolean}5891 */5892 this.responseDelimited = Boolean(responseDelimited);5893}5894/**5895 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.5896 * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method5897 * @param {Constructor<TReq>} requestCtor Request constructor5898 * @param {Constructor<TRes>} responseCtor Response constructor5899 * @param {TReq|Properties<TReq>} request Request message or plain object5900 * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback5901 * @returns {undefined}5902 * @template TReq extends Message<TReq>5903 * @template TRes extends Message<TRes>5904 */5905Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {5906 if (!request)5907 throw TypeError("request must be specified");5908 var self = this;5909 if (!callback)5910 return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);5911 if (!self.rpcImpl) {5912 setTimeout(function() { callback(Error("already ended")); }, 0);5913 return undefined;5914 }5915 try {5916 return self.rpcImpl(5917 method,5918 requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),5919 function rpcCallback(err, response) {5920 if (err) {5921 self.emit("error", err, method);5922 return callback(err);5923 }5924 if (response === null) {5925 self.end(/* endedByRPC */ true);5926 return undefined;5927 }5928 if (!(response instanceof responseCtor)) {5929 try {5930 response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);5931 } catch (err) {5932 self.emit("error", err, method);5933 return callback(err);5934 }5935 }5936 self.emit("data", response, method);5937 return callback(null, response);5938 }5939 );5940 } catch (err) {5941 self.emit("error", err, method);5942 setTimeout(function() { callback(err); }, 0);5943 return undefined;5944 }5945};5946/**5947 * Ends this service and emits the `end` event.5948 * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.5949 * @returns {rpc.Service} `this`5950 */5951Service.prototype.end = function end(endedByRPC) {5952 if (this.rpcImpl) {5953 if (!endedByRPC) // signal end to rpcImpl5954 this.rpcImpl(null, null, null);5955 this.rpcImpl = null;5956 this.emit("end").off();5957 }5958 return this;5959};5960},{"../util/minimal":45}],39:[function(require,module,exports){5961"use strict";5962module.exports = Service;5963// extends Namespace5964var Namespace = require("./namespace");5965((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";5966var Method = require("./method"),5967 util = require("./util"),5968 rpc = require("./rpc");5969/**5970 * Constructs a new service instance.5971 * @classdesc Reflected service.5972 * @extends NamespaceBase5973 * @constructor5974 * @param {string} name Service name5975 * @param {Object.<string,*>} [options] Service options5976 * @throws {TypeError} If arguments are invalid5977 */5978function Service(name, options) {5979 Namespace.call(this, name, options);5980 /**5981 * Service methods.5982 * @type {Object.<string,Method>}5983 */5984 this.methods = {}; // toJSON, marker5985 /**5986 * Cached methods as an array.5987 * @type {Method[]|null}5988 * @private5989 */5990 this._methodsArray = null;5991}5992/**5993 * Service descriptor.5994 * @interface IService5995 * @extends INamespace5996 * @property {Object.<string,IMethod>} methods Method descriptors5997 */5998/**5999 * Constructs a service from a service descriptor.6000 * @param {string} name Service name6001 * @param {IService} json Service descriptor6002 * @returns {Service} Created service6003 * @throws {TypeError} If arguments are invalid6004 */6005Service.fromJSON = function fromJSON(name, json) {6006 var service = new Service(name, json.options);6007 /* istanbul ignore else */6008 if (json.methods)6009 for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)6010 service.add(Method.fromJSON(names[i], json.methods[names[i]]));6011 if (json.nested)6012 service.addJSON(json.nested);6013 service.comment = json.comment;6014 return service;6015};6016/**6017 * Converts this service to a service descriptor.6018 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options6019 * @returns {IService} Service descriptor6020 */6021Service.prototype.toJSON = function toJSON(toJSONOptions) {6022 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);6023 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;6024 return util.toObject([6025 "options" , inherited && inherited.options || undefined,6026 "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},6027 "nested" , inherited && inherited.nested || undefined,6028 "comment" , keepComments ? this.comment : undefined6029 ]);6030};6031/**6032 * Methods of this service as an array for iteration.6033 * @name Service#methodsArray6034 * @type {Method[]}6035 * @readonly6036 */6037Object.defineProperty(Service.prototype, "methodsArray", {6038 get: function() {6039 return this._methodsArray || (this._methodsArray = util.toArray(this.methods));6040 }6041});6042function clearCache(service) {6043 service._methodsArray = null;6044 return service;6045}6046/**6047 * @override6048 */6049Service.prototype.get = function get(name) {6050 return this.methods[name]6051 || Namespace.prototype.get.call(this, name);6052};6053/**6054 * @override6055 */6056Service.prototype.resolveAll = function resolveAll() {6057 var methods = this.methodsArray;6058 for (var i = 0; i < methods.length; ++i)6059 methods[i].resolve();6060 return Namespace.prototype.resolve.call(this);6061};6062/**6063 * @override6064 */6065Service.prototype.add = function add(object) {6066 /* istanbul ignore if */6067 if (this.get(object.name))6068 throw Error("duplicate name '" + object.name + "' in " + this);6069 if (object instanceof Method) {6070 this.methods[object.name] = object;6071 object.parent = this;6072 return clearCache(this);6073 }6074 return Namespace.prototype.add.call(this, object);6075};6076/**6077 * @override6078 */6079Service.prototype.remove = function remove(object) {6080 if (object instanceof Method) {6081 /* istanbul ignore if */6082 if (this.methods[object.name] !== object)6083 throw Error(object + " is not a member of " + this);6084 delete this.methods[object.name];6085 object.parent = null;6086 return clearCache(this);6087 }6088 return Namespace.prototype.remove.call(this, object);6089};6090/**6091 * Creates a runtime service using the specified rpc implementation.6092 * @param {RPCImpl} rpcImpl RPC implementation6093 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited6094 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited6095 * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.6096 */6097Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {6098 var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);6099 for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {6100 var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");6101 rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({6102 m: method,6103 q: method.resolvedRequestType.ctor,6104 s: method.resolvedResponseType.ctor6105 });6106 }6107 return rpcService;6108};6109},{"./method":28,"./namespace":29,"./rpc":37,"./util":43}],40:[function(require,module,exports){6110"use strict";6111module.exports = tokenize;6112var delimRe = /[\s{}=;:[\],'"()<>]/g,6113 stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,6114 stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;6115var setCommentRe = /^ *[*/]+ */,6116 setCommentAltRe = /^\s*\*?\/*/,6117 setCommentSplitRe = /\n/g,6118 whitespaceRe = /\s/,6119 unescapeRe = /\\(.?)/g;6120var unescapeMap = {6121 "0": "\0",6122 "r": "\r",6123 "n": "\n",6124 "t": "\t"6125};6126/**6127 * Unescapes a string.6128 * @param {string} str String to unescape6129 * @returns {string} Unescaped string6130 * @property {Object.<string,string>} map Special characters map6131 * @memberof tokenize6132 */6133function unescape(str) {6134 return str.replace(unescapeRe, function($0, $1) {6135 switch ($1) {6136 case "\\":6137 case "":6138 return $1;6139 default:6140 return unescapeMap[$1] || "";6141 }6142 });6143}6144tokenize.unescape = unescape;6145/**6146 * Gets the next token and advances.6147 * @typedef TokenizerHandleNext6148 * @type {function}6149 * @returns {string|null} Next token or `null` on eof6150 */6151/**6152 * Peeks for the next token.6153 * @typedef TokenizerHandlePeek6154 * @type {function}6155 * @returns {string|null} Next token or `null` on eof6156 */6157/**6158 * Pushes a token back to the stack.6159 * @typedef TokenizerHandlePush6160 * @type {function}6161 * @param {string} token Token6162 * @returns {undefined}6163 */6164/**6165 * Skips the next token.6166 * @typedef TokenizerHandleSkip6167 * @type {function}6168 * @param {string} expected Expected token6169 * @param {boolean} [optional=false] If optional6170 * @returns {boolean} Whether the token matched6171 * @throws {Error} If the token didn't match and is not optional6172 */6173/**6174 * Gets the comment on the previous line or, alternatively, the line comment on the specified line.6175 * @typedef TokenizerHandleCmnt6176 * @type {function}6177 * @param {number} [line] Line number6178 * @returns {string|null} Comment text or `null` if none6179 */6180/**6181 * Handle object returned from {@link tokenize}.6182 * @interface ITokenizerHandle6183 * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)6184 * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)6185 * @property {TokenizerHandlePush} push Pushes a token back to the stack6186 * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws6187 * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any6188 * @property {number} line Current line number6189 */6190/**6191 * Tokenizes the given .proto source and returns an object with useful utility functions.6192 * @param {string} source Source contents6193 * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.6194 * @returns {ITokenizerHandle} Tokenizer handle6195 */6196function tokenize(source, alternateCommentMode) {6197 /* eslint-disable callback-return */6198 source = source.toString();6199 var offset = 0,6200 length = source.length,6201 line = 1,6202 commentType = null,6203 commentText = null,6204 commentLine = 0,6205 commentLineEmpty = false;6206 var stack = [];6207 var stringDelim = null;6208 /* istanbul ignore next */6209 /**6210 * Creates an error for illegal syntax.6211 * @param {string} subject Subject6212 * @returns {Error} Error created6213 * @inner6214 */6215 function illegal(subject) {6216 return Error("illegal " + subject + " (line " + line + ")");6217 }6218 /**6219 * Reads a string till its end.6220 * @returns {string} String read6221 * @inner6222 */6223 function readString() {6224 var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;6225 re.lastIndex = offset - 1;6226 var match = re.exec(source);6227 if (!match)6228 throw illegal("string");6229 offset = re.lastIndex;6230 push(stringDelim);6231 stringDelim = null;6232 return unescape(match[1]);6233 }6234 /**6235 * Gets the character at `pos` within the source.6236 * @param {number} pos Position6237 * @returns {string} Character6238 * @inner6239 */6240 function charAt(pos) {6241 return source.charAt(pos);6242 }6243 /**6244 * Sets the current comment text.6245 * @param {number} start Start offset6246 * @param {number} end End offset6247 * @returns {undefined}6248 * @inner6249 */6250 function setComment(start, end) {6251 commentType = source.charAt(start++);6252 commentLine = line;6253 commentLineEmpty = false;6254 var lookback;6255 if (alternateCommentMode) {6256 lookback = 2; // alternate comment parsing: "//" or "/*"6257 } else {6258 lookback = 3; // "///" or "/**"6259 }6260 var commentOffset = start - lookback,6261 c;6262 do {6263 if (--commentOffset < 0 ||6264 (c = source.charAt(commentOffset)) === "\n") {6265 commentLineEmpty = true;6266 break;6267 }6268 } while (c === " " || c === "\t");6269 var lines = source6270 .substring(start, end)6271 .split(setCommentSplitRe);6272 for (var i = 0; i < lines.length; ++i)6273 lines[i] = lines[i]6274 .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "")6275 .trim();6276 commentText = lines6277 .join("\n")6278 .trim();6279 }6280 function isDoubleSlashCommentLine(startOffset) {6281 var endOffset = findEndOfLine(startOffset);6282 // see if remaining line matches comment pattern6283 var lineText = source.substring(startOffset, endOffset);6284 // look for 1 or 2 slashes since startOffset would already point past6285 // the first slash that started the comment.6286 var isComment = /^\s*\/{1,2}/.test(lineText);6287 return isComment;6288 }6289 function findEndOfLine(cursor) {6290 // find end of cursor's line6291 var endOffset = cursor;6292 while (endOffset < length && charAt(endOffset) !== "\n") {6293 endOffset++;6294 }6295 return endOffset;6296 }6297 /**6298 * Obtains the next token.6299 * @returns {string|null} Next token or `null` on eof6300 * @inner6301 */6302 function next() {6303 if (stack.length > 0)6304 return stack.shift();6305 if (stringDelim)6306 return readString();6307 var repeat,6308 prev,6309 curr,6310 start,6311 isDoc;6312 do {6313 if (offset === length)6314 return null;6315 repeat = false;6316 while (whitespaceRe.test(curr = charAt(offset))) {6317 if (curr === "\n")6318 ++line;6319 if (++offset === length)6320 return null;6321 }6322 if (charAt(offset) === "/") {6323 if (++offset === length) {6324 throw illegal("comment");6325 }6326 if (charAt(offset) === "/") { // Line6327 if (!alternateCommentMode) {6328 // check for triple-slash comment6329 isDoc = charAt(start = offset + 1) === "/";6330 while (charAt(++offset) !== "\n") {6331 if (offset === length) {6332 return null;6333 }6334 }6335 ++offset;6336 if (isDoc) {6337 setComment(start, offset - 1);6338 }6339 ++line;6340 repeat = true;6341 } else {6342 // check for double-slash comments, consolidating consecutive lines6343 start = offset;6344 isDoc = false;6345 if (isDoubleSlashCommentLine(offset)) {6346 isDoc = true;6347 do {6348 offset = findEndOfLine(offset);6349 if (offset === length) {6350 break;6351 }6352 offset++;6353 } while (isDoubleSlashCommentLine(offset));6354 } else {6355 offset = Math.min(length, findEndOfLine(offset) + 1);6356 }6357 if (isDoc) {6358 setComment(start, offset);6359 }6360 line++;6361 repeat = true;6362 }6363 } else if ((curr = charAt(offset)) === "*") { /* Block */6364 // check for /** (regular comment mode) or /* (alternate comment mode)6365 start = offset + 1;6366 isDoc = alternateCommentMode || charAt(start) === "*";6367 do {6368 if (curr === "\n") {6369 ++line;6370 }6371 if (++offset === length) {6372 throw illegal("comment");6373 }6374 prev = curr;6375 curr = charAt(offset);6376 } while (prev !== "*" || curr !== "/");6377 ++offset;6378 if (isDoc) {6379 setComment(start, offset - 2);6380 }6381 repeat = true;6382 } else {6383 return "/";6384 }6385 }6386 } while (repeat);6387 // offset !== length if we got here6388 var end = offset;6389 delimRe.lastIndex = 0;6390 var delim = delimRe.test(charAt(end++));6391 if (!delim)6392 while (end < length && !delimRe.test(charAt(end)))6393 ++end;6394 var token = source.substring(offset, offset = end);6395 if (token === "\"" || token === "'")6396 stringDelim = token;6397 return token;6398 }6399 /**6400 * Pushes a token back to the stack.6401 * @param {string} token Token6402 * @returns {undefined}6403 * @inner6404 */6405 function push(token) {6406 stack.push(token);6407 }6408 /**6409 * Peeks for the next token.6410 * @returns {string|null} Token or `null` on eof6411 * @inner6412 */6413 function peek() {6414 if (!stack.length) {6415 var token = next();6416 if (token === null)6417 return null;6418 push(token);6419 }6420 return stack[0];6421 }6422 /**6423 * Skips a token.6424 * @param {string} expected Expected token6425 * @param {boolean} [optional=false] Whether the token is optional6426 * @returns {boolean} `true` when skipped, `false` if not6427 * @throws {Error} When a required token is not present6428 * @inner6429 */6430 function skip(expected, optional) {6431 var actual = peek(),6432 equals = actual === expected;6433 if (equals) {6434 next();6435 return true;6436 }6437 if (!optional)6438 throw illegal("token '" + actual + "', '" + expected + "' expected");6439 return false;6440 }6441 /**6442 * Gets a comment.6443 * @param {number} [trailingLine] Line number if looking for a trailing comment6444 * @returns {string|null} Comment text6445 * @inner6446 */6447 function cmnt(trailingLine) {6448 var ret = null;6449 if (trailingLine === undefined) {6450 if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) {6451 ret = commentText;6452 }6453 } else {6454 /* istanbul ignore else */6455 if (commentLine < trailingLine) {6456 peek();6457 }6458 if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) {6459 ret = commentText;6460 }6461 }6462 return ret;6463 }6464 return Object.defineProperty({6465 next: next,6466 peek: peek,6467 push: push,6468 skip: skip,6469 cmnt: cmnt6470 }, "line", {6471 get: function() { return line; }6472 });6473 /* eslint-enable callback-return */6474}6475},{}],41:[function(require,module,exports){6476"use strict";6477module.exports = Type;6478// extends Namespace6479var Namespace = require("./namespace");6480((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";6481var Enum = require("./enum"),6482 OneOf = require("./oneof"),6483 Field = require("./field"),6484 MapField = require("./mapfield"),6485 Service = require("./service"),6486 Message = require("./message"),6487 Reader = require("./reader"),6488 Writer = require("./writer"),6489 util = require("./util"),6490 encoder = require("./encoder"),6491 decoder = require("./decoder"),6492 verifier = require("./verifier"),6493 converter = require("./converter"),6494 wrappers = require("./wrappers");6495/**6496 * Constructs a new reflected message type instance.6497 * @classdesc Reflected message type.6498 * @extends NamespaceBase6499 * @constructor6500 * @param {string} name Message name6501 * @param {Object.<string,*>} [options] Declared options6502 */6503function Type(name, options) {6504 Namespace.call(this, name, options);6505 /**6506 * Message fields.6507 * @type {Object.<string,Field>}6508 */6509 this.fields = {}; // toJSON, marker6510 /**6511 * Oneofs declared within this namespace, if any.6512 * @type {Object.<string,OneOf>}6513 */6514 this.oneofs = undefined; // toJSON6515 /**6516 * Extension ranges, if any.6517 * @type {number[][]}6518 */6519 this.extensions = undefined; // toJSON6520 /**6521 * Reserved ranges, if any.6522 * @type {Array.<number[]|string>}6523 */6524 this.reserved = undefined; // toJSON6525 /*?6526 * Whether this type is a legacy group.6527 * @type {boolean|undefined}6528 */6529 this.group = undefined; // toJSON6530 /**6531 * Cached fields by id.6532 * @type {Object.<number,Field>|null}6533 * @private6534 */6535 this._fieldsById = null;6536 /**6537 * Cached fields as an array.6538 * @type {Field[]|null}6539 * @private6540 */6541 this._fieldsArray = null;6542 /**6543 * Cached oneofs as an array.6544 * @type {OneOf[]|null}6545 * @private6546 */6547 this._oneofsArray = null;6548 /**6549 * Cached constructor.6550 * @type {Constructor<{}>}6551 * @private6552 */6553 this._ctor = null;6554}6555Object.defineProperties(Type.prototype, {6556 /**6557 * Message fields by id.6558 * @name Type#fieldsById6559 * @type {Object.<number,Field>}6560 * @readonly6561 */6562 fieldsById: {6563 get: function() {6564 /* istanbul ignore if */6565 if (this._fieldsById)6566 return this._fieldsById;6567 this._fieldsById = {};6568 for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {6569 var field = this.fields[names[i]],6570 id = field.id;6571 /* istanbul ignore if */6572 if (this._fieldsById[id])6573 throw Error("duplicate id " + id + " in " + this);6574 this._fieldsById[id] = field;6575 }6576 return this._fieldsById;6577 }6578 },6579 /**6580 * Fields of this message as an array for iteration.6581 * @name Type#fieldsArray6582 * @type {Field[]}6583 * @readonly6584 */6585 fieldsArray: {6586 get: function() {6587 return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));6588 }6589 },6590 /**6591 * Oneofs of this message as an array for iteration.6592 * @name Type#oneofsArray6593 * @type {OneOf[]}6594 * @readonly6595 */6596 oneofsArray: {6597 get: function() {6598 return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));6599 }6600 },6601 /**6602 * The registered constructor, if any registered, otherwise a generic constructor.6603 * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.6604 * @name Type#ctor6605 * @type {Constructor<{}>}6606 */6607 ctor: {6608 get: function() {6609 return this._ctor || (this.ctor = Type.generateConstructor(this)());6610 },6611 set: function(ctor) {6612 // Ensure proper prototype6613 var prototype = ctor.prototype;6614 if (!(prototype instanceof Message)) {6615 (ctor.prototype = new Message()).constructor = ctor;6616 util.merge(ctor.prototype, prototype);6617 }6618 // Classes and messages reference their reflected type6619 ctor.$type = ctor.prototype.$type = this;6620 // Mix in static methods6621 util.merge(ctor, Message, true);6622 this._ctor = ctor;6623 // Messages have non-enumerable default values on their prototype6624 var i = 0;6625 for (; i < /* initializes */ this.fieldsArray.length; ++i)6626 this._fieldsArray[i].resolve(); // ensures a proper value6627 // Messages have non-enumerable getters and setters for each virtual oneof field6628 var ctorProperties = {};6629 for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)6630 ctorProperties[this._oneofsArray[i].resolve().name] = {6631 get: util.oneOfGetter(this._oneofsArray[i].oneof),6632 set: util.oneOfSetter(this._oneofsArray[i].oneof)6633 };6634 if (i)6635 Object.defineProperties(ctor.prototype, ctorProperties);6636 }6637 }6638});6639/**6640 * Generates a constructor function for the specified type.6641 * @param {Type} mtype Message type6642 * @returns {Codegen} Codegen instance6643 */6644Type.generateConstructor = function generateConstructor(mtype) {6645 /* eslint-disable no-unexpected-multiline */6646 var gen = util.codegen(["p"], mtype.name);6647 // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype6648 for (var i = 0, field; i < mtype.fieldsArray.length; ++i)6649 if ((field = mtype._fieldsArray[i]).map) gen6650 ("this%s={}", util.safeProp(field.name));6651 else if (field.repeated) gen6652 ("this%s=[]", util.safeProp(field.name));6653 return gen6654 ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null6655 ("this[ks[i]]=p[ks[i]]");6656 /* eslint-enable no-unexpected-multiline */6657};6658function clearCache(type) {6659 type._fieldsById = type._fieldsArray = type._oneofsArray = null;6660 delete type.encode;6661 delete type.decode;6662 delete type.verify;6663 return type;6664}6665/**6666 * Message type descriptor.6667 * @interface IType6668 * @extends INamespace6669 * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors6670 * @property {Object.<string,IField>} fields Field descriptors6671 * @property {number[][]} [extensions] Extension ranges6672 * @property {number[][]} [reserved] Reserved ranges6673 * @property {boolean} [group=false] Whether a legacy group or not6674 */6675/**6676 * Creates a message type from a message type descriptor.6677 * @param {string} name Message name6678 * @param {IType} json Message type descriptor6679 * @returns {Type} Created message type6680 */6681Type.fromJSON = function fromJSON(name, json) {6682 var type = new Type(name, json.options);6683 type.extensions = json.extensions;6684 type.reserved = json.reserved;6685 var names = Object.keys(json.fields),6686 i = 0;6687 for (; i < names.length; ++i)6688 type.add(6689 ( typeof json.fields[names[i]].keyType !== "undefined"6690 ? MapField.fromJSON6691 : Field.fromJSON )(names[i], json.fields[names[i]])6692 );6693 if (json.oneofs)6694 for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)6695 type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));6696 if (json.nested)6697 for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {6698 var nested = json.nested[names[i]];6699 type.add( // most to least likely6700 ( nested.id !== undefined6701 ? Field.fromJSON6702 : nested.fields !== undefined6703 ? Type.fromJSON6704 : nested.values !== undefined6705 ? Enum.fromJSON6706 : nested.methods !== undefined6707 ? Service.fromJSON6708 : Namespace.fromJSON )(names[i], nested)6709 );6710 }6711 if (json.extensions && json.extensions.length)6712 type.extensions = json.extensions;6713 if (json.reserved && json.reserved.length)6714 type.reserved = json.reserved;6715 if (json.group)6716 type.group = true;6717 if (json.comment)6718 type.comment = json.comment;6719 return type;6720};6721/**6722 * Converts this message type to a message type descriptor.6723 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options6724 * @returns {IType} Message type descriptor6725 */6726Type.prototype.toJSON = function toJSON(toJSONOptions) {6727 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);6728 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;6729 return util.toObject([6730 "options" , inherited && inherited.options || undefined,6731 "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),6732 "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},6733 "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,6734 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,6735 "group" , this.group || undefined,6736 "nested" , inherited && inherited.nested || undefined,6737 "comment" , keepComments ? this.comment : undefined6738 ]);6739};6740/**6741 * @override6742 */6743Type.prototype.resolveAll = function resolveAll() {6744 var fields = this.fieldsArray, i = 0;6745 while (i < fields.length)6746 fields[i++].resolve();6747 var oneofs = this.oneofsArray; i = 0;6748 while (i < oneofs.length)6749 oneofs[i++].resolve();6750 return Namespace.prototype.resolveAll.call(this);6751};6752/**6753 * @override6754 */6755Type.prototype.get = function get(name) {6756 return this.fields[name]6757 || this.oneofs && this.oneofs[name]6758 || this.nested && this.nested[name]6759 || null;6760};6761/**6762 * Adds a nested object to this type.6763 * @param {ReflectionObject} object Nested object to add6764 * @returns {Type} `this`6765 * @throws {TypeError} If arguments are invalid6766 * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id6767 */6768Type.prototype.add = function add(object) {6769 if (this.get(object.name))6770 throw Error("duplicate name '" + object.name + "' in " + this);6771 if (object instanceof Field && object.extend === undefined) {6772 // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.6773 // The root object takes care of adding distinct sister-fields to the respective extended6774 // type instead.6775 // avoids calling the getter if not absolutely necessary because it's called quite frequently6776 if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])6777 throw Error("duplicate id " + object.id + " in " + this);6778 if (this.isReservedId(object.id))6779 throw Error("id " + object.id + " is reserved in " + this);6780 if (this.isReservedName(object.name))6781 throw Error("name '" + object.name + "' is reserved in " + this);6782 if (object.parent)6783 object.parent.remove(object);6784 this.fields[object.name] = object;6785 object.message = this;6786 object.onAdd(this);6787 return clearCache(this);6788 }6789 if (object instanceof OneOf) {6790 if (!this.oneofs)6791 this.oneofs = {};6792 this.oneofs[object.name] = object;6793 object.onAdd(this);6794 return clearCache(this);6795 }6796 return Namespace.prototype.add.call(this, object);6797};6798/**6799 * Removes a nested object from this type.6800 * @param {ReflectionObject} object Nested object to remove6801 * @returns {Type} `this`6802 * @throws {TypeError} If arguments are invalid6803 * @throws {Error} If `object` is not a member of this type6804 */6805Type.prototype.remove = function remove(object) {6806 if (object instanceof Field && object.extend === undefined) {6807 // See Type#add for the reason why extension fields are excluded here.6808 /* istanbul ignore if */6809 if (!this.fields || this.fields[object.name] !== object)6810 throw Error(object + " is not a member of " + this);6811 delete this.fields[object.name];6812 object.parent = null;6813 object.onRemove(this);6814 return clearCache(this);6815 }6816 if (object instanceof OneOf) {6817 /* istanbul ignore if */6818 if (!this.oneofs || this.oneofs[object.name] !== object)6819 throw Error(object + " is not a member of " + this);6820 delete this.oneofs[object.name];6821 object.parent = null;6822 object.onRemove(this);6823 return clearCache(this);6824 }6825 return Namespace.prototype.remove.call(this, object);6826};6827/**6828 * Tests if the specified id is reserved.6829 * @param {number} id Id to test6830 * @returns {boolean} `true` if reserved, otherwise `false`6831 */6832Type.prototype.isReservedId = function isReservedId(id) {6833 return Namespace.isReservedId(this.reserved, id);6834};6835/**6836 * Tests if the specified name is reserved.6837 * @param {string} name Name to test6838 * @returns {boolean} `true` if reserved, otherwise `false`6839 */6840Type.prototype.isReservedName = function isReservedName(name) {6841 return Namespace.isReservedName(this.reserved, name);6842};6843/**6844 * Creates a new message of this type using the specified properties.6845 * @param {Object.<string,*>} [properties] Properties to set6846 * @returns {Message<{}>} Message instance6847 */6848Type.prototype.create = function create(properties) {6849 return new this.ctor(properties);6850};6851/**6852 * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.6853 * @returns {Type} `this`6854 */6855Type.prototype.setup = function setup() {6856 // Sets up everything at once so that the prototype chain does not have to be re-evaluated6857 // multiple times (V8, soft-deopt prototype-check).6858 var fullName = this.fullName,6859 types = [];6860 for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)6861 types.push(this._fieldsArray[i].resolve().resolvedType);6862 // Replace setup methods with type-specific generated functions6863 this.encode = encoder(this)({6864 Writer : Writer,6865 types : types,6866 util : util6867 });6868 this.decode = decoder(this)({6869 Reader : Reader,6870 types : types,6871 util : util6872 });6873 this.verify = verifier(this)({6874 types : types,6875 util : util6876 });6877 this.fromObject = converter.fromObject(this)({6878 types : types,6879 util : util6880 });6881 this.toObject = converter.toObject(this)({6882 types : types,6883 util : util6884 });6885 // Inject custom wrappers for common types6886 var wrapper = wrappers[fullName];6887 if (wrapper) {6888 var originalThis = Object.create(this);6889 // if (wrapper.fromObject) {6890 originalThis.fromObject = this.fromObject;6891 this.fromObject = wrapper.fromObject.bind(originalThis);6892 // }6893 // if (wrapper.toObject) {6894 originalThis.toObject = this.toObject;6895 this.toObject = wrapper.toObject.bind(originalThis);6896 // }6897 }6898 return this;6899};6900/**6901 * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.6902 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object6903 * @param {Writer} [writer] Writer to encode to6904 * @returns {Writer} writer6905 */6906Type.prototype.encode = function encode_setup(message, writer) {6907 return this.setup().encode(message, writer); // overrides this method6908};6909/**6910 * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.6911 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object6912 * @param {Writer} [writer] Writer to encode to6913 * @returns {Writer} writer6914 */6915Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {6916 return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();6917};6918/**6919 * Decodes a message of this type.6920 * @param {Reader|Uint8Array} reader Reader or buffer to decode from6921 * @param {number} [length] Length of the message, if known beforehand6922 * @returns {Message<{}>} Decoded message6923 * @throws {Error} If the payload is not a reader or valid buffer6924 * @throws {util.ProtocolError<{}>} If required fields are missing6925 */6926Type.prototype.decode = function decode_setup(reader, length) {6927 return this.setup().decode(reader, length); // overrides this method6928};6929/**6930 * Decodes a message of this type preceeded by its byte length as a varint.6931 * @param {Reader|Uint8Array} reader Reader or buffer to decode from6932 * @returns {Message<{}>} Decoded message6933 * @throws {Error} If the payload is not a reader or valid buffer6934 * @throws {util.ProtocolError} If required fields are missing6935 */6936Type.prototype.decodeDelimited = function decodeDelimited(reader) {6937 if (!(reader instanceof Reader))6938 reader = Reader.create(reader);6939 return this.decode(reader, reader.uint32());6940};6941/**6942 * Verifies that field values are valid and that required fields are present.6943 * @param {Object.<string,*>} message Plain object to verify6944 * @returns {null|string} `null` if valid, otherwise the reason why it is not6945 */6946Type.prototype.verify = function verify_setup(message) {6947 return this.setup().verify(message); // overrides this method6948};6949/**6950 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.6951 * @param {Object.<string,*>} object Plain object to convert6952 * @returns {Message<{}>} Message instance6953 */6954Type.prototype.fromObject = function fromObject(object) {6955 return this.setup().fromObject(object);6956};6957/**6958 * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.6959 * @interface IConversionOptions6960 * @property {Function} [longs] Long conversion type.6961 * Valid values are `String` and `Number` (the global types).6962 * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.6963 * @property {Function} [enums] Enum value conversion type.6964 * Only valid value is `String` (the global type).6965 * Defaults to copy the present value, which is the numeric id.6966 * @property {Function} [bytes] Bytes value conversion type.6967 * Valid values are `Array` and (a base64 encoded) `String` (the global types).6968 * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.6969 * @property {boolean} [defaults=false] Also sets default values on the resulting object6970 * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`6971 * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`6972 * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any6973 * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings6974 */6975/**6976 * Creates a plain object from a message of this type. Also converts values to other types if specified.6977 * @param {Message<{}>} message Message instance6978 * @param {IConversionOptions} [options] Conversion options6979 * @returns {Object.<string,*>} Plain object6980 */6981Type.prototype.toObject = function toObject(message, options) {6982 return this.setup().toObject(message, options);6983};6984/**6985 * Decorator function as returned by {@link Type.d} (TypeScript).6986 * @typedef TypeDecorator6987 * @type {function}6988 * @param {Constructor<T>} target Target constructor6989 * @returns {undefined}6990 * @template T extends Message<T>6991 */6992/**6993 * Type decorator (TypeScript).6994 * @param {string} [typeName] Type name, defaults to the constructor's name6995 * @returns {TypeDecorator<T>} Decorator function6996 * @template T extends Message<T>6997 */6998Type.d = function decorateType(typeName) {6999 return function typeDecorator(target) {7000 util.decorateType(target, typeName);7001 };7002};7003},{"./converter":18,"./decoder":19,"./encoder":20,"./enum":21,"./field":22,"./mapfield":26,"./message":27,"./namespace":29,"./oneof":31,"./reader":33,"./service":39,"./util":43,"./verifier":46,"./wrappers":47,"./writer":48}],42:[function(require,module,exports){7004"use strict";7005/**7006 * Common type constants.7007 * @namespace7008 */7009var types = exports;7010var util = require("./util");7011var s = [7012 "double", // 07013 "float", // 17014 "int32", // 27015 "uint32", // 37016 "sint32", // 47017 "fixed32", // 57018 "sfixed32", // 67019 "int64", // 77020 "uint64", // 87021 "sint64", // 97022 "fixed64", // 107023 "sfixed64", // 117024 "bool", // 127025 "string", // 137026 "bytes" // 147027];7028function bake(values, offset) {7029 var i = 0, o = {};7030 offset |= 0;7031 while (i < values.length) o[s[i + offset]] = values[i++];7032 return o;7033}7034/**7035 * Basic type wire types.7036 * @type {Object.<string,number>}7037 * @const7038 * @property {number} double=1 Fixed64 wire type7039 * @property {number} float=5 Fixed32 wire type7040 * @property {number} int32=0 Varint wire type7041 * @property {number} uint32=0 Varint wire type7042 * @property {number} sint32=0 Varint wire type7043 * @property {number} fixed32=5 Fixed32 wire type7044 * @property {number} sfixed32=5 Fixed32 wire type7045 * @property {number} int64=0 Varint wire type7046 * @property {number} uint64=0 Varint wire type7047 * @property {number} sint64=0 Varint wire type7048 * @property {number} fixed64=1 Fixed64 wire type7049 * @property {number} sfixed64=1 Fixed64 wire type7050 * @property {number} bool=0 Varint wire type7051 * @property {number} string=2 Ldelim wire type7052 * @property {number} bytes=2 Ldelim wire type7053 */7054types.basic = bake([7055 /* double */ 1,7056 /* float */ 5,7057 /* int32 */ 0,7058 /* uint32 */ 0,7059 /* sint32 */ 0,7060 /* fixed32 */ 5,7061 /* sfixed32 */ 5,7062 /* int64 */ 0,7063 /* uint64 */ 0,7064 /* sint64 */ 0,7065 /* fixed64 */ 1,7066 /* sfixed64 */ 1,7067 /* bool */ 0,7068 /* string */ 2,7069 /* bytes */ 27070]);7071/**7072 * Basic type defaults.7073 * @type {Object.<string,*>}7074 * @const7075 * @property {number} double=0 Double default7076 * @property {number} float=0 Float default7077 * @property {number} int32=0 Int32 default7078 * @property {number} uint32=0 Uint32 default7079 * @property {number} sint32=0 Sint32 default7080 * @property {number} fixed32=0 Fixed32 default7081 * @property {number} sfixed32=0 Sfixed32 default7082 * @property {number} int64=0 Int64 default7083 * @property {number} uint64=0 Uint64 default7084 * @property {number} sint64=0 Sint32 default7085 * @property {number} fixed64=0 Fixed64 default7086 * @property {number} sfixed64=0 Sfixed64 default7087 * @property {boolean} bool=false Bool default7088 * @property {string} string="" String default7089 * @property {Array.<number>} bytes=Array(0) Bytes default7090 * @property {null} message=null Message default7091 */7092types.defaults = bake([7093 /* double */ 0,7094 /* float */ 0,7095 /* int32 */ 0,7096 /* uint32 */ 0,7097 /* sint32 */ 0,7098 /* fixed32 */ 0,7099 /* sfixed32 */ 0,7100 /* int64 */ 0,7101 /* uint64 */ 0,7102 /* sint64 */ 0,7103 /* fixed64 */ 0,7104 /* sfixed64 */ 0,7105 /* bool */ false,7106 /* string */ "",7107 /* bytes */ util.emptyArray,7108 /* message */ null7109]);7110/**7111 * Basic long type wire types.7112 * @type {Object.<string,number>}7113 * @const7114 * @property {number} int64=0 Varint wire type7115 * @property {number} uint64=0 Varint wire type7116 * @property {number} sint64=0 Varint wire type7117 * @property {number} fixed64=1 Fixed64 wire type7118 * @property {number} sfixed64=1 Fixed64 wire type7119 */7120types.long = bake([7121 /* int64 */ 0,7122 /* uint64 */ 0,7123 /* sint64 */ 0,7124 /* fixed64 */ 1,7125 /* sfixed64 */ 17126], 7);7127/**7128 * Allowed types for map keys with their associated wire type.7129 * @type {Object.<string,number>}7130 * @const7131 * @property {number} int32=0 Varint wire type7132 * @property {number} uint32=0 Varint wire type7133 * @property {number} sint32=0 Varint wire type7134 * @property {number} fixed32=5 Fixed32 wire type7135 * @property {number} sfixed32=5 Fixed32 wire type7136 * @property {number} int64=0 Varint wire type7137 * @property {number} uint64=0 Varint wire type7138 * @property {number} sint64=0 Varint wire type7139 * @property {number} fixed64=1 Fixed64 wire type7140 * @property {number} sfixed64=1 Fixed64 wire type7141 * @property {number} bool=0 Varint wire type7142 * @property {number} string=2 Ldelim wire type7143 */7144types.mapKey = bake([7145 /* int32 */ 0,7146 /* uint32 */ 0,7147 /* sint32 */ 0,7148 /* fixed32 */ 5,7149 /* sfixed32 */ 5,7150 /* int64 */ 0,7151 /* uint64 */ 0,7152 /* sint64 */ 0,7153 /* fixed64 */ 1,7154 /* sfixed64 */ 1,7155 /* bool */ 0,7156 /* string */ 27157], 2);7158/**7159 * Allowed types for packed repeated fields with their associated wire type.7160 * @type {Object.<string,number>}7161 * @const7162 * @property {number} double=1 Fixed64 wire type7163 * @property {number} float=5 Fixed32 wire type7164 * @property {number} int32=0 Varint wire type7165 * @property {number} uint32=0 Varint wire type7166 * @property {number} sint32=0 Varint wire type7167 * @property {number} fixed32=5 Fixed32 wire type7168 * @property {number} sfixed32=5 Fixed32 wire type7169 * @property {number} int64=0 Varint wire type7170 * @property {number} uint64=0 Varint wire type7171 * @property {number} sint64=0 Varint wire type7172 * @property {number} fixed64=1 Fixed64 wire type7173 * @property {number} sfixed64=1 Fixed64 wire type7174 * @property {number} bool=0 Varint wire type7175 */7176types.packed = bake([7177 /* double */ 1,7178 /* float */ 5,7179 /* int32 */ 0,7180 /* uint32 */ 0,7181 /* sint32 */ 0,7182 /* fixed32 */ 5,7183 /* sfixed32 */ 5,7184 /* int64 */ 0,7185 /* uint64 */ 0,7186 /* sint64 */ 0,7187 /* fixed64 */ 1,7188 /* sfixed64 */ 1,7189 /* bool */ 07190]);7191},{"./util":43}],43:[function(require,module,exports){7192"use strict";7193/**7194 * Various utility functions.7195 * @namespace7196 */7197var util = module.exports = require("./util/minimal");7198var roots = require("./roots");7199var Type, // cyclic7200 Enum;7201util.codegen = require("@protobufjs/codegen");7202util.fetch = require("@protobufjs/fetch");7203util.path = require("@protobufjs/path");7204/**7205 * Node's fs module if available.7206 * @type {Object.<string,*>}7207 */7208util.fs = util.inquire("fs");7209/**7210 * Converts an object's values to an array.7211 * @param {Object.<string,*>} object Object to convert7212 * @returns {Array.<*>} Converted array7213 */7214util.toArray = function toArray(object) {7215 if (object) {7216 var keys = Object.keys(object),7217 array = new Array(keys.length),7218 index = 0;7219 while (index < keys.length)7220 array[index] = object[keys[index++]];7221 return array;7222 }7223 return [];7224};7225/**7226 * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.7227 * @param {Array.<*>} array Array to convert7228 * @returns {Object.<string,*>} Converted object7229 */7230util.toObject = function toObject(array) {7231 var object = {},7232 index = 0;7233 while (index < array.length) {7234 var key = array[index++],7235 val = array[index++];7236 if (val !== undefined)7237 object[key] = val;7238 }7239 return object;7240};7241var safePropBackslashRe = /\\/g,7242 safePropQuoteRe = /"/g;7243/**7244 * Tests whether the specified name is a reserved word in JS.7245 * @param {string} name Name to test7246 * @returns {boolean} `true` if reserved, otherwise `false`7247 */7248util.isReserved = function isReserved(name) {7249 return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);7250};7251/**7252 * Returns a safe property accessor for the specified property name.7253 * @param {string} prop Property name7254 * @returns {string} Safe accessor7255 */7256util.safeProp = function safeProp(prop) {7257 if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))7258 return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";7259 return "." + prop;7260};7261/**7262 * Converts the first character of a string to upper case.7263 * @param {string} str String to convert7264 * @returns {string} Converted string7265 */7266util.ucFirst = function ucFirst(str) {7267 return str.charAt(0).toUpperCase() + str.substring(1);7268};7269var camelCaseRe = /_([a-z])/g;7270/**7271 * Converts a string to camel case.7272 * @param {string} str String to convert7273 * @returns {string} Converted string7274 */7275util.camelCase = function camelCase(str) {7276 return str.substring(0, 1)7277 + str.substring(1)7278 .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });7279};7280/**7281 * Compares reflected fields by id.7282 * @param {Field} a First field7283 * @param {Field} b Second field7284 * @returns {number} Comparison value7285 */7286util.compareFieldsById = function compareFieldsById(a, b) {7287 return a.id - b.id;7288};7289/**7290 * Decorator helper for types (TypeScript).7291 * @param {Constructor<T>} ctor Constructor function7292 * @param {string} [typeName] Type name, defaults to the constructor's name7293 * @returns {Type} Reflected type7294 * @template T extends Message<T>7295 * @property {Root} root Decorators root7296 */7297util.decorateType = function decorateType(ctor, typeName) {7298 /* istanbul ignore if */7299 if (ctor.$type) {7300 if (typeName && ctor.$type.name !== typeName) {7301 util.decorateRoot.remove(ctor.$type);7302 ctor.$type.name = typeName;7303 util.decorateRoot.add(ctor.$type);7304 }7305 return ctor.$type;7306 }7307 /* istanbul ignore next */7308 if (!Type)7309 Type = require("./type");7310 var type = new Type(typeName || ctor.name);7311 util.decorateRoot.add(type);7312 type.ctor = ctor; // sets up .encode, .decode etc.7313 Object.defineProperty(ctor, "$type", { value: type, enumerable: false });7314 Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });7315 return type;7316};7317var decorateEnumIndex = 0;7318/**7319 * Decorator helper for enums (TypeScript).7320 * @param {Object} object Enum object7321 * @returns {Enum} Reflected enum7322 */7323util.decorateEnum = function decorateEnum(object) {7324 /* istanbul ignore if */7325 if (object.$type)7326 return object.$type;7327 /* istanbul ignore next */7328 if (!Enum)7329 Enum = require("./enum");7330 var enm = new Enum("Enum" + decorateEnumIndex++, object);7331 util.decorateRoot.add(enm);7332 Object.defineProperty(object, "$type", { value: enm, enumerable: false });7333 return enm;7334};7335/**7336 * Decorator root (TypeScript).7337 * @name util.decorateRoot7338 * @type {Root}7339 * @readonly7340 */7341Object.defineProperty(util, "decorateRoot", {7342 get: function() {7343 return roots["decorated"] || (roots["decorated"] = new (require("./root"))());7344 }7345});7346},{"./enum":21,"./root":35,"./roots":36,"./type":41,"./util/minimal":45,"@protobufjs/codegen":7,"@protobufjs/fetch":9,"@protobufjs/path":12}],44:[function(require,module,exports){7347"use strict";7348module.exports = LongBits;7349var util = require("../util/minimal");7350/**7351 * Constructs new long bits.7352 * @classdesc Helper class for working with the low and high bits of a 64 bit value.7353 * @memberof util7354 * @constructor7355 * @param {number} lo Low 32 bits, unsigned7356 * @param {number} hi High 32 bits, unsigned7357 */7358function LongBits(lo, hi) {7359 // note that the casts below are theoretically unnecessary as of today, but older statically7360 // generated converter code might still call the ctor with signed 32bits. kept for compat.7361 /**7362 * Low bits.7363 * @type {number}7364 */7365 this.lo = lo >>> 0;7366 /**7367 * High bits.7368 * @type {number}7369 */7370 this.hi = hi >>> 0;7371}7372/**7373 * Zero bits.7374 * @memberof util.LongBits7375 * @type {util.LongBits}7376 */7377var zero = LongBits.zero = new LongBits(0, 0);7378zero.toNumber = function() { return 0; };7379zero.zzEncode = zero.zzDecode = function() { return this; };7380zero.length = function() { return 1; };7381/**7382 * Zero hash.7383 * @memberof util.LongBits7384 * @type {string}7385 */7386var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";7387/**7388 * Constructs new long bits from the specified number.7389 * @param {number} value Value7390 * @returns {util.LongBits} Instance7391 */7392LongBits.fromNumber = function fromNumber(value) {7393 if (value === 0)7394 return zero;7395 var sign = value < 0;7396 if (sign)7397 value = -value;7398 var lo = value >>> 0,7399 hi = (value - lo) / 4294967296 >>> 0;7400 if (sign) {7401 hi = ~hi >>> 0;7402 lo = ~lo >>> 0;7403 if (++lo > 4294967295) {7404 lo = 0;7405 if (++hi > 4294967295)7406 hi = 0;7407 }7408 }7409 return new LongBits(lo, hi);7410};7411/**7412 * Constructs new long bits from a number, long or string.7413 * @param {Long|number|string} value Value7414 * @returns {util.LongBits} Instance7415 */7416LongBits.from = function from(value) {7417 if (typeof value === "number")7418 return LongBits.fromNumber(value);7419 if (util.isString(value)) {7420 /* istanbul ignore else */7421 if (util.Long)7422 value = util.Long.fromString(value);7423 else7424 return LongBits.fromNumber(parseInt(value, 10));7425 }7426 return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;7427};7428/**7429 * Converts this long bits to a possibly unsafe JavaScript number.7430 * @param {boolean} [unsigned=false] Whether unsigned or not7431 * @returns {number} Possibly unsafe number7432 */7433LongBits.prototype.toNumber = function toNumber(unsigned) {7434 if (!unsigned && this.hi >>> 31) {7435 var lo = ~this.lo + 1 >>> 0,7436 hi = ~this.hi >>> 0;7437 if (!lo)7438 hi = hi + 1 >>> 0;7439 return -(lo + hi * 4294967296);7440 }7441 return this.lo + this.hi * 4294967296;7442};7443/**7444 * Converts this long bits to a long.7445 * @param {boolean} [unsigned=false] Whether unsigned or not7446 * @returns {Long} Long7447 */7448LongBits.prototype.toLong = function toLong(unsigned) {7449 return util.Long7450 ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))7451 /* istanbul ignore next */7452 : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };7453};7454var charCodeAt = String.prototype.charCodeAt;7455/**7456 * Constructs new long bits from the specified 8 characters long hash.7457 * @param {string} hash Hash7458 * @returns {util.LongBits} Bits7459 */7460LongBits.fromHash = function fromHash(hash) {7461 if (hash === zeroHash)7462 return zero;7463 return new LongBits(7464 ( charCodeAt.call(hash, 0)7465 | charCodeAt.call(hash, 1) << 87466 | charCodeAt.call(hash, 2) << 167467 | charCodeAt.call(hash, 3) << 24) >>> 07468 ,7469 ( charCodeAt.call(hash, 4)7470 | charCodeAt.call(hash, 5) << 87471 | charCodeAt.call(hash, 6) << 167472 | charCodeAt.call(hash, 7) << 24) >>> 07473 );7474};7475/**7476 * Converts this long bits to a 8 characters long hash.7477 * @returns {string} Hash7478 */7479LongBits.prototype.toHash = function toHash() {7480 return String.fromCharCode(7481 this.lo & 255,7482 this.lo >>> 8 & 255,7483 this.lo >>> 16 & 255,7484 this.lo >>> 24 ,7485 this.hi & 255,7486 this.hi >>> 8 & 255,7487 this.hi >>> 16 & 255,7488 this.hi >>> 247489 );7490};7491/**7492 * Zig-zag encodes this long bits.7493 * @returns {util.LongBits} `this`7494 */7495LongBits.prototype.zzEncode = function zzEncode() {7496 var mask = this.hi >> 31;7497 this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;7498 this.lo = ( this.lo << 1 ^ mask) >>> 0;7499 return this;7500};7501/**7502 * Zig-zag decodes this long bits.7503 * @returns {util.LongBits} `this`7504 */7505LongBits.prototype.zzDecode = function zzDecode() {7506 var mask = -(this.lo & 1);7507 this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;7508 this.hi = ( this.hi >>> 1 ^ mask) >>> 0;7509 return this;7510};7511/**7512 * Calculates the length of this longbits when encoded as a varint.7513 * @returns {number} Length7514 */7515LongBits.prototype.length = function length() {7516 var part0 = this.lo,7517 part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,7518 part2 = this.hi >>> 24;7519 return part2 === 07520 ? part1 === 07521 ? part0 < 163847522 ? part0 < 128 ? 1 : 27523 : part0 < 2097152 ? 3 : 47524 : part1 < 163847525 ? part1 < 128 ? 5 : 67526 : part1 < 2097152 ? 7 : 87527 : part2 < 128 ? 9 : 10;7528};7529},{"../util/minimal":45}],45:[function(require,module,exports){7530(function (global){7531"use strict";7532var util = exports;7533// used to return a Promise where callback is omitted7534util.asPromise = require("@protobufjs/aspromise");7535// converts to / from base64 encoded strings7536util.base64 = require("@protobufjs/base64");7537// base class of rpc.Service7538util.EventEmitter = require("@protobufjs/eventemitter");7539// float handling accross browsers7540util.float = require("@protobufjs/float");7541// requires modules optionally and hides the call from bundlers7542util.inquire = require("@protobufjs/inquire");7543// converts to / from utf8 encoded strings7544util.utf8 = require("@protobufjs/utf8");7545// provides a node-like buffer pool in the browser7546util.pool = require("@protobufjs/pool");7547// utility to work with the low and high bits of a 64 bit value7548util.LongBits = require("./longbits");7549// global object reference7550util.global = typeof window !== "undefined" && window7551 || typeof global !== "undefined" && global7552 || typeof self !== "undefined" && self7553 || this; // eslint-disable-line no-invalid-this7554/**7555 * An immuable empty array.7556 * @memberof util7557 * @type {Array.<*>}7558 * @const7559 */7560util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes7561/**7562 * An immutable empty object.7563 * @type {Object}7564 * @const7565 */7566util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes7567/**7568 * Whether running within node or not.7569 * @memberof util7570 * @type {boolean}7571 * @const7572 */7573util.isNode = Boolean(util.global.process && util.global.process.versions && util.global.process.versions.node);7574/**7575 * Tests if the specified value is an integer.7576 * @function7577 * @param {*} value Value to test7578 * @returns {boolean} `true` if the value is an integer7579 */7580util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {7581 return typeof value === "number" && isFinite(value) && Math.floor(value) === value;7582};7583/**7584 * Tests if the specified value is a string.7585 * @param {*} value Value to test7586 * @returns {boolean} `true` if the value is a string7587 */7588util.isString = function isString(value) {7589 return typeof value === "string" || value instanceof String;7590};7591/**7592 * Tests if the specified value is a non-null object.7593 * @param {*} value Value to test7594 * @returns {boolean} `true` if the value is a non-null object7595 */7596util.isObject = function isObject(value) {7597 return value && typeof value === "object";7598};7599/**7600 * Checks if a property on a message is considered to be present.7601 * This is an alias of {@link util.isSet}.7602 * @function7603 * @param {Object} obj Plain object or message instance7604 * @param {string} prop Property name7605 * @returns {boolean} `true` if considered to be present, otherwise `false`7606 */7607util.isset =7608/**7609 * Checks if a property on a message is considered to be present.7610 * @param {Object} obj Plain object or message instance7611 * @param {string} prop Property name7612 * @returns {boolean} `true` if considered to be present, otherwise `false`7613 */7614util.isSet = function isSet(obj, prop) {7615 var value = obj[prop];7616 if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins7617 return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;7618 return false;7619};7620/**7621 * Any compatible Buffer instance.7622 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.7623 * @interface Buffer7624 * @extends Uint8Array7625 */7626/**7627 * Node's Buffer class if available.7628 * @type {Constructor<Buffer>}7629 */7630util.Buffer = (function() {7631 try {7632 var Buffer = util.inquire("buffer").Buffer;7633 // refuse to use non-node buffers if not explicitly assigned (perf reasons):7634 return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;7635 } catch (e) {7636 /* istanbul ignore next */7637 return null;7638 }7639})();7640// Internal alias of or polyfull for Buffer.from.7641util._Buffer_from = null;7642// Internal alias of or polyfill for Buffer.allocUnsafe.7643util._Buffer_allocUnsafe = null;7644/**7645 * Creates a new buffer of whatever type supported by the environment.7646 * @param {number|number[]} [sizeOrArray=0] Buffer size or number array7647 * @returns {Uint8Array|Buffer} Buffer7648 */7649util.newBuffer = function newBuffer(sizeOrArray) {7650 /* istanbul ignore next */7651 return typeof sizeOrArray === "number"7652 ? util.Buffer7653 ? util._Buffer_allocUnsafe(sizeOrArray)7654 : new util.Array(sizeOrArray)7655 : util.Buffer7656 ? util._Buffer_from(sizeOrArray)7657 : typeof Uint8Array === "undefined"7658 ? sizeOrArray7659 : new Uint8Array(sizeOrArray);7660};7661/**7662 * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.7663 * @type {Constructor<Uint8Array>}7664 */7665util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;7666/**7667 * Any compatible Long instance.7668 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.7669 * @interface Long7670 * @property {number} low Low bits7671 * @property {number} high High bits7672 * @property {boolean} unsigned Whether unsigned or not7673 */7674/**7675 * Long.js's Long class if available.7676 * @type {Constructor<Long>}7677 */7678util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long7679 || /* istanbul ignore next */ util.global.Long7680 || util.inquire("long");7681/**7682 * Regular expression used to verify 2 bit (`bool`) map keys.7683 * @type {RegExp}7684 * @const7685 */7686util.key2Re = /^true|false|0|1$/;7687/**7688 * Regular expression used to verify 32 bit (`int32` etc.) map keys.7689 * @type {RegExp}7690 * @const7691 */7692util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;7693/**7694 * Regular expression used to verify 64 bit (`int64` etc.) map keys.7695 * @type {RegExp}7696 * @const7697 */7698util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;7699/**7700 * Converts a number or long to an 8 characters long hash string.7701 * @param {Long|number} value Value to convert7702 * @returns {string} Hash7703 */7704util.longToHash = function longToHash(value) {7705 return value7706 ? util.LongBits.from(value).toHash()7707 : util.LongBits.zeroHash;7708};7709/**7710 * Converts an 8 characters long hash string to a long or number.7711 * @param {string} hash Hash7712 * @param {boolean} [unsigned=false] Whether unsigned or not7713 * @returns {Long|number} Original value7714 */7715util.longFromHash = function longFromHash(hash, unsigned) {7716 var bits = util.LongBits.fromHash(hash);7717 if (util.Long)7718 return util.Long.fromBits(bits.lo, bits.hi, unsigned);7719 return bits.toNumber(Boolean(unsigned));7720};7721/**7722 * Merges the properties of the source object into the destination object.7723 * @memberof util7724 * @param {Object.<string,*>} dst Destination object7725 * @param {Object.<string,*>} src Source object7726 * @param {boolean} [ifNotSet=false] Merges only if the key is not already set7727 * @returns {Object.<string,*>} Destination object7728 */7729function merge(dst, src, ifNotSet) { // used by converters7730 for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)7731 if (dst[keys[i]] === undefined || !ifNotSet)7732 dst[keys[i]] = src[keys[i]];7733 return dst;7734}7735util.merge = merge;7736/**7737 * Converts the first character of a string to lower case.7738 * @param {string} str String to convert7739 * @returns {string} Converted string7740 */7741util.lcFirst = function lcFirst(str) {7742 return str.charAt(0).toLowerCase() + str.substring(1);7743};7744/**7745 * Creates a custom error constructor.7746 * @memberof util7747 * @param {string} name Error name7748 * @returns {Constructor<Error>} Custom error constructor7749 */7750function newError(name) {7751 function CustomError(message, properties) {7752 if (!(this instanceof CustomError))7753 return new CustomError(message, properties);7754 // Error.call(this, message);7755 // ^ just returns a new error instance because the ctor can be called as a function7756 Object.defineProperty(this, "message", { get: function() { return message; } });7757 /* istanbul ignore next */7758 if (Error.captureStackTrace) // node7759 Error.captureStackTrace(this, CustomError);7760 else7761 Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });7762 if (properties)7763 merge(this, properties);7764 }7765 (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;7766 Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });7767 CustomError.prototype.toString = function toString() {7768 return this.name + ": " + this.message;7769 };7770 return CustomError;7771}7772util.newError = newError;7773/**7774 * Constructs a new protocol error.7775 * @classdesc Error subclass indicating a protocol specifc error.7776 * @memberof util7777 * @extends Error7778 * @template T extends Message<T>7779 * @constructor7780 * @param {string} message Error message7781 * @param {Object.<string,*>} [properties] Additional properties7782 * @example7783 * try {7784 * MyMessage.decode(someBuffer); // throws if required fields are missing7785 * } catch (e) {7786 * if (e instanceof ProtocolError && e.instance)7787 * console.log("decoded so far: " + JSON.stringify(e.instance));7788 * }7789 */7790util.ProtocolError = newError("ProtocolError");7791/**7792 * So far decoded message instance.7793 * @name util.ProtocolError#instance7794 * @type {Message<T>}7795 */7796/**7797 * A OneOf getter as returned by {@link util.oneOfGetter}.7798 * @typedef OneOfGetter7799 * @type {function}7800 * @returns {string|undefined} Set field name, if any7801 */7802/**7803 * Builds a getter for a oneof's present field name.7804 * @param {string[]} fieldNames Field names7805 * @returns {OneOfGetter} Unbound getter7806 */7807util.oneOfGetter = function getOneOf(fieldNames) {7808 var fieldMap = {};7809 for (var i = 0; i < fieldNames.length; ++i)7810 fieldMap[fieldNames[i]] = 1;7811 /**7812 * @returns {string|undefined} Set field name, if any7813 * @this Object7814 * @ignore7815 */7816 return function() { // eslint-disable-line consistent-return7817 for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)7818 if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)7819 return keys[i];7820 };7821};7822/**7823 * A OneOf setter as returned by {@link util.oneOfSetter}.7824 * @typedef OneOfSetter7825 * @type {function}7826 * @param {string|undefined} value Field name7827 * @returns {undefined}7828 */7829/**7830 * Builds a setter for a oneof's present field name.7831 * @param {string[]} fieldNames Field names7832 * @returns {OneOfSetter} Unbound setter7833 */7834util.oneOfSetter = function setOneOf(fieldNames) {7835 /**7836 * @param {string} name Field name7837 * @returns {undefined}7838 * @this Object7839 * @ignore7840 */7841 return function(name) {7842 for (var i = 0; i < fieldNames.length; ++i)7843 if (fieldNames[i] !== name)7844 delete this[fieldNames[i]];7845 };7846};7847/**7848 * Default conversion options used for {@link Message#toJSON} implementations.7849 *7850 * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:7851 *7852 * - Longs become strings7853 * - Enums become string keys7854 * - Bytes become base64 encoded strings7855 * - (Sub-)Messages become plain objects7856 * - Maps become plain objects with all string keys7857 * - Repeated fields become arrays7858 * - NaN and Infinity for float and double fields become strings7859 *7860 * @type {IConversionOptions}7861 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json7862 */7863util.toJSONOptions = {7864 longs: String,7865 enums: String,7866 bytes: String,7867 json: true7868};7869// Sets up buffer utility according to the environment (called in index-minimal)7870util._configure = function() {7871 var Buffer = util.Buffer;7872 /* istanbul ignore if */7873 if (!Buffer) {7874 util._Buffer_from = util._Buffer_allocUnsafe = null;7875 return;7876 }7877 // because node 4.x buffers are incompatible & immutable7878 // see: https://github.com/dcodeIO/protobuf.js/pull/6657879 util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||7880 /* istanbul ignore next */7881 function Buffer_from(value, encoding) {7882 return new Buffer(value, encoding);7883 };7884 util._Buffer_allocUnsafe = Buffer.allocUnsafe ||7885 /* istanbul ignore next */7886 function Buffer_allocUnsafe(size) {7887 return new Buffer(size);7888 };7889};7890}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})7891},{"./longbits":44,"@protobufjs/aspromise":5,"@protobufjs/base64":6,"@protobufjs/eventemitter":8,"@protobufjs/float":10,"@protobufjs/inquire":11,"@protobufjs/pool":13,"@protobufjs/utf8":14}],46:[function(require,module,exports){7892"use strict";7893module.exports = verifier;7894var Enum = require("./enum"),7895 util = require("./util");7896function invalid(field, expected) {7897 return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";7898}7899/**7900 * Generates a partial value verifier.7901 * @param {Codegen} gen Codegen instance7902 * @param {Field} field Reflected field7903 * @param {number} fieldIndex Field index7904 * @param {string} ref Variable reference7905 * @returns {Codegen} Codegen instance7906 * @ignore7907 */7908function genVerifyValue(gen, field, fieldIndex, ref) {7909 /* eslint-disable no-unexpected-multiline */7910 if (field.resolvedType) {7911 if (field.resolvedType instanceof Enum) { gen7912 ("switch(%s){", ref)7913 ("default:")7914 ("return%j", invalid(field, "enum value"));7915 for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen7916 ("case %i:", field.resolvedType.values[keys[j]]);7917 gen7918 ("break")7919 ("}");7920 } else {7921 gen7922 ("{")7923 ("var e=types[%i].verify(%s);", fieldIndex, ref)7924 ("if(e)")7925 ("return%j+e", field.name + ".")7926 ("}");7927 }7928 } else {7929 switch (field.type) {7930 case "int32":7931 case "uint32":7932 case "sint32":7933 case "fixed32":7934 case "sfixed32": gen7935 ("if(!util.isInteger(%s))", ref)7936 ("return%j", invalid(field, "integer"));7937 break;7938 case "int64":7939 case "uint64":7940 case "sint64":7941 case "fixed64":7942 case "sfixed64": gen7943 ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)7944 ("return%j", invalid(field, "integer|Long"));7945 break;7946 case "float":7947 case "double": gen7948 ("if(typeof %s!==\"number\")", ref)7949 ("return%j", invalid(field, "number"));7950 break;7951 case "bool": gen7952 ("if(typeof %s!==\"boolean\")", ref)7953 ("return%j", invalid(field, "boolean"));7954 break;7955 case "string": gen7956 ("if(!util.isString(%s))", ref)7957 ("return%j", invalid(field, "string"));7958 break;7959 case "bytes": gen7960 ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)7961 ("return%j", invalid(field, "buffer"));7962 break;7963 }7964 }7965 return gen;7966 /* eslint-enable no-unexpected-multiline */7967}7968/**7969 * Generates a partial key verifier.7970 * @param {Codegen} gen Codegen instance7971 * @param {Field} field Reflected field7972 * @param {string} ref Variable reference7973 * @returns {Codegen} Codegen instance7974 * @ignore7975 */7976function genVerifyKey(gen, field, ref) {7977 /* eslint-disable no-unexpected-multiline */7978 switch (field.keyType) {7979 case "int32":7980 case "uint32":7981 case "sint32":7982 case "fixed32":7983 case "sfixed32": gen7984 ("if(!util.key32Re.test(%s))", ref)7985 ("return%j", invalid(field, "integer key"));7986 break;7987 case "int64":7988 case "uint64":7989 case "sint64":7990 case "fixed64":7991 case "sfixed64": gen7992 ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not7993 ("return%j", invalid(field, "integer|Long key"));7994 break;7995 case "bool": gen7996 ("if(!util.key2Re.test(%s))", ref)7997 ("return%j", invalid(field, "boolean key"));7998 break;7999 }8000 return gen;8001 /* eslint-enable no-unexpected-multiline */8002}8003/**8004 * Generates a verifier specific to the specified message type.8005 * @param {Type} mtype Message type8006 * @returns {Codegen} Codegen instance8007 */8008function verifier(mtype) {8009 /* eslint-disable no-unexpected-multiline */8010 var gen = util.codegen(["m"], mtype.name + "$verify")8011 ("if(typeof m!==\"object\"||m===null)")8012 ("return%j", "object expected");8013 var oneofs = mtype.oneofsArray,8014 seenFirstField = {};8015 if (oneofs.length) gen8016 ("var p={}");8017 for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {8018 var field = mtype._fieldsArray[i].resolve(),8019 ref = "m" + util.safeProp(field.name);8020 if (field.optional) gen8021 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null8022 // map fields8023 if (field.map) { gen8024 ("if(!util.isObject(%s))", ref)8025 ("return%j", invalid(field, "object"))8026 ("var k=Object.keys(%s)", ref)8027 ("for(var i=0;i<k.length;++i){");8028 genVerifyKey(gen, field, "k[i]");8029 genVerifyValue(gen, field, i, ref + "[k[i]]")8030 ("}");8031 // repeated fields8032 } else if (field.repeated) { gen8033 ("if(!Array.isArray(%s))", ref)8034 ("return%j", invalid(field, "array"))8035 ("for(var i=0;i<%s.length;++i){", ref);8036 genVerifyValue(gen, field, i, ref + "[i]")8037 ("}");8038 // required or present fields8039 } else {8040 if (field.partOf) {8041 var oneofProp = util.safeProp(field.partOf.name);8042 if (seenFirstField[field.partOf.name] === 1) gen8043 ("if(p%s===1)", oneofProp)8044 ("return%j", field.partOf.name + ": multiple values");8045 seenFirstField[field.partOf.name] = 1;8046 gen8047 ("p%s=1", oneofProp);8048 }8049 genVerifyValue(gen, field, i, ref);8050 }8051 if (field.optional) gen8052 ("}");8053 }8054 return gen8055 ("return null");8056 /* eslint-enable no-unexpected-multiline */8057}8058},{"./enum":21,"./util":43}],47:[function(require,module,exports){8059"use strict";8060/**8061 * Wrappers for common types.8062 * @type {Object.<string,IWrapper>}8063 * @const8064 */8065var wrappers = exports;8066var Message = require("./message");8067/**8068 * From object converter part of an {@link IWrapper}.8069 * @typedef WrapperFromObjectConverter8070 * @type {function}8071 * @param {Object.<string,*>} object Plain object8072 * @returns {Message<{}>} Message instance8073 * @this Type8074 */8075/**8076 * To object converter part of an {@link IWrapper}.8077 * @typedef WrapperToObjectConverter8078 * @type {function}8079 * @param {Message<{}>} message Message instance8080 * @param {IConversionOptions} [options] Conversion options8081 * @returns {Object.<string,*>} Plain object8082 * @this Type8083 */8084/**8085 * Common type wrapper part of {@link wrappers}.8086 * @interface IWrapper8087 * @property {WrapperFromObjectConverter} [fromObject] From object converter8088 * @property {WrapperToObjectConverter} [toObject] To object converter8089 */8090// Custom wrapper for Any8091wrappers[".google.protobuf.Any"] = {8092 fromObject: function(object) {8093 // unwrap value type if mapped8094 if (object && object["@type"]) {8095 var type = this.lookup(object["@type"]);8096 /* istanbul ignore else */8097 if (type) {8098 // type_url does not accept leading "."8099 var type_url = object["@type"].charAt(0) === "." ?8100 object["@type"].substr(1) : object["@type"];8101 // type_url prefix is optional, but path seperator is required8102 return this.create({8103 type_url: "/" + type_url,8104 value: type.encode(type.fromObject(object)).finish()8105 });8106 }8107 }8108 return this.fromObject(object);8109 },8110 toObject: function(message, options) {8111 // decode value if requested and unmapped8112 if (options && options.json && message.type_url && message.value) {8113 // Only use fully qualified type name after the last '/'8114 var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);8115 var type = this.lookup(name);8116 /* istanbul ignore else */8117 if (type)8118 message = type.decode(message.value);8119 }8120 // wrap value if unmapped8121 if (!(message instanceof this.ctor) && message instanceof Message) {8122 var object = message.$type.toObject(message, options);8123 object["@type"] = message.$type.fullName;8124 return object;8125 }8126 return this.toObject(message, options);8127 }8128};8129},{"./message":27}],48:[function(require,module,exports){8130"use strict";8131module.exports = Writer;8132var util = require("./util/minimal");8133var BufferWriter; // cyclic8134var LongBits = util.LongBits,8135 base64 = util.base64,8136 utf8 = util.utf8;8137/**8138 * Constructs a new writer operation instance.8139 * @classdesc Scheduled writer operation.8140 * @constructor8141 * @param {function(*, Uint8Array, number)} fn Function to call8142 * @param {number} len Value byte length8143 * @param {*} val Value to write8144 * @ignore8145 */8146function Op(fn, len, val) {8147 /**8148 * Function to call.8149 * @type {function(Uint8Array, number, *)}8150 */8151 this.fn = fn;8152 /**8153 * Value byte length.8154 * @type {number}8155 */8156 this.len = len;8157 /**8158 * Next operation.8159 * @type {Writer.Op|undefined}8160 */8161 this.next = undefined;8162 /**8163 * Value to write.8164 * @type {*}8165 */8166 this.val = val; // type varies8167}8168/* istanbul ignore next */8169function noop() {} // eslint-disable-line no-empty-function8170/**8171 * Constructs a new writer state instance.8172 * @classdesc Copied writer state.8173 * @memberof Writer8174 * @constructor8175 * @param {Writer} writer Writer to copy state from8176 * @ignore8177 */8178function State(writer) {8179 /**8180 * Current head.8181 * @type {Writer.Op}8182 */8183 this.head = writer.head;8184 /**8185 * Current tail.8186 * @type {Writer.Op}8187 */8188 this.tail = writer.tail;8189 /**8190 * Current buffer length.8191 * @type {number}8192 */8193 this.len = writer.len;8194 /**8195 * Next state.8196 * @type {State|null}8197 */8198 this.next = writer.states;8199}8200/**8201 * Constructs a new writer instance.8202 * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.8203 * @constructor8204 */8205function Writer() {8206 /**8207 * Current length.8208 * @type {number}8209 */8210 this.len = 0;8211 /**8212 * Operations head.8213 * @type {Object}8214 */8215 this.head = new Op(noop, 0, 0);8216 /**8217 * Operations tail8218 * @type {Object}8219 */8220 this.tail = this.head;8221 /**8222 * Linked forked states.8223 * @type {Object|null}8224 */8225 this.states = null;8226 // When a value is written, the writer calculates its byte length and puts it into a linked8227 // list of operations to perform when finish() is called. This both allows us to allocate8228 // buffers of the exact required size and reduces the amount of work we have to do compared8229 // to first calculating over objects and then encoding over objects. In our case, the encoding8230 // part is just a linked list walk calling operations with already prepared values.8231}8232/**8233 * Creates a new writer.8234 * @function8235 * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}8236 */8237Writer.create = util.Buffer8238 ? function create_buffer_setup() {8239 return (Writer.create = function create_buffer() {8240 return new BufferWriter();8241 })();8242 }8243 /* istanbul ignore next */8244 : function create_array() {8245 return new Writer();8246 };8247/**8248 * Allocates a buffer of the specified size.8249 * @param {number} size Buffer size8250 * @returns {Uint8Array} Buffer8251 */8252Writer.alloc = function alloc(size) {8253 return new util.Array(size);8254};8255// Use Uint8Array buffer pool in the browser, just like node does with buffers8256/* istanbul ignore else */8257if (util.Array !== Array)8258 Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);8259/**8260 * Pushes a new operation to the queue.8261 * @param {function(Uint8Array, number, *)} fn Function to call8262 * @param {number} len Value byte length8263 * @param {number} val Value to write8264 * @returns {Writer} `this`8265 * @private8266 */8267Writer.prototype._push = function push(fn, len, val) {8268 this.tail = this.tail.next = new Op(fn, len, val);8269 this.len += len;8270 return this;8271};8272function writeByte(val, buf, pos) {8273 buf[pos] = val & 255;8274}8275function writeVarint32(val, buf, pos) {8276 while (val > 127) {8277 buf[pos++] = val & 127 | 128;8278 val >>>= 7;8279 }8280 buf[pos] = val;8281}8282/**8283 * Constructs a new varint writer operation instance.8284 * @classdesc Scheduled varint writer operation.8285 * @extends Op8286 * @constructor8287 * @param {number} len Value byte length8288 * @param {number} val Value to write8289 * @ignore8290 */8291function VarintOp(len, val) {8292 this.len = len;8293 this.next = undefined;8294 this.val = val;8295}8296VarintOp.prototype = Object.create(Op.prototype);8297VarintOp.prototype.fn = writeVarint32;8298/**8299 * Writes an unsigned 32 bit value as a varint.8300 * @param {number} value Value to write8301 * @returns {Writer} `this`8302 */8303Writer.prototype.uint32 = function write_uint32(value) {8304 // here, the call to this.push has been inlined and a varint specific Op subclass is used.8305 // uint32 is by far the most frequently used operation and benefits significantly from this.8306 this.len += (this.tail = this.tail.next = new VarintOp(8307 (value = value >>> 0)8308 < 128 ? 18309 : value < 16384 ? 28310 : value < 2097152 ? 38311 : value < 268435456 ? 48312 : 5,8313 value)).len;8314 return this;8315};8316/**8317 * Writes a signed 32 bit value as a varint.8318 * @function8319 * @param {number} value Value to write8320 * @returns {Writer} `this`8321 */8322Writer.prototype.int32 = function write_int32(value) {8323 return value < 08324 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec8325 : this.uint32(value);8326};8327/**8328 * Writes a 32 bit value as a varint, zig-zag encoded.8329 * @param {number} value Value to write8330 * @returns {Writer} `this`8331 */8332Writer.prototype.sint32 = function write_sint32(value) {8333 return this.uint32((value << 1 ^ value >> 31) >>> 0);8334};8335function writeVarint64(val, buf, pos) {8336 while (val.hi) {8337 buf[pos++] = val.lo & 127 | 128;8338 val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;8339 val.hi >>>= 7;8340 }8341 while (val.lo > 127) {8342 buf[pos++] = val.lo & 127 | 128;8343 val.lo = val.lo >>> 7;8344 }8345 buf[pos++] = val.lo;8346}8347/**8348 * Writes an unsigned 64 bit value as a varint.8349 * @param {Long|number|string} value Value to write8350 * @returns {Writer} `this`8351 * @throws {TypeError} If `value` is a string and no long library is present.8352 */8353Writer.prototype.uint64 = function write_uint64(value) {8354 var bits = LongBits.from(value);8355 return this._push(writeVarint64, bits.length(), bits);8356};8357/**8358 * Writes a signed 64 bit value as a varint.8359 * @function8360 * @param {Long|number|string} value Value to write8361 * @returns {Writer} `this`8362 * @throws {TypeError} If `value` is a string and no long library is present.8363 */8364Writer.prototype.int64 = Writer.prototype.uint64;8365/**8366 * Writes a signed 64 bit value as a varint, zig-zag encoded.8367 * @param {Long|number|string} value Value to write8368 * @returns {Writer} `this`8369 * @throws {TypeError} If `value` is a string and no long library is present.8370 */8371Writer.prototype.sint64 = function write_sint64(value) {8372 var bits = LongBits.from(value).zzEncode();8373 return this._push(writeVarint64, bits.length(), bits);8374};8375/**8376 * Writes a boolish value as a varint.8377 * @param {boolean} value Value to write8378 * @returns {Writer} `this`8379 */8380Writer.prototype.bool = function write_bool(value) {8381 return this._push(writeByte, 1, value ? 1 : 0);8382};8383function writeFixed32(val, buf, pos) {8384 buf[pos ] = val & 255;8385 buf[pos + 1] = val >>> 8 & 255;8386 buf[pos + 2] = val >>> 16 & 255;8387 buf[pos + 3] = val >>> 24;8388}8389/**8390 * Writes an unsigned 32 bit value as fixed 32 bits.8391 * @param {number} value Value to write8392 * @returns {Writer} `this`8393 */8394Writer.prototype.fixed32 = function write_fixed32(value) {8395 return this._push(writeFixed32, 4, value >>> 0);8396};8397/**8398 * Writes a signed 32 bit value as fixed 32 bits.8399 * @function8400 * @param {number} value Value to write8401 * @returns {Writer} `this`8402 */8403Writer.prototype.sfixed32 = Writer.prototype.fixed32;8404/**8405 * Writes an unsigned 64 bit value as fixed 64 bits.8406 * @param {Long|number|string} value Value to write8407 * @returns {Writer} `this`8408 * @throws {TypeError} If `value` is a string and no long library is present.8409 */8410Writer.prototype.fixed64 = function write_fixed64(value) {8411 var bits = LongBits.from(value);8412 return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);8413};8414/**8415 * Writes a signed 64 bit value as fixed 64 bits.8416 * @function8417 * @param {Long|number|string} value Value to write8418 * @returns {Writer} `this`8419 * @throws {TypeError} If `value` is a string and no long library is present.8420 */8421Writer.prototype.sfixed64 = Writer.prototype.fixed64;8422/**8423 * Writes a float (32 bit).8424 * @function8425 * @param {number} value Value to write8426 * @returns {Writer} `this`8427 */8428Writer.prototype.float = function write_float(value) {8429 return this._push(util.float.writeFloatLE, 4, value);8430};8431/**8432 * Writes a double (64 bit float).8433 * @function8434 * @param {number} value Value to write8435 * @returns {Writer} `this`8436 */8437Writer.prototype.double = function write_double(value) {8438 return this._push(util.float.writeDoubleLE, 8, value);8439};8440var writeBytes = util.Array.prototype.set8441 ? function writeBytes_set(val, buf, pos) {8442 buf.set(val, pos); // also works for plain array values8443 }8444 /* istanbul ignore next */8445 : function writeBytes_for(val, buf, pos) {8446 for (var i = 0; i < val.length; ++i)8447 buf[pos + i] = val[i];8448 };8449/**8450 * Writes a sequence of bytes.8451 * @param {Uint8Array|string} value Buffer or base64 encoded string to write8452 * @returns {Writer} `this`8453 */8454Writer.prototype.bytes = function write_bytes(value) {8455 var len = value.length >>> 0;8456 if (!len)8457 return this._push(writeByte, 1, 0);8458 if (util.isString(value)) {8459 var buf = Writer.alloc(len = base64.length(value));8460 base64.decode(value, buf, 0);8461 value = buf;8462 }8463 return this.uint32(len)._push(writeBytes, len, value);8464};8465/**8466 * Writes a string.8467 * @param {string} value Value to write8468 * @returns {Writer} `this`8469 */8470Writer.prototype.string = function write_string(value) {8471 var len = utf8.length(value);8472 return len8473 ? this.uint32(len)._push(utf8.write, len, value)8474 : this._push(writeByte, 1, 0);8475};8476/**8477 * Forks this writer's state by pushing it to a stack.8478 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.8479 * @returns {Writer} `this`8480 */8481Writer.prototype.fork = function fork() {8482 this.states = new State(this);8483 this.head = this.tail = new Op(noop, 0, 0);8484 this.len = 0;8485 return this;8486};8487/**8488 * Resets this instance to the last state.8489 * @returns {Writer} `this`8490 */8491Writer.prototype.reset = function reset() {8492 if (this.states) {8493 this.head = this.states.head;8494 this.tail = this.states.tail;8495 this.len = this.states.len;8496 this.states = this.states.next;8497 } else {8498 this.head = this.tail = new Op(noop, 0, 0);8499 this.len = 0;8500 }8501 return this;8502};8503/**8504 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.8505 * @returns {Writer} `this`8506 */8507Writer.prototype.ldelim = function ldelim() {8508 var head = this.head,8509 tail = this.tail,8510 len = this.len;8511 this.reset().uint32(len);8512 if (len) {8513 this.tail.next = head.next; // skip noop8514 this.tail = tail;8515 this.len += len;8516 }8517 return this;8518};8519/**8520 * Finishes the write operation.8521 * @returns {Uint8Array} Finished buffer8522 */8523Writer.prototype.finish = function finish() {8524 var head = this.head.next, // skip noop8525 buf = this.constructor.alloc(this.len),8526 pos = 0;8527 while (head) {8528 head.fn(head.val, buf, pos);8529 pos += head.len;8530 head = head.next;8531 }8532 // this.head = this.tail = null;8533 return buf;8534};8535Writer._configure = function(BufferWriter_) {8536 BufferWriter = BufferWriter_;8537};8538},{"./util/minimal":45}],49:[function(require,module,exports){8539"use strict";8540module.exports = BufferWriter;8541// extends Writer8542var Writer = require("./writer");8543(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;8544var util = require("./util/minimal");8545var Buffer = util.Buffer;8546/**8547 * Constructs a new buffer writer instance.8548 * @classdesc Wire format writer using node buffers.8549 * @extends Writer8550 * @constructor8551 */8552function BufferWriter() {8553 Writer.call(this);8554}8555/**8556 * Allocates a buffer of the specified size.8557 * @param {number} size Buffer size8558 * @returns {Buffer} Buffer8559 */8560BufferWriter.alloc = function alloc_buffer(size) {8561 return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);8562};8563var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"8564 ? function writeBytesBuffer_set(val, buf, pos) {8565 buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)8566 // also works for plain array values8567 }8568 /* istanbul ignore next */8569 : function writeBytesBuffer_copy(val, buf, pos) {8570 if (val.copy) // Buffer values8571 val.copy(buf, pos, 0, val.length);8572 else for (var i = 0; i < val.length;) // plain array values8573 buf[pos++] = val[i++];8574 };8575/**8576 * @override8577 */8578BufferWriter.prototype.bytes = function write_bytes_buffer(value) {8579 if (util.isString(value))8580 value = util._Buffer_from(value, "base64");8581 var len = value.length >>> 0;8582 this.uint32(len);8583 if (len)8584 this._push(writeBytesBuffer, len, value);8585 return this;8586};8587function writeStringBuffer(val, buf, pos) {8588 if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)8589 util.utf8.write(val, buf, pos);8590 else8591 buf.utf8Write(val, pos);8592}8593/**8594 * @override8595 */8596BufferWriter.prototype.string = function write_string_buffer(value) {8597 var len = Buffer.byteLength(value);8598 this.uint32(len);8599 if (len)8600 this._push(writeStringBuffer, len, value);8601 return this;8602};8603/**8604 * Finishes the write operation.8605 * @name BufferWriter#finish8606 * @function8607 * @returns {Buffer} Finished buffer8608 */...
routes.js
Source:routes.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3var node_fetch_1 = require("node-fetch");4var handlers_1 = require("./handlers"), handlers = handlers_1;5var protos = null;6function InitRoutes(p) {7 protos = p;8 onProtosLoad();9 handlers_1.default(p);10}11exports.default = InitRoutes;12var RouteListItem = /** @class */ (function () {13 function RouteListItem(url, data, handler) {14 this.url = url;15 this.data = data;16 this.handler = handler;17 }18 return RouteListItem;19}());20exports.RouteListItem = RouteListItem;21exports.listOfRoutes = [];22function onProtosLoad() {23 exports.listOfRoutes = [24 new RouteListItem("/ryzthn/rpc/GetEvent", protos.messages.Empty.create({}), handlers.GetEventHandler),25 new RouteListItem("/ryzthn/rpc/LookupUser", protos.messages.UserInfo.create({}), handlers.LookupUserHandler),26 new RouteListItem("/ryzthn/rpc/SearchUsers", protos.messages.SearchUsersResult.create({}), handlers.SearchUsersHandler),27 new RouteListItem("/ryzthn/rpc/CreateUser", protos.messages.CreateUserResult.create({}), handlers.CreateUserHandler),28 new RouteListItem("/ryzthn/rpc/UpdateUser", protos.messages.Empty.create({}), handlers.UpdateUserHandler),29 new RouteListItem("/ryzthn/rpc/SetUserContactAddress", protos.messages.Empty.create({}), handlers.SetUserContactAddressHandler),30 new RouteListItem("/ryzthn/rpc/SetUserAccess", protos.messages.Empty.create({}), handlers.SetUserAccessHandler),31 new RouteListItem("/ryzthn/rpc/SetUserLoginStatus", protos.messages.Empty.create({}), handlers.SetUserLoginStatusHandler),32 new RouteListItem("/ryzthn/rpc/ResetUserPassword", protos.messages.Empty.create({}), handlers.ResetUserPasswordHandler),33 new RouteListItem("/ryzthn/rpc/NukeHandle", protos.messages.NukeHandleResult.create({}), handlers.NukeHandleHandler),34 new RouteListItem("/ryzthn/rpc/GetHandleHistory", protos.messages.GetHandleHistoryResult.create({}), handlers.GetHandleHistoryHandler),35 new RouteListItem("/ryzthn/rpc/SendUserEmailNotification", protos.messages.Empty.create({}), handlers.SendUserEmailNotificationHandler),36 new RouteListItem("/ryzthn/rpc/SearchAuditHistory", protos.messages.SearchAuditHistoryResult.create({}), handlers.SearchAuditHistoryHandler),37 new RouteListItem("/ryzthn/rpc/GetAppConfig", protos.messages.AppConfig.create({}), handlers.GetAppConfigHandler),38 new RouteListItem("/ryzthn/rpc/GetGlobalConfig", protos.messages.GetGlobalConfigResult.create({}), handlers.GetGlobalConfigHandler),39 new RouteListItem("/ryzthn/rpc/SetGlobalConfig", protos.messages.Empty.create({}), handlers.SetGlobalConfigHandler),40 new RouteListItem("/ryzthn/rpc/GetMatchQueueConfig", protos.messages.GetMatchQueueConfigResult.create({}), handlers.GetMatchQueueConfigHandler),41 new RouteListItem("/ryzthn/rpc/SetMatchQueueConfig", protos.messages.Empty.create({}), handlers.SetMatchQueueConfigHandler),42 new RouteListItem("/ryzthn/rpc/GetMatchUserConfig", protos.messages.GetMatchUserConfigResult.create({}), handlers.GetMatchUserConfigHandler),43 new RouteListItem("/ryzthn/rpc/SetMatchUserConfig", protos.messages.Empty.create({}), handlers.SetMatchUserConfigHandler),44 new RouteListItem("/ryzthn/rpc/GetLobbyConfig", protos.messages.GetLobbyConfigResult.create({}), handlers.GetLobbyConfigHandler),45 new RouteListItem("/ryzthn/rpc/SetLobbyConfig", protos.messages.Empty.create({}), handlers.SetLobbyConfigHandler),46 new RouteListItem("/ryzthn/rpc/ListFeatureDefinitions", protos.messages.ListFeatureDefinitionsResult.create({}), handlers.ListFeatureDefinitionsHandler),47 new RouteListItem("/ryzthn/rpc/SetFeatureDefinition", protos.messages.Empty.create({}), handlers.SetFeatureDefinitionHandler),48 new RouteListItem("/ryzthn/rpc/DeleteFeatureDefinition", protos.messages.Empty.create({}), handlers.DeleteFeatureDefinitionHandler),49 new RouteListItem("/ryzthn/rpc/ListFeatureRules", protos.messages.ListFeatureRulesResult.create({}), handlers.ListFeatureRulesHandler),50 new RouteListItem("/ryzthn/rpc/GetActiveFeatures", protos.messages.GetActiveFeaturesResult.create({}), handlers.GetActiveFeaturesHandler),51 new RouteListItem("/ryzthn/rpc/CreateFeatureRule", protos.messages.Empty.create({}), handlers.CreateFeatureRuleHandler),52 new RouteListItem("/ryzthn/rpc/UpdateFeatureRule", protos.messages.Empty.create({}), handlers.UpdateFeatureRuleHandler),53 new RouteListItem("/ryzthn/rpc/DeleteFeatureRule", protos.messages.Empty.create({}), handlers.DeleteFeatureRuleHandler),54 new RouteListItem("/ryzthn/rpc/GetMatchQueueUsers", protos.messages.GetMatchQueueUsersResult.create({}), handlers.GetMatchQueueUsersHandler),55 new RouteListItem("/ryzthn/rpc/GetLobbies", protos.messages.GetLobbiesResult.create({}), handlers.GetLobbiesHandler),56 new RouteListItem("/ryzthn/rpc/GetLobby", protos.messages.GetLobbyResult.create({}), handlers.GetLobbyHandler),57 new RouteListItem("/ryzthn/rpc/GetActiveMatches", protos.messages.GetActiveMatchesResult.create({}), handlers.GetActiveMatchesHandler),58 new RouteListItem("/ryzthn/rpc/GetActiveMatch", protos.messages.GetActiveMatchResult.create({}), handlers.GetActiveMatchHandler),59 new RouteListItem("/ryzthn/rpc/GetRecentMatches", protos.messages.GetRecentMatchesResult.create({}), handlers.GetRecentMatchesHandler),60 new RouteListItem("/ryzthn/rpc/GetMatchDetail", protos.messages.GetMatchDetailResult.create({}), handlers.GetMatchDetailHandler),61 new RouteListItem("/ryzthn/rpc/GetPlayerDetail", protos.messages.GetPlayerDetailResult.create({}), handlers.GetPlayerDetailHandler),62 new RouteListItem("/ryzthn/rpc/ListDesyncs", protos.messages.ListDesyncsResult.create({}), handlers.ListDesyncsHandler),63 new RouteListItem("/ryzthn/rpc/ListCrashes", protos.messages.ListCrashesResult.create({}), handlers.ListCrashesHandler),64 new RouteListItem("/ryzthn/rpc/ListCrashBuildIdentifiers", protos.messages.ListCrashBuildIdentifiersResult.create({}), handlers.ListCrashBuildIdentifiersHandler),65 new RouteListItem("/ryzthn/rpc/ListCrashCollections", protos.messages.ListCrashCollectionsResult.create({}), handlers.ListCrashCollectionsHandler),66 new RouteListItem("/ryzthn/rpc/SearchPurchaseOrders", protos.messages.SearchPurchaseOrdersResult.create({}), handlers.SearchPurchaseOrdersHandler),67 new RouteListItem("/ryzthn/rpc/SyncPurchaseOrder", protos.messages.Empty.create({}), handlers.SyncPurchaseOrderHandler),68 new RouteListItem("/ryzthn/rpc/VoidPurchaseOrder", protos.messages.Empty.create({}), handlers.VoidPurchaseOrderHandler),69 new RouteListItem("/ryzthn/rpc/RefundPurchaseOrder", protos.messages.Empty.create({}), handlers.RefundPurchaseOrderHandler),70 new RouteListItem("/ryzthn/rpc/CountUsers", protos.messages.UserCountStats.create({}), handlers.CountUsersHandler),71 new RouteListItem("/ryzthn/rpc/GetSessions", protos.messages.GetSessionsResult.create({}), handlers.GetSessionsHandler),72 new RouteListItem("/ryzthn/rpc/GetCharacterUsage", protos.messages.GetCharacterUsageResult.create({}), handlers.GetCharacterUsageHandler),73 new RouteListItem("/ryzthn/rpc/CheckHandle", protos.messages.Empty.create({}), handlers.CheckHandleHandler),74 new RouteListItem("/ryzthn/rpc/RegisterUser", protos.messages.Empty.create({}), handlers.RegisterUserHandler),75 new RouteListItem("/ryzthn/rpc/ValidateUser", protos.messages.UserInfo.create({}), handlers.ValidateUserHandler),76 new RouteListItem("/ryzthn/rpc/GetSecretQuestion", protos.messages.GetSecretQuestionResult.create({}), handlers.GetSecretQuestionHandler),77 new RouteListItem("/ryzthn/rpc/SendPasswordResetEmail", protos.messages.Empty.create({}), handlers.SendPasswordResetEmailHandler),78 new RouteListItem("/ryzthn/rpc/VerifyResetPasswordCode", protos.messages.Empty.create({}), handlers.VerifyResetPasswordCodeHandler),79 new RouteListItem("/ryzthn/rpc/ResetPassword", protos.messages.Empty.create({}), handlers.ResetPasswordHandler),80 new RouteListItem("/ryzthn/rpc/GetUserInfo", protos.messages.UserInfo.create({}), handlers.GetUserInfoHandler),81 new RouteListItem("/ryzthn/rpc/ResendValidationEmail", protos.messages.Empty.create({}), handlers.ResendValidationEmailHandler),82 new RouteListItem("/ryzthn/rpc/SetLocale", protos.messages.Empty.create({}), handlers.SetLocaleHandler),83 new RouteListItem("/ryzthn/rpc/SetContactAddress", protos.messages.Empty.create({}), handlers.SetContactAddressHandler),84 new RouteListItem("/ryzthn/rpc/GetUserPrefs", protos.messages.UserPrefs.create({}), handlers.GetUserPrefsHandler),85 new RouteListItem("/ryzthn/rpc/SetUserPrefs", protos.messages.Empty.create({}), handlers.SetUserPrefsHandler),86 new RouteListItem("/ryzthn/rpc/ChangePassword", protos.messages.Empty.create({}), handlers.ChangePasswordHandler),87 new RouteListItem("/ryzthn/rpc/ChangeEmailAddress", protos.messages.Empty.create({}), handlers.ChangeEmailAddressHandler),88 new RouteListItem("/ryzthn/rpc/RedeemAccessCode", protos.messages.Empty.create({}), handlers.RedeemAccessCodeHandler),89 new RouteListItem("/ryzthn/rpc/CrashReport", protos.messages.Empty.create({}), handlers.CrashReportHandler),90 new RouteListItem("/ryzthn/rpc/EventPing", protos.messages.Empty.create({}), handlers.EventPingHandler),91 new RouteListItem("/ryzthn/rpc/CreateLobby", protos.messages.Empty.create({}), handlers.CreateLobbyHandler),92 new RouteListItem("/ryzthn/rpc/GetLobbyJoinCode", protos.messages.GetLobbyJoinCodeResult.create({}), handlers.GetLobbyJoinCodeHandler),93 new RouteListItem("/ryzthn/rpc/JoinLobbyByCode", protos.messages.Empty.create({}), handlers.JoinLobbyByCodeHandler),94 new RouteListItem("/ryzthn/rpc/LeaveLobby", protos.messages.Empty.create({}), handlers.LeaveLobbyHandler),95 new RouteListItem("/ryzthn/rpc/LobbySetReady", protos.messages.Empty.create({}), handlers.LobbySetReadyHandler),96 new RouteListItem("/ryzthn/rpc/LobbySetOwner", protos.messages.Empty.create({}), handlers.LobbySetOwnerHandler),97 new RouteListItem("/ryzthn/rpc/LobbySetGameOptions", protos.messages.Empty.create({}), handlers.LobbySetGameOptionsHandler),98 new RouteListItem("/ryzthn/rpc/LobbyBanUser", protos.messages.Empty.create({}), handlers.LobbyBanUserHandler),99 new RouteListItem("/ryzthn/rpc/LobbyRemoveUser", protos.messages.Empty.create({}), handlers.LobbyRemoveUserHandler),100 new RouteListItem("/ryzthn/rpc/GetGameProfile", protos.messages.GameProfile.create({}), handlers.GetGameProfileHandler),101 new RouteListItem("/ryzthn/rpc/PingTest", protos.messages.PingTestResult.create({}), handlers.PingTestHandler),102 new RouteListItem("/ryzthn/rpc/GetMatch", protos.messages.Empty.create({}), handlers.GetMatchHandler),103 new RouteListItem("/ryzthn/rpc/ResumeGetMatch", protos.messages.Empty.create({}), handlers.ResumeGetMatchHandler),104 new RouteListItem("/ryzthn/rpc/CancelGetMatch", protos.messages.Empty.create({}), handlers.CancelGetMatchHandler),105 new RouteListItem("/ryzthn/rpc/ResetGame", protos.messages.Empty.create({}), handlers.ResetGameHandler),106 new RouteListItem("/ryzthn/rpc/GetGameReplayRecord", protos.messages.GetGameReplayRecordResult.create({}), handlers.GetGameReplayRecordHandler),107 new RouteListItem("/ryzthn/rpc/DesyncReport", protos.messages.Empty.create({}), handlers.DesyncReportHandler),108 new RouteListItem("/ryzthn/rpc/UpdatePlayerPreferences", protos.messages.Empty.create({}), handlers.UpdatePlayerPreferencesHandler),109 new RouteListItem("/ryzthn/rpc/GetPlayerStats", protos.messages.GetPlayerStatsResult.create({}), handlers.GetPlayerStatsHandler),110 new RouteListItem("/ryzthn/rpc/GetRecentGames", protos.messages.GetRecentGamesResult.create({}), handlers.GetRecentGamesHandler),111 new RouteListItem("/ryzthn/rpc/Login", protos.messages.LoginRequest.create({112 // Either handle or e-mail address can be used.113 login: "1",114 password: "2",115 // Client build. May require certain version to login.116 buildVersion: "5",117 }), handlers.LoginHandler),118 new RouteListItem("/ryzthn/rpc/GetGameSessionTicket", protos.messages.GetGameSessionTicketResult.create({}), handlers.GetGameSessionTicketHandler),119 new RouteListItem("/ryzthn/rpc/RedeemGameSessionTicket", protos.messages.Empty.create({}), handlers.RedeemGameSessionTicketHandler),120 new RouteListItem("/ryzthn/rpc/Logout", protos.messages.Empty.create({}), handlers.LogoutHandler),121 new RouteListItem("/ryzthn/rpc/GetStoredPaymentMethods", protos.messages.GetStoredPaymentMethodsResult.create({}), handlers.GetStoredPaymentMethodsHandler),122 new RouteListItem("/ryzthn/rpc/CreateStoredPaymentMethod", protos.messages.Empty.create({}), handlers.CreateStoredPaymentMethodHandler),123 new RouteListItem("/ryzthn/rpc/UpdateStoredPaymentMethod", protos.messages.Empty.create({}), handlers.UpdateStoredPaymentMethodHandler),124 new RouteListItem("/ryzthn/rpc/SetDefaultStoredPaymentMethod", protos.messages.Empty.create({}), handlers.SetDefaultStoredPaymentMethodHandler),125 new RouteListItem("/ryzthn/rpc/RemoveStoredPaymentMethod", protos.messages.Empty.create({}), handlers.RemoveStoredPaymentMethodHandler),126 new RouteListItem("/ryzthn/rpc/SubmitPurchaseOrder", protos.messages.SubmitPurchaseOrderResult.create({}), handlers.SubmitPurchaseOrderHandler),127 new RouteListItem("/ryzthn/rpc/GetPurchaseOrder", protos.messages.PurchaseOrder.create({}), handlers.GetPurchaseOrderHandler),128 new RouteListItem("/ryzthn/rpc/GetAccountOrderHistory", protos.messages.GetAccountOrderHistoryResult.create({}), handlers.GetAccountOrderHistoryHandler),129 new RouteListItem("/ryzthn/rpc/GetAccountBalanceHistory", protos.messages.GetAccountBalanceHistoryResult.create({}), handlers.GetAccountBalanceHistoryHandler),130 new RouteListItem("/ryzthn/rpc/GetAccountBalance", protos.messages.GetAccountBalanceResult.create({}), handlers.GetAccountBalanceHandler),131 ];132}133exports.onProtosLoad = onProtosLoad;134function request(route) {135 console.log(route.data);136 // const final = createResultPayload(route.data.$type.encode(route.data).finish());137 var final = route.data.$type.encode(route.data).finish();138 node_fetch_1.default("https://localhost:" + (getPort() || 8000) + route.url, {139 "method": "POST",140 "body": JSON.stringify(Array.from(final))141 })142 .then(function (res) { return route.handler(res); })143 .catch(function (e) {144 console.error("Could not complete the request. " + e);145 });146}147exports.request = request;148function createResultPayload(mainDataEncoded) {149 var ResultPayload = {150 result: protos.enums.Status.values.S_SUCCESS,151 content: mainDataEncoded152 };153 var err = protos.messages.Result.verify(ResultPayload);154 if (err) {155 console.error(err);156 return;157 }158 var resultData = protos.messages.Result.create(ResultPayload);159 var final = protos.messages.Result.encode(resultData).finish();160 return final;161}162function parseURLSearch() {163 var searchValues = {};164 location.search.replace(/^./, "")165 .split("&")166 .map(function (pair) {167 var pairArray = pair.split("=");168 searchValues[pairArray[0]] = pairArray[1];169 });170 return searchValues;171}172function getPort() {173 return document.querySelector(".port-input").value;...
auto-gen-cs.js
Source:auto-gen-cs.js
1var fs = require("fs");2var listOfNames = [3 'GetEvent',4 'LookupUser',5 'SearchUsers',6 'CreateUser',7 'UpdateUser',8 'SetUserContactAddress',9 'SetUserAccess',10 'SetUserLoginStatus',11 'ResetUserPassword',12 'NukeHandle',13 'GetHandleHistory',14 'SendUserEmailNotification',15 'SearchAuditHistory',16 'GetAppConfig',17 'GetGlobalConfig',18 'SetGlobalConfig',19 'GetMatchQueueConfig',20 'SetMatchQueueConfig',21 'GetMatchUserConfig',22 'SetMatchUserConfig',23 'GetLobbyConfig',24 'SetLobbyConfig',25 'ListFeatureDefinitions',26 'SetFeatureDefinition',27 'DeleteFeatureDefinition',28 'ListFeatureRules',29 'GetActiveFeatures',30 'CreateFeatureRule',31 'UpdateFeatureRule',32 'DeleteFeatureRule',33 'GetMatchQueueUsers',34 'GetLobbies',35 'GetLobby',36 'GetActiveMatches',37 'GetActiveMatch',38 'GetRecentMatches',39 'GetMatchDetail',40 'GetPlayerDetail',41 'ListDesyncs',42 'ListCrashes',43 'ListCrashBuildIdentifiers',44 'ListCrashCollections',45 'SearchPurchaseOrders',46 'SyncPurchaseOrder',47 'VoidPurchaseOrder',48 'RefundPurchaseOrder',49 'CountUsers',50 'GetSessions',51 'GetCharacterUsage',52 'CheckHandle',53 'RegisterUser',54 'ValidateUser',55 'GetSecretQuestion',56 'SendPasswordResetEmail',57 'VerifyResetPasswordCode',58 'ResetPassword',59 'GetUserInfo',60 'ResendValidationEmail',61 'SetLocale',62 'SetContactAddress',63 'GetUserPrefs',64 'SetUserPrefs',65 'ChangePassword',66 'ChangeEmailAddress',67 'RedeemAccessCode',68 'CrashReport',69 'EventPing',70 'CreateLobby',71 'GetLobbyJoinCode',72 'JoinLobbyByCode',73 'LeaveLobby',74 'LobbySetReady',75 'LobbySetOwner',76 'LobbySetGameOptions',77 'LobbyBanUser',78 'LobbyRemoveUser',79 'GetGameProfile',80 'PingTest',81 'GetMatch',82 'ResumeGetMatch',83 'CancelGetMatch',84 'ResetGame',85 'GetGameReplayRecord',86 'DesyncReport',87 'UpdatePlayerPreferences',88 'GetPlayerStats',89 'GetRecentGames',90 'Login',91 'GetGameSessionTicket',92 'RedeemGameSessionTicket',93 'Logout',94 'GetStoredPaymentMethods',95 'CreateStoredPaymentMethod',96 'UpdateStoredPaymentMethod',97 'SetDefaultStoredPaymentMethod',98 'RemoveStoredPaymentMethod',99 'SubmitPurchaseOrder',100 'GetPurchaseOrder',101 'GetAccountOrderHistory',102 'GetAccountBalanceHistory',103 'GetAccountBalance',104 'GetUserCount',105 'GetUsersInRankedCount',106];107function makeCode(name) {108 return `using Rising_Thunder_Server_CS.Protobufs.Tbportal;109using Rising_Thunder_Server_CS.Protobufs.Tbadmin;110using Rising_Thunder_Server_CS.Protobufs.Tbmatch;111using Rising_Thunder_Server_CS.Protobufs.Tbrpc;112using Rising_Thunder_Server_CS.Protobufs.Tbui;113using System.Collections.Generic;114using Microsoft.AspNetCore.Mvc;115using Newtonsoft.Json.Linq;116using System.Diagnostics;117using Google.Protobuf;118using Newtonsoft.Json;119using System.IO;120using System;121namespace Rising_Thunder_Server_CS.Controllers122{123 public partial class RPCController : ControllerBase124 {125 [HttpPost("{{NAME}}")]126 public ByteString {{NAME}}()127 {128 byte[] payload = null;129 Empty content = null;130 using (StreamReader reader = new StreamReader(Request.Body))131 {132 payload = JsonConvert.DeserializeObject<Byte[]>(reader.ReadToEnd());133 }134 if (payload != null)135 {136 content = Empty.Parser.ParseFrom(payload);137 }138 // do logout stuff here...139 // success140 Result resultPayload = new Result()141 {142 Result_ = Status.SSuccess143 };144 var outData = resultPayload.ToByteString();145 Debug.Print("\\n\\r\\n\\rSome converted data: '" + content.ToString() + "'\\n\\r\\n\\r");146 Debug.Print("\\n\\r\\n\\rSome resulted data: '" + resultPayload.ToString() + "'\\n\\r\\n\\r");147 return outData;148 }149 }150}`.replace(/\{\{NAME\}\}/g, name);151}152var arr = [153 "EventPing",154 "GetUserInfo",155 "Login",156 "Logout",157 "PingTest",158 "RPC",159];160listOfNames.filter(x => {161 return arr.indexOf(x) < 0;162}).map(name => {163 var code = makeCode(name);164 var filename = name + "Controller.cs";165 fs.writeFile("../server/Rising Thunder Server CS/Controllers/" + filename, code, err => {166 if (err) throw err;167 });...
ios-crash-log.js
Source:ios-crash-log.js
...22 this.sim = opts.sim;23 }24 async _gatherFromRealDevice () {25 if (await this.pyideviceClient.assertExists(false)) {26 return (await this.pyideviceClient.listCrashes())27 .map((x) => `${REAL_DEVICE_MAGIC}${MAGIC_SEP}${x}`);28 }29 let crashLogsRoot = this.logDir;30 if (this.udid) {31 this.phoneName = this.phoneName || await utilities.getDeviceName(this.udid);32 crashLogsRoot = path.resolve(crashLogsRoot, this.phoneName);33 }34 if (!await fs.exists(crashLogsRoot)) {35 log.debug(`Crash reports root '${crashLogsRoot}' does not exist. Got nothing to gather.`);36 return [];37 }38 const foundFiles = await fs.glob(`${crashLogsRoot}/**/*.crash`, {39 strict: false40 });...
py-ios-device-client.js
Source:py-ios-device-client.js
1import { exec, SubProcess } from 'teen_process';2import { fs, util, tempDir } from '@appium/support';3import log from './logger';4import path from 'path';5// https://github.com/YueChen-C/py-ios-device6const BINARY_NAME = 'pyidevice';7class Pyidevice {8 constructor (udid) {9 this.udid = udid;10 this.binaryPath = null;11 }12 async assertExists (isStrict = true) {13 if (this.binaryPath) {14 return true;15 }16 try {17 this.binaryPath = await fs.which(BINARY_NAME);18 return true;19 } catch (e) {20 if (isStrict) {21 throw new Error(`${BINARY_NAME} binary cannot be found in PATH. ` +22 `Please make sure it is installed. Visit https://github.com/YueChen-C/py-ios-device for ` +23 `more details.`);24 }25 return false;26 }27 }28 async execute (args, opts = {}) {29 await this.assertExists();30 const {31 cwd,32 format = 'json',33 logStdout = false,34 asynchronous = false,35 } = opts;36 const finalArgs = [...args, '--udid', this.udid];37 if (format) {38 finalArgs.push('--format', format);39 }40 const cmdStr = util.quote([this.binaryPath, ...finalArgs]);41 log.debug(`Executing ${cmdStr}`);42 try {43 if (asynchronous) {44 const result = new SubProcess(this.binaryPath, finalArgs, {cwd});45 await result.start(0);46 return result;47 }48 const result = await exec(this.binaryPath, finalArgs, {cwd});49 if (logStdout) {50 log.debug(`Command output: ${result.stdout}`);51 }52 return result;53 } catch (e) {54 throw new Error(`'${cmdStr}' failed. Original error: ${e.stderr || e.stdout || e.message}`);55 }56 }57 async listProfiles () {58 const {stdout} = await this.execute(['profiles', 'list']);59 return JSON.parse(stdout);60 }61 async installProfile ({profilePath, payload} = {}) {62 if (!profilePath && !payload) {63 throw new Error('Either the full path to the profile or its payload must be provided');64 }65 let tmpRoot;66 let srcPath = profilePath;67 try {68 if (!srcPath) {69 tmpRoot = await tempDir.openDir();70 srcPath = path.join(tmpRoot, 'cert.pem');71 await fs.writeFile(srcPath, payload, 'utf8');72 }73 await this.execute(['profiles', 'install', '--path', srcPath], {74 logStdout: true75 });76 } finally {77 if (tmpRoot) {78 await fs.rimraf(tmpRoot);79 }80 }81 }82 async removeProfile (name) {83 await this.execute(['profiles', 'remove', name], {logStdout: true});84 }85 async listCrashes () {86 const {stdout} = await this.execute(['crash', 'list']);87 return JSON.parse(stdout.replace(/'/g, '"')).filter((x) => !['.', '..'].includes(x));88 }89 async exportCrash (name, dstFolder) {90 await this.execute(['crash', 'export', '--name', name], {91 logStdout: true,92 // The tool exports crash reports to the current working dir93 cwd: dstFolder94 });95 }96 async collectPcap (dstFile) {97 return await this.execute(['pcapd', dstFile], {98 format: null,99 asynchronous: true100 });101 }102}103export { Pyidevice };...
api.js
Source:api.js
1import axios from "axios";2const mainAxios = axios.create({3 xsrfCookieName: "csrftoken",4 xsrfHeaderName: "X-CSRFToken",5 withCredentials: true,6});7export const retrieveBucket = async (id) =>8 (await mainAxios.get(`/crashmanager/rest/buckets/${id}/`)).data;9export const listBuckets = async (params) =>10 (await mainAxios.get("/crashmanager/rest/buckets/", { params })).data;11export const createBucket = async ({ params, ...data }) =>12 (await mainAxios.post("/crashmanager/rest/buckets/", data, { params })).data;13export const updateBucket = async ({ id, params, ...data }) =>14 (await mainAxios.patch(`/crashmanager/rest/buckets/${id}/`, data, { params }))15 .data;16export const retrieveCrash = async (id) =>17 (await mainAxios.get(`/crashmanager/rest/crashes/${id}/`)).data;18export const retrieveCrashTestCase = async (id) =>19 (await mainAxios.get(`/crashmanager/rest/crashes/${id}/download/`)).data;20export const retrieveCrashTestCaseBinary = async (id) =>21 new Uint8Array(22 (23 await mainAxios.request({24 url: `/crashmanager/rest/crashes/${id}/download/`,25 responseType: "arraybuffer",26 })27 ).data28 );29export const listCrashes = async (params) =>30 (await mainAxios.get("/crashmanager/rest/crashes/", { params })).data;31export const listBugProviders = async () =>32 (await mainAxios.get("/crashmanager/rest/bugproviders/")).data;33export const listTemplates = async () =>34 (await mainAxios.get("/crashmanager/rest/bugzilla/templates/")).data;35export const listUnreadNotifications = async (params) =>36 (await mainAxios.get("/crashmanager/rest/inbox/", { params })).data;37export const dismissNotification = async (id) =>38 (await mainAxios.patch(`/crashmanager/rest/inbox/${id}/mark_as_read/`)).data;39export const dismissAllNotifications = async () =>40 (await mainAxios.patch("/crashmanager/rest/inbox/mark_all_as_read/")).data;41export const listPools = async (params) =>42 (await mainAxios.get("/taskmanager/rest/pools/", { params })).data;43export const listTasks = async (params) =>...
Using AI Code Generation
1const { AppiumDriver, errors } = require('appium-base-driver');2const { XCUITestDriver } = require('appium-xcuitest-driver');3const { XCUITestSimulator, XCUITestRealDevice } = require('appium-xcuitest-driver/lib/commands/crash-report');4const driver = new XCUITestDriver();5const proxy = new AppiumDriver();6driver.proxydriver = proxy;7const crashLogs = await driver.listCrashes();8console.log(crashLogs);9[ { 'app_name': 'MyApp',10 'reason': 'EXC_BAD_ACCESS / KERN_INVALID_ADDRESS' } ]
Using AI Code Generation
1const wd = require('wd');2const assert = require('assert');3const {exec} = require('teen_process');4const {fs, system} = require('appium-support');5const PORT = 4723;6const HOST = 'localhost';7const BUNDLE_ID = 'com.apple.Preferences';8const DEVICE_UDID = '00008020-00013E0C2A20802E';9const caps = {10};11async function main () {12 const driver = await wd.promiseChainRemote(HOST, PORT);13 await driver.init(caps);14 await driver.sleep(3000);15 await driver.execute('mobile: listCrashes', {});16}17main();18Version: 13.0 (13.0)19Code Type: ARM-64 (Native)20OS Version: iPhone OS 13.4 (17E255)
Using AI Code Generation
1let driver = await createDriver();2let crashes = await driver.listCrashes();3console.log(crashes);4await driver.quit();5let driver = await createDriver();6let crashes = await driver.listCrashes();7console.log(crashes);8await driver.quit();9let driver = await createDriver();10let crashes = await driver.listCrashes();11console.log(crashes);12await driver.quit();13let driver = await createDriver();14let crashes = await driver.listCrashes();15console.log(crashes);16await driver.quit();17let driver = await createDriver();18let crashes = await driver.listCrashes();19console.log(crashes);20await driver.quit();21let driver = await createDriver();22let crashes = await driver.listCrashes();23console.log(crashes);24await driver.quit();25let driver = await createDriver();26let crashes = await driver.listCrashes();27console.log(crashes);28await driver.quit();29let driver = await createDriver();30let crashes = await driver.listCrashes();31console.log(crashes);32await driver.quit();33let driver = await createDriver();34let crashes = await driver.listCrashes();35console.log(crashes);36await driver.quit();37let driver = await createDriver();38let crashes = await driver.listCrashes();39console.log(crashes);40await driver.quit();41let driver = await createDriver();42let crashes = await driver.listCrashes();43console.log(crashes);44await driver.quit();45let driver = await createDriver();46let crashes = await driver.listCrashes();47console.log(crashes);48await driver.quit();
Using AI Code Generation
1const wd = require('wd');2const assert = require('assert');3const PORT = 4723;4const HOST = 'localhost';5const DEVICE_NAME = 'iPhone 11 Pro Max';6const PLATFORM_VERSION = '13.2.2';7const UDID = '00008020-000C0D5E1C30002E';8const BUNDLE_ID = 'com.apple.mobilesafari';9(async () => {10 const driver = wd.promiseChainRemote(HOST, PORT);11 await driver.init({
Using AI Code Generation
1const { execSync } = require('child_process');2const crashLogs = execSync('xcrun simctl spawn booted log stream --predicate "processImagePath CONTAINS \'WebDriverAgentRunner\'" --style compact --level debug --color always --info --debug --fault --error --signpost --predicate "eventMessage CONTAINS \'Crash\'"');3console.log(crashLogs);4const { execSync } = require('child_process');5const crashLogs = execSync('xcrun simctl spawn booted log stream --predicate "processImagePath CONTAINS \'WebDriverAgentRunner\'" --style compact --level debug --color always --info --debug --fault --error --signpost --predicate "eventMessage CONTAINS \'Crash\'"');6console.log(crashLogs);7const { execSync } = require('child_process');8const crashLogs = execSync('xcrun simctl spawn booted log stream --predicate "processImagePath CONTAINS \'WebDriverAgentRunner\'" --style compact --level debug --color always --info --debug --fault --error --signpost --predicate "eventMessage CONTAINS \'Crash\'"');9console.log(crashLogs);10const { execSync } = require('child_process');11const crashLogs = execSync('xcrun simctl spawn booted log stream --predicate "processImagePath CONTAINS \'WebDriverAgentRunner\'" --style compact --level debug --color always --info --debug --fault --error --signpost --predicate "eventMessage CONTAINS \'Crash\'"');12console.log(crashLogs);13const { execSync } = require('child_process');14const crashLogs = execSync('xcrun simctl spawn booted log stream --predicate "processImagePath CONTAINS \'WebDriverAgentRunner\'" --style compact --level debug --color always --info --debug --fault --error --signpost --predicate "eventMessage CONTAINS \'Crash\'"');15console.log(crashLogs);16const { execSync } = require('child_process');
Using AI Code Generation
1const { exec } = require('child_process');2var appium = require('appium');3var path = require('path');4var fs = require('fs');5var appiumPath = path.dirname(require.resolve('appium'));6var appiumProcess = exec('node ' + appiumPath + '/build/lib/main.js -p 4723 -U 00008020-001A1C0E0C20002E --log-level d
Using AI Code Generation
1const request = require('request');2const fs = require('fs');3const appiumHeaders = {4};5const appiumBody = {6 'desiredCapabilities': {7 }8};9const appiumOptions = {10 body: JSON.stringify(appiumBody)11};12const appiumCallback = (error, response, body) => {13 if (error) {14 console.log('error: ', error);15 } else {16 console.log('statusCode: ', response && response.statusCode);17 console.log('body: ', body);18 const appiumResponse = JSON.parse(body);19 const sessionId = appiumResponse.sessionId;20 console.log('sessionId: ' + sessionId);21 const appiumOptions = {22 };23 const appiumCallback = (error, response, body) => {24 if (error) {25 console.log('error: ', error);26 } else {27 console.log('statusCode: ', response && response.statusCode);28 console.log('body: ', body);29 }30 };31 request(appiumOptions, appiumCallback);32 }33};34request(appiumOptions, appiumCallback);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!