index.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993
  1. (function() {
  2. var nodeEnv = typeof require !== 'undefined' && typeof process !== 'undefined';
  3. var __module = nodeEnv ? module : {exports:{}};
  4. var __filename = 'preview-scripts/__node_modules/tsbuffer/index.js';
  5. var __require = nodeEnv ? function (request) {
  6. return cc.require(request);
  7. } : function (request) {
  8. return __quick_compile_project__.require(request, __filename);
  9. };
  10. function __define (exports, require, module) {
  11. if (!nodeEnv) {__quick_compile_project__.registerModule(__filename, module);}(function (Buffer){
  12. /*!
  13. * TSBuffer v2.2.10
  14. * -----------------------------------------
  15. * MIT LICENSE
  16. * KingWorks (C) Copyright 2025
  17. * https://github.com/k8w/tsbuffer
  18. */
  19. 'use strict';
  20. Object.defineProperty(exports, '__esModule', { value: true });
  21. require('k8w-extend-native');
  22. var tslib = require('tslib');
  23. var tsbufferValidator = require('tsbuffer-validator');
  24. var tsbufferSchema = require('tsbuffer-schema');
  25. var Base64Util = /** @class */ (function () {
  26. function Base64Util() {
  27. }
  28. Base64Util.bufferToBase64 = function (buf) {
  29. if (typeof Buffer !== "undefined") {
  30. return Buffer.from(buf).toString("base64");
  31. }
  32. var base64 = "";
  33. var len = buf.length;
  34. for (var i = 0; i < len; i += 3) {
  35. base64 += base64Chars[buf[i] >> 2];
  36. base64 += base64Chars[((buf[i] & 3) << 4) | (buf[i + 1] >> 4)];
  37. base64 += base64Chars[((buf[i + 1] & 15) << 2) | (buf[i + 2] >> 6)];
  38. base64 += base64Chars[buf[i + 2] & 63];
  39. }
  40. if (len % 3 === 2) {
  41. base64 = base64.substring(0, base64.length - 1) + "=";
  42. }
  43. else if (len % 3 === 1) {
  44. base64 = base64.substring(0, base64.length - 2) + "==";
  45. }
  46. return base64;
  47. };
  48. Base64Util.base64ToBuffer = function (base64) {
  49. if (typeof Buffer !== "undefined") {
  50. return new Uint8Array(Buffer.from(base64, "base64"));
  51. }
  52. var bufferLength = base64.length * 0.75, len = base64.length, p = 0;
  53. var encoded1, encoded2, encoded3, encoded4;
  54. if (base64[base64.length - 1] === "=") {
  55. bufferLength--;
  56. if (base64[base64.length - 2] === "=") {
  57. bufferLength--;
  58. }
  59. }
  60. var buf = new Uint8Array(bufferLength);
  61. for (var i = 0; i < len; i += 4) {
  62. encoded1 = lookup[base64.charCodeAt(i)];
  63. encoded2 = lookup[base64.charCodeAt(i + 1)];
  64. encoded3 = lookup[base64.charCodeAt(i + 2)];
  65. encoded4 = lookup[base64.charCodeAt(i + 3)];
  66. buf[p++] = (encoded1 << 2) | (encoded2 >> 4);
  67. buf[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  68. buf[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  69. }
  70. return buf;
  71. };
  72. return Base64Util;
  73. }());
  74. /*base64*/
  75. var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  76. // Use a lookup table to find the index.
  77. var lookup = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256);
  78. for (var i = 0; i < base64Chars.length; i++) {
  79. lookup[base64Chars.charCodeAt(i)] = i;
  80. }
  81. /*end*/
  82. var CoderUtil = /** @class */ (function () {
  83. function CoderUtil() {
  84. }
  85. CoderUtil.isJsonCompatible = function (schema, type, protoHelper) {
  86. var _this = this;
  87. var schemaInfo = schema;
  88. var key = type === "encode" ? "isJsonEncodable" : "isJsonDecodable";
  89. if (schemaInfo[key] === undefined) {
  90. // Just for avoding circular recursive, the value should be overwriten below
  91. schemaInfo[key] = true;
  92. switch (schema.type) {
  93. case tsbufferSchema.SchemaType.Array:
  94. schemaInfo[key] = this.isJsonCompatible(schema.elementType, type, protoHelper);
  95. break;
  96. case tsbufferSchema.SchemaType.Tuple:
  97. schemaInfo[key] = schema.elementTypes.every(function (v) {
  98. return _this.isJsonCompatible(v, type, protoHelper);
  99. });
  100. break;
  101. case tsbufferSchema.SchemaType.Interface:
  102. var flatSchema = protoHelper.getFlatInterfaceSchema(schema);
  103. schemaInfo[key] = flatSchema.properties.every(function (v) {
  104. return _this.isJsonCompatible(v.type, type, protoHelper);
  105. });
  106. if (flatSchema.indexSignature) {
  107. schemaInfo[key] =
  108. schemaInfo[key] &&
  109. this.isJsonCompatible(flatSchema.indexSignature.type, type, protoHelper);
  110. }
  111. break;
  112. case tsbufferSchema.SchemaType.IndexedAccess:
  113. case tsbufferSchema.SchemaType.Reference: {
  114. var parsed = protoHelper.parseReference(schema);
  115. schemaInfo[key] = this.isJsonCompatible(parsed, type, protoHelper);
  116. break;
  117. }
  118. case tsbufferSchema.SchemaType.Union:
  119. case tsbufferSchema.SchemaType.Intersection:
  120. schemaInfo[key] = schema.members.every(function (v) {
  121. return _this.isJsonCompatible(v.type, type, protoHelper);
  122. });
  123. break;
  124. case tsbufferSchema.SchemaType.NonNullable:
  125. schemaInfo[key] = this.isJsonCompatible(schema.target, type, protoHelper);
  126. break;
  127. case tsbufferSchema.SchemaType.Pick:
  128. case tsbufferSchema.SchemaType.Partial:
  129. case tsbufferSchema.SchemaType.Omit:
  130. case tsbufferSchema.SchemaType.Overwrite: {
  131. var parsed = protoHelper.parseMappedType(schema);
  132. if (parsed.type === tsbufferSchema.SchemaType.Interface) {
  133. var flatSchema_1 = protoHelper.getFlatInterfaceSchema(schema);
  134. schemaInfo[key] = flatSchema_1.properties.every(function (v) {
  135. return _this.isJsonCompatible(v.type, type, protoHelper);
  136. });
  137. if (flatSchema_1.indexSignature) {
  138. schemaInfo[key] =
  139. schemaInfo[key] &&
  140. this.isJsonCompatible(flatSchema_1.indexSignature.type, type, protoHelper);
  141. }
  142. }
  143. else if (parsed.type === tsbufferSchema.SchemaType.Union || parsed.type === tsbufferSchema.SchemaType.Intersection) {
  144. schemaInfo[key] = parsed.members.every(function (v) {
  145. return _this.isJsonCompatible(v.type, type, protoHelper);
  146. });
  147. }
  148. break;
  149. }
  150. case tsbufferSchema.SchemaType.Custom:
  151. case tsbufferSchema.SchemaType.Date:
  152. case tsbufferSchema.SchemaType.Buffer:
  153. schemaInfo[key] = false;
  154. break;
  155. default:
  156. schemaInfo[key] = true;
  157. break;
  158. }
  159. }
  160. return schemaInfo[key];
  161. };
  162. return CoderUtil;
  163. }());
  164. /** @internal */
  165. var IdBlockUtil = /** @class */ (function () {
  166. function IdBlockUtil() {
  167. }
  168. IdBlockUtil.getPayloadLengthInfo = function (parsedSchema, protoHelper) {
  169. switch (parsedSchema.type) {
  170. case tsbufferSchema.SchemaType.Boolean:
  171. case tsbufferSchema.SchemaType.Enum:
  172. return { lengthType: LengthType.Varint };
  173. case tsbufferSchema.SchemaType.Number:
  174. if (!parsedSchema.scalarType ||
  175. parsedSchema.scalarType.includes("64") ||
  176. parsedSchema.scalarType === "double") {
  177. return { lengthType: LengthType.Bit64 };
  178. }
  179. else if (parsedSchema.scalarType && parsedSchema.scalarType.startsWith("big")) {
  180. return { lengthType: LengthType.LengthDelimited };
  181. }
  182. else {
  183. return { lengthType: LengthType.Varint };
  184. }
  185. case tsbufferSchema.SchemaType.Buffer:
  186. case tsbufferSchema.SchemaType.String:
  187. case tsbufferSchema.SchemaType.Any:
  188. case tsbufferSchema.SchemaType.Object:
  189. return { lengthType: LengthType.LengthDelimited };
  190. case tsbufferSchema.SchemaType.Interface:
  191. case tsbufferSchema.SchemaType.Pick:
  192. case tsbufferSchema.SchemaType.Partial:
  193. case tsbufferSchema.SchemaType.Omit:
  194. case tsbufferSchema.SchemaType.Union:
  195. case tsbufferSchema.SchemaType.Intersection:
  196. return { lengthType: LengthType.IdBlock };
  197. case tsbufferSchema.SchemaType.Array:
  198. case tsbufferSchema.SchemaType.Overwrite:
  199. case tsbufferSchema.SchemaType.Tuple:
  200. return {
  201. lengthType: LengthType.LengthDelimited,
  202. needLengthPrefix: true,
  203. };
  204. case tsbufferSchema.SchemaType.Literal:
  205. return {
  206. lengthType: LengthType.LengthDelimited,
  207. needLengthPrefix: false,
  208. };
  209. case tsbufferSchema.SchemaType.Date:
  210. return { lengthType: LengthType.Varint };
  211. case tsbufferSchema.SchemaType.NonNullable:
  212. return this.getPayloadLengthInfo(protoHelper.parseReference(parsedSchema.target), protoHelper);
  213. case tsbufferSchema.SchemaType.Custom:
  214. return { lengthType: LengthType.LengthDelimited };
  215. default:
  216. // @ts-expect-error
  217. throw new Error("Unrecognized schema type: ".concat(parsedSchema.type));
  218. }
  219. };
  220. return IdBlockUtil;
  221. }());
  222. /** @internal */
  223. var LengthType;
  224. (function (LengthType) {
  225. LengthType[LengthType["LengthDelimited"] = 0] = "LengthDelimited";
  226. LengthType[LengthType["Varint"] = 1] = "Varint";
  227. LengthType[LengthType["Bit64"] = 2] = "Bit64";
  228. LengthType[LengthType["IdBlock"] = 3] = "IdBlock";
  229. })(LengthType || (LengthType = {}));
  230. /** @internal */
  231. var SchemaUtil = /** @class */ (function () {
  232. function SchemaUtil() {
  233. }
  234. /** type类型是否能编码为该literal */
  235. SchemaUtil.canBeLiteral = function (schema, literal) {
  236. var _this = this;
  237. if (schema.type === tsbufferSchema.SchemaType.Union) {
  238. return schema.members.some(function (v) { return _this.canBeLiteral(v.type, literal); });
  239. }
  240. if (schema.type === tsbufferSchema.SchemaType.Any) {
  241. return true;
  242. }
  243. if (schema.type === tsbufferSchema.SchemaType.Literal && schema.literal === literal) {
  244. return true;
  245. }
  246. return false;
  247. };
  248. return SchemaUtil;
  249. }());
  250. var TypedArrays = {
  251. Int8Array: Int8Array,
  252. Int16Array: Int16Array,
  253. Int32Array: Int32Array,
  254. Uint8Array: Uint8Array,
  255. Uint16Array: Uint16Array,
  256. Uint32Array: Uint32Array,
  257. Float32Array: Float32Array,
  258. Float64Array: Float64Array,
  259. };
  260. /**!
  261. * From [protobuf.js](https://github.com/protobufjs/protobuf.js/blob/master/lib/utf8/index.js)
  262. */
  263. var Utf8CoderJS = {
  264. measureLength: function (str) {
  265. var len = 0, c = 0;
  266. for (var i = 0; i < str.length; ++i) {
  267. c = str.charCodeAt(i);
  268. if (c < 128)
  269. len += 1;
  270. else if (c < 2048)
  271. len += 2;
  272. else if ((c & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
  273. ++i;
  274. len += 4;
  275. }
  276. else
  277. len += 3;
  278. }
  279. return len;
  280. },
  281. write: function (str, buf, pos) {
  282. var start = pos, c1, // character 1
  283. c2; // character 2
  284. for (var i = 0; i < str.length; ++i) {
  285. c1 = str.charCodeAt(i);
  286. if (c1 < 128) {
  287. buf[pos++] = c1;
  288. }
  289. else if (c1 < 2048) {
  290. buf[pos++] = (c1 >> 6) | 192;
  291. buf[pos++] = (c1 & 63) | 128;
  292. }
  293. else if ((c1 & 0xfc00) === 0xd800 && ((c2 = str.charCodeAt(i + 1)) & 0xfc00) === 0xdc00) {
  294. c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff);
  295. ++i;
  296. buf[pos++] = (c1 >> 18) | 240;
  297. buf[pos++] = ((c1 >> 12) & 63) | 128;
  298. buf[pos++] = ((c1 >> 6) & 63) | 128;
  299. buf[pos++] = (c1 & 63) | 128;
  300. }
  301. else {
  302. buf[pos++] = (c1 >> 12) | 224;
  303. buf[pos++] = ((c1 >> 6) & 63) | 128;
  304. buf[pos++] = (c1 & 63) | 128;
  305. }
  306. }
  307. return pos - start;
  308. },
  309. read: function (buf, pos, length) {
  310. if (length < 1) {
  311. return "";
  312. }
  313. var str = "";
  314. for (var i = pos, end = pos + length; i < end;) {
  315. var t = buf[i++];
  316. if (t <= 0x7f) {
  317. str += String.fromCharCode(t);
  318. }
  319. else if (t >= 0xc0 && t < 0xe0) {
  320. str += String.fromCharCode(((t & 0x1f) << 6) | (buf[i++] & 0x3f));
  321. }
  322. else if (t >= 0xe0 && t < 0xf0) {
  323. str += String.fromCharCode(((t & 0xf) << 12) | ((buf[i++] & 0x3f) << 6) | (buf[i++] & 0x3f));
  324. }
  325. else if (t >= 0xf0) {
  326. var t2 = (((t & 7) << 18) |
  327. ((buf[i++] & 0x3f) << 12) |
  328. ((buf[i++] & 0x3f) << 6) |
  329. (buf[i++] & 0x3f)) -
  330. 0x10000;
  331. str += String.fromCharCode(0xd800 + (t2 >> 10));
  332. str += String.fromCharCode(0xdc00 + (t2 & 0x3ff));
  333. }
  334. }
  335. return str;
  336. },
  337. };
  338. var Utf8CoderNode = {
  339. measureLength: function (str) { return Buffer.byteLength(str, "utf-8"); },
  340. write: function (str, buf, pos) {
  341. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).write(str, pos, "utf-8");
  342. },
  343. read: function (buf, pos, length) {
  344. return Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString("utf-8", pos, pos + length);
  345. },
  346. };
  347. /**
  348. * 自动判断环境,选择使用NodeJS Native方法编码或是JS编码
  349. */
  350. var Utf8Coder = typeof Buffer !== "undefined" && Buffer.from && Buffer.prototype.write
  351. ? Utf8CoderNode
  352. : Utf8CoderJS;
  353. /** @internal */
  354. var Varint64 = /** @class */ (function () {
  355. function Varint64(high, low, byteLength) {
  356. this.uint32s = new Uint32Array([high, low]);
  357. if (byteLength !== undefined) {
  358. this._byteLength = byteLength;
  359. }
  360. }
  361. Varint64.from = function (value) {
  362. if (value === 0) {
  363. return this.Zero;
  364. }
  365. var sign = value < 0;
  366. if (sign) {
  367. value = -value;
  368. }
  369. var lo = value >>> 0, hi = ((value - lo) / 4294967296) >>> 0;
  370. if (sign) {
  371. hi = ~hi >>> 0;
  372. lo = ~lo >>> 0;
  373. if (++lo > 4294967295) {
  374. lo = 0;
  375. if (++hi > 4294967295)
  376. hi = 0;
  377. }
  378. }
  379. return new Varint64(hi, lo);
  380. };
  381. Varint64.prototype.toNumber = function (unsigned) {
  382. if (!unsigned && this.uint32s[0] >>> 31) {
  383. var low = (~this.uint32s[1] + 1) >>> 0, high = ~this.uint32s[0] >>> 0;
  384. if (!low)
  385. high = (high + 1) >>> 0;
  386. return -(low + high * 4294967296);
  387. }
  388. return this.uint32s[1] + this.uint32s[0] * 4294967296;
  389. };
  390. Varint64.prototype.zzEncode = function () {
  391. var mask = this.uint32s[0] >> 31;
  392. this.uint32s[0] = (((this.uint32s[0] << 1) | (this.uint32s[1] >>> 31)) ^ mask) >>> 0;
  393. this.uint32s[1] = ((this.uint32s[1] << 1) ^ mask) >>> 0;
  394. return this;
  395. };
  396. Varint64.prototype.zzDecode = function () {
  397. var mask = -(this.uint32s[1] & 1);
  398. this.uint32s[1] = (((this.uint32s[1] >>> 1) | (this.uint32s[0] << 31)) ^ mask) >>> 0;
  399. this.uint32s[0] = ((this.uint32s[0] >>> 1) ^ mask) >>> 0;
  400. return this;
  401. };
  402. Object.defineProperty(Varint64.prototype, "byteLength", {
  403. get: function () {
  404. if (this._byteLength === undefined) {
  405. var part0 = this.uint32s[1], part1 = ((this.uint32s[1] >>> 28) | (this.uint32s[0] << 4)) >>> 0, part2 = this.uint32s[0] >>> 24;
  406. this._byteLength =
  407. part2 === 0
  408. ? part1 === 0
  409. ? part0 < 16384
  410. ? part0 < 128
  411. ? 1
  412. : 2
  413. : part0 < 2097152
  414. ? 3
  415. : 4
  416. : part1 < 16384
  417. ? part1 < 128
  418. ? 5
  419. : 6
  420. : part1 < 2097152
  421. ? 7
  422. : 8
  423. : part2 < 128
  424. ? 9
  425. : 10;
  426. }
  427. return this._byteLength;
  428. },
  429. enumerable: false,
  430. configurable: true
  431. });
  432. /**
  433. * 编码
  434. * @param buf
  435. * @param pos
  436. * @returns 编码后最新的pos
  437. */
  438. Varint64.prototype.writeToBuffer = function (buf, pos) {
  439. while (this.uint32s[0]) {
  440. buf[pos++] = (this.uint32s[1] & 127) | 128;
  441. this.uint32s[1] = ((this.uint32s[1] >>> 7) | (this.uint32s[0] << 25)) >>> 0;
  442. this.uint32s[0] >>>= 7;
  443. }
  444. while (this.uint32s[1] > 127) {
  445. buf[pos++] = (this.uint32s[1] & 127) | 128;
  446. this.uint32s[1] = this.uint32s[1] >>> 7;
  447. }
  448. buf[pos++] = this.uint32s[1];
  449. return pos;
  450. };
  451. Varint64.readFromBuffer = function (buf, pos) {
  452. var startPos = pos;
  453. var hi = 0, lo = 0;
  454. var i = 0;
  455. if (buf.byteLength - pos > 4) {
  456. // fast route (lo)
  457. for (; i < 4; ++i) {
  458. // 1st..4th
  459. lo = (lo | ((buf[pos] & 127) << (i * 7))) >>> 0;
  460. if (buf[pos++] < 128)
  461. return new Varint64(hi, lo, pos - startPos);
  462. }
  463. // 5th
  464. lo = (lo | ((buf[pos] & 127) << 28)) >>> 0;
  465. hi = (hi | ((buf[pos] & 127) >> 4)) >>> 0;
  466. if (buf[pos++] < 128)
  467. return new Varint64(hi, lo, pos - startPos);
  468. i = 0;
  469. }
  470. else {
  471. for (; i < 3; ++i) {
  472. /* istanbul ignore if */
  473. if (pos >= buf.byteLength)
  474. throw new Error("Read varint error: index out of range");
  475. // 1st..3th
  476. lo = (lo | ((buf[pos] & 127) << (i * 7))) >>> 0;
  477. if (buf[pos++] < 128)
  478. return new Varint64(hi, lo, pos - startPos);
  479. }
  480. // 4th
  481. lo = (lo | ((buf[pos++] & 127) << (i * 7))) >>> 0;
  482. return new Varint64(hi, lo, pos - startPos);
  483. }
  484. if (buf.byteLength - pos > 4) {
  485. // fast route (hi)
  486. for (; i < 5; ++i) {
  487. // 6th..10th
  488. hi = (hi | ((buf[pos] & 127) << (i * 7 + 3))) >>> 0;
  489. if (buf[pos++] < 128)
  490. return new Varint64(hi, lo, pos - startPos);
  491. }
  492. }
  493. else {
  494. for (; i < 5; ++i) {
  495. /* istanbul ignore if */
  496. if (pos >= buf.byteLength)
  497. throw new Error("Read varint error: index out of range");
  498. // 6th..10th
  499. hi = (hi | ((buf[pos] & 127) << (i * 7 + 3))) >>> 0;
  500. if (buf[pos++] < 128)
  501. return new Varint64(hi, lo, pos - startPos);
  502. }
  503. }
  504. /* istanbul ignore next */
  505. throw Error("invalid varint encoding");
  506. };
  507. Varint64.Zero = new Varint64(0, 0);
  508. return Varint64;
  509. }());
  510. var BufferReader = /** @class */ (function () {
  511. function BufferReader() {
  512. this._pos = 0;
  513. }
  514. BufferReader.prototype.load = function (buf, pos) {
  515. if (pos === void 0) { pos = 0; }
  516. this._buf = buf;
  517. this._pos = pos;
  518. this._view = new DataView(buf.buffer);
  519. };
  520. BufferReader.prototype.readVarint = function () {
  521. var varint = Varint64.readFromBuffer(this._buf, this._pos);
  522. this._pos += varint.byteLength;
  523. return varint;
  524. };
  525. BufferReader.prototype.readUint = function () {
  526. return this.readVarint().toNumber(true);
  527. };
  528. BufferReader.prototype.readInt = function () {
  529. return this.readVarint().zzDecode().toNumber();
  530. };
  531. BufferReader.prototype.readDouble = function () {
  532. var pos = this._pos;
  533. this._pos += 8;
  534. return this._view.getFloat64(this._buf.byteOffset + pos);
  535. };
  536. BufferReader.prototype.readString = function () {
  537. var strByteLength = this.readUint();
  538. var str = Utf8Coder.read(this._buf, this._pos, strByteLength);
  539. this._pos += strByteLength;
  540. return str;
  541. };
  542. BufferReader.prototype.readBuffer = function () {
  543. var bufByteLength = this.readUint();
  544. var buf = this._buf.subarray(this._pos, this._pos + bufByteLength);
  545. this._pos += bufByteLength;
  546. return buf;
  547. };
  548. BufferReader.prototype.skip = function (byteLength) {
  549. this._pos += byteLength;
  550. };
  551. BufferReader.prototype.skipByLengthType = function (lengthType) {
  552. if (lengthType === LengthType.Bit64) {
  553. this._pos += 8;
  554. }
  555. else if (lengthType === LengthType.Varint) {
  556. this.readVarint();
  557. }
  558. else if (lengthType === LengthType.LengthDelimited) {
  559. var bufByteLength = this.readUint();
  560. this._pos += bufByteLength;
  561. }
  562. else if (lengthType === LengthType.IdBlock) {
  563. this.skipIdBlock();
  564. }
  565. else {
  566. throw new Error("Unknown lengthType: " + lengthType);
  567. }
  568. };
  569. BufferReader.prototype.skipIdBlock = function () {
  570. var idNum = this.readUint();
  571. for (var i = 0; i < idNum; ++i) {
  572. var id = this.readUint();
  573. var lengthType = id & 3;
  574. this.skipByLengthType(lengthType);
  575. }
  576. };
  577. BufferReader.prototype.readBoolean = function () {
  578. var value = this._view.getUint8(this._buf.byteOffset + this._pos++);
  579. if (value === 255) {
  580. return true;
  581. }
  582. else if (value === 0) {
  583. return false;
  584. }
  585. else {
  586. throw new Error("Invalid boolean encoding [".concat(value, "] at pos ").concat(this._pos - 1));
  587. }
  588. };
  589. Object.defineProperty(BufferReader.prototype, "unreadByteLength", {
  590. get: function () {
  591. return this._buf.byteLength - this._pos;
  592. },
  593. enumerable: false,
  594. configurable: true
  595. });
  596. BufferReader.prototype.dispose = function () {
  597. this._buf = this._view = undefined;
  598. };
  599. return BufferReader;
  600. }());
  601. /** @internal */
  602. var Decoder = /** @class */ (function () {
  603. function Decoder(options) {
  604. this._options = options;
  605. this._reader = new BufferReader();
  606. this._validator = options.validator;
  607. }
  608. Decoder.prototype.decode = function (buffer, schema) {
  609. this._reader.load(buffer);
  610. return this._read(schema);
  611. };
  612. Decoder.prototype.decodeJSON = function (json, schema) {
  613. var _this = this;
  614. if (json === null ||
  615. CoderUtil.isJsonCompatible(schema, "decode", this._validator.protoHelper)) {
  616. return json;
  617. }
  618. // 递归 只处理 ArrayBuffer、Date、ObjectId
  619. switch (schema.type) {
  620. case tsbufferSchema.SchemaType.Array:
  621. if (!Array.isArray(json)) {
  622. break;
  623. }
  624. return json.map(function (v) { return _this.decodeJSON(v, schema.elementType); });
  625. case tsbufferSchema.SchemaType.Tuple:
  626. if (!Array.isArray(json)) {
  627. break;
  628. }
  629. return json.map(function (v, i) { return _this.decodeJSON(v, schema.elementTypes[i]); });
  630. case tsbufferSchema.SchemaType.Interface:
  631. if (json.constructor !== Object) {
  632. break;
  633. }
  634. json = Object.assign({}, json);
  635. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  636. var _loop_1 = function (key) {
  637. var property = flatSchema.properties.find(function (v) { return v.name === key; });
  638. if (property) {
  639. json[key] = this_1.decodeJSON(json[key], property.type);
  640. }
  641. else if (flatSchema.indexSignature) {
  642. json[key] = this_1.decodeJSON(json[key], flatSchema.indexSignature.type);
  643. }
  644. };
  645. var this_1 = this;
  646. for (var key in json) {
  647. _loop_1(key);
  648. }
  649. return json;
  650. case tsbufferSchema.SchemaType.Date:
  651. if (typeof json !== "string" && typeof json !== "number") {
  652. break;
  653. }
  654. return new Date(json);
  655. case tsbufferSchema.SchemaType.Partial:
  656. case tsbufferSchema.SchemaType.Pick:
  657. case tsbufferSchema.SchemaType.Omit:
  658. case tsbufferSchema.SchemaType.Overwrite:
  659. var parsed = this._validator.protoHelper.parseMappedType(schema);
  660. if (parsed.type === tsbufferSchema.SchemaType.Interface) {
  661. if (json.constructor !== Object) {
  662. break;
  663. }
  664. json = Object.assign({}, json);
  665. var flatSchema_1 = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  666. var _loop_2 = function (key) {
  667. var property = flatSchema_1.properties.find(function (v) { return v.name === key; });
  668. if (property) {
  669. json[key] = this_2.decodeJSON(json[key], property.type);
  670. }
  671. else if (flatSchema_1.indexSignature) {
  672. json[key] = this_2.decodeJSON(json[key], flatSchema_1.indexSignature.type);
  673. }
  674. };
  675. var this_2 = this;
  676. for (var key in json) {
  677. _loop_2(key);
  678. }
  679. return json;
  680. }
  681. else if (parsed.type === tsbufferSchema.SchemaType.Union || parsed.type === tsbufferSchema.SchemaType.Intersection) {
  682. for (var _i = 0, _a = parsed.members; _i < _a.length; _i++) {
  683. var member = _a[_i];
  684. json = this.decodeJSON(json, member.type);
  685. }
  686. return json;
  687. }
  688. break;
  689. case tsbufferSchema.SchemaType.Buffer:
  690. if (typeof json !== "string") {
  691. break;
  692. }
  693. var uint8Arr = Base64Util.base64ToBuffer(json);
  694. return this._getBufferValue(uint8Arr, schema);
  695. case tsbufferSchema.SchemaType.IndexedAccess:
  696. case tsbufferSchema.SchemaType.Reference:
  697. case tsbufferSchema.SchemaType.Keyof:
  698. return this.decodeJSON(json, this._validator.protoHelper.parseReference(schema));
  699. case tsbufferSchema.SchemaType.Union:
  700. case tsbufferSchema.SchemaType.Intersection: {
  701. // 逐个编码 然后合并 (失败的会原值返回,所以不影响结果)
  702. for (var _b = 0, _c = schema.members; _b < _c.length; _b++) {
  703. var member = _c[_b];
  704. json = this.decodeJSON(json, member.type);
  705. }
  706. return json;
  707. }
  708. case tsbufferSchema.SchemaType.NonNullable:
  709. return this.decodeJSON(json, schema.target);
  710. case tsbufferSchema.SchemaType.Custom:
  711. if (schema.decodeJSON) {
  712. return schema.decodeJSON(json);
  713. }
  714. break;
  715. default:
  716. schema.type;
  717. }
  718. return json;
  719. };
  720. Decoder.prototype._read = function (schema) {
  721. switch (schema.type) {
  722. case tsbufferSchema.SchemaType.Boolean:
  723. return this._reader.readBoolean();
  724. case tsbufferSchema.SchemaType.Number:
  725. return this._readNumber(schema);
  726. case tsbufferSchema.SchemaType.String:
  727. return this._reader.readString();
  728. case tsbufferSchema.SchemaType.Array: {
  729. var output = [];
  730. // 数组长度:Varint
  731. var length_1 = this._reader.readUint();
  732. for (var i = 0; i < length_1; ++i) {
  733. var item = this._read(schema.elementType);
  734. output.push(item);
  735. }
  736. return output;
  737. }
  738. case tsbufferSchema.SchemaType.Tuple: {
  739. if (schema.elementTypes.length > 64) {
  740. throw new Error("Elements oversized, maximum supported tuple elements is 64, now get " +
  741. schema.elementTypes.length);
  742. }
  743. var output = [];
  744. // PayloadMask: Varint64
  745. var payloadMask = this._reader.readVarint();
  746. // 计算maskIndices
  747. var maskIndices = [];
  748. // Low
  749. for (var i = 0; i < 32; ++i) {
  750. if (payloadMask.uint32s[1] & (1 << i)) {
  751. maskIndices.push(i);
  752. }
  753. }
  754. // High
  755. for (var i = 0; i < 32; ++i) {
  756. if (payloadMask.uint32s[0] & (1 << i)) {
  757. maskIndices.push(i + 32);
  758. }
  759. }
  760. if (!maskIndices.length) {
  761. return [];
  762. }
  763. var maxIndex = maskIndices.last();
  764. for (var i = 0, nextMaskIndex = 0, next = maskIndices[0]; i <= maxIndex; ++i) {
  765. if (i === next) {
  766. output[i] = this._read(schema.elementTypes[i]);
  767. ++nextMaskIndex;
  768. next = maskIndices[nextMaskIndex];
  769. }
  770. else {
  771. output[i] = undefined;
  772. }
  773. }
  774. // undefined as null
  775. for (var i = 0; i < schema.elementTypes.length; ++i) {
  776. if (this._undefinedAsNull(output[i], schema.elementTypes[i], schema.optionalStartIndex !== undefined && i >= schema.optionalStartIndex)) {
  777. output[i] = null;
  778. }
  779. }
  780. return output;
  781. }
  782. case tsbufferSchema.SchemaType.Enum:
  783. var enumId_1 = this._reader.readVarint().toNumber();
  784. var enumItem = schema.members.find(function (v) { return v.id === enumId_1; });
  785. if (!enumItem) {
  786. throw new Error("Invalid enum encoding: unexpected id ".concat(enumId_1));
  787. }
  788. return enumItem.value;
  789. case tsbufferSchema.SchemaType.Any:
  790. case tsbufferSchema.SchemaType.Object:
  791. var jsonStr = this._reader.readString();
  792. if (jsonStr === "undefined") {
  793. return undefined;
  794. }
  795. return JSON.parse(jsonStr);
  796. case tsbufferSchema.SchemaType.Literal:
  797. return schema.literal;
  798. case tsbufferSchema.SchemaType.Interface:
  799. return this._readInterface(schema);
  800. case tsbufferSchema.SchemaType.Buffer:
  801. var uint8Arr = this._reader.readBuffer();
  802. return this._getBufferValue(uint8Arr, schema);
  803. case tsbufferSchema.SchemaType.IndexedAccess:
  804. case tsbufferSchema.SchemaType.Reference:
  805. case tsbufferSchema.SchemaType.Keyof:
  806. return this._read(this._validator.protoHelper.parseReference(schema));
  807. case tsbufferSchema.SchemaType.Partial:
  808. case tsbufferSchema.SchemaType.Pick:
  809. case tsbufferSchema.SchemaType.Omit:
  810. case tsbufferSchema.SchemaType.Overwrite:
  811. var parsed = this._validator.protoHelper.parseMappedType(schema);
  812. if (parsed.type === tsbufferSchema.SchemaType.Interface) {
  813. return this._readPureMappedType(schema);
  814. }
  815. else {
  816. return this._readUnionOrIntersection(parsed);
  817. }
  818. case tsbufferSchema.SchemaType.Union:
  819. case tsbufferSchema.SchemaType.Intersection:
  820. return this._readUnionOrIntersection(schema);
  821. case tsbufferSchema.SchemaType.Date:
  822. return new Date(this._reader.readUint());
  823. case tsbufferSchema.SchemaType.NonNullable:
  824. return this._read(schema.target);
  825. case tsbufferSchema.SchemaType.Custom:
  826. if (!schema.decode) {
  827. throw new Error("Missing decode method for CustomTypeSchema");
  828. }
  829. var buf = this._reader.readBuffer();
  830. return schema.decode(buf);
  831. default:
  832. // @ts-expect-error
  833. throw new Error("Unrecognized schema type: ".concat(schema.type));
  834. }
  835. };
  836. /**
  837. * PureMappedType 每一层的target 都是MappedType或Interface(最终层)
  838. */
  839. Decoder.prototype._readPureMappedType = function (schema) {
  840. var output;
  841. var overwrite;
  842. if (schema.type === "Overwrite") {
  843. // Overwrite Block
  844. overwrite = this._read(schema.overwrite);
  845. }
  846. var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
  847. if (parsedTarget.type === "Interface") {
  848. output = this._readInterface(parsedTarget);
  849. }
  850. else if (parsedTarget.type === "Pick" ||
  851. parsedTarget.type === "Omit" ||
  852. parsedTarget.type === "Partial" ||
  853. parsedTarget.type === "Overwrite") {
  854. output = this._readPureMappedType(parsedTarget);
  855. }
  856. else {
  857. throw new Error("Invalid PureMappedType child: " + schema.type);
  858. }
  859. // filter key
  860. if (schema.type === "Pick") {
  861. // 把Pick以外的剔除
  862. for (var key in output) {
  863. if (schema.keys.indexOf(key) === -1) {
  864. delete output[key];
  865. }
  866. }
  867. }
  868. else if (schema.type === "Omit") {
  869. // 剔除Omit
  870. for (var key in output) {
  871. if (schema.keys.indexOf(key) > -1) {
  872. delete output[key];
  873. }
  874. }
  875. }
  876. else if (schema.type === "Overwrite") {
  877. Object.assign(output, overwrite);
  878. }
  879. // Partial 原样返回
  880. return output;
  881. };
  882. Decoder.prototype._readNumber = function (schema) {
  883. // 默认为double
  884. var scalarType = schema.scalarType || "double";
  885. switch (scalarType) {
  886. // 定长编码
  887. case "double":
  888. return this._reader.readDouble();
  889. // Varint编码
  890. case "int":
  891. return this._reader.readInt();
  892. case "uint":
  893. return this._reader.readUint();
  894. default:
  895. throw new Error("Scalar type not support : " + scalarType);
  896. }
  897. };
  898. Decoder.prototype._readInterface = function (schema) {
  899. var output = {};
  900. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  901. // BlockID数量
  902. var blockIdNum = this._reader.readUint();
  903. var _loop_3 = function (i) {
  904. // ReadBlock
  905. var readBlockId = this_3._reader.readUint();
  906. var lengthType = readBlockId & 3;
  907. var blockId = readBlockId >> 2;
  908. // indexSignature
  909. if (blockId === 0) {
  910. if (flatSchema.indexSignature) {
  911. var type = flatSchema.indexSignature.type;
  912. var fieldName = this_3._reader.readString();
  913. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(type));
  914. output[fieldName] = this_3._read(type);
  915. }
  916. // indexSignature未定义,可能是新协议,此处兼容,根据lengthType跳过
  917. else {
  918. // skip fieldName
  919. this_3._reader.skipByLengthType(LengthType.LengthDelimited);
  920. // skipPayload
  921. this_3._reader.skipByLengthType(lengthType);
  922. }
  923. }
  924. // extend block
  925. else if (blockId <= 9) {
  926. var extendId_1 = blockId - 1;
  927. var extend = schema.extends && schema.extends.find(function (v) { return v.id === extendId_1; });
  928. if (extend) {
  929. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(extend.type));
  930. var extendValue = this_3._read(extend.type);
  931. Object.assign(output, extendValue);
  932. }
  933. // 未知的extendId 可能是新协议 跳过
  934. else {
  935. // skipPayload
  936. this_3._reader.skipByLengthType(lengthType);
  937. }
  938. }
  939. // property
  940. else {
  941. var propertyId_1 = blockId - 10;
  942. var property = schema.properties && schema.properties.find(function (v) { return v.id === propertyId_1; });
  943. if (property) {
  944. this_3._skipIdLengthPrefix(this_3._validator.protoHelper.parseReference(property.type));
  945. output[property.name] = this_3._read(property.type);
  946. }
  947. // 未知的PropertyID 可能是新协议 跳过
  948. else {
  949. // skipPayload
  950. this_3._reader.skipByLengthType(lengthType);
  951. }
  952. }
  953. };
  954. var this_3 = this;
  955. for (var i = 0; i < blockIdNum; ++i) {
  956. _loop_3();
  957. }
  958. // Literal property 由于不编码 将其补回
  959. // undefined as null
  960. for (var _i = 0, _a = flatSchema.properties; _i < _a.length; _i++) {
  961. var property = _a[_i];
  962. if (output.hasOwnProperty(property.name)) {
  963. continue;
  964. }
  965. // Literal
  966. var parsedType = this._validator.protoHelper.parseReference(property.type);
  967. if (parsedType.type === "Literal") {
  968. output[property.name] = parsedType.literal;
  969. continue;
  970. }
  971. // undefined as null
  972. if (this._undefinedAsNull(output[property.name], parsedType, property.optional)) {
  973. output[property.name] = null;
  974. continue;
  975. }
  976. }
  977. return output;
  978. };
  979. /** @internal 是否该null值小于当做undefined编码 */
  980. Decoder.prototype._undefinedAsNull = function (value, type, isOptional) {
  981. return (value === undefined &&
  982. this._options.undefinedAsNull &&
  983. !SchemaUtil.canBeLiteral(type, undefined) &&
  984. !isOptional &&
  985. SchemaUtil.canBeLiteral(type, null));
  986. };
  987. Decoder.prototype._skipIdLengthPrefix = function (parsedSchema) {
  988. var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
  989. if (lengthInfo.needLengthPrefix) {
  990. // skip length prefix
  991. this._reader.skipByLengthType(LengthType.Varint);
  992. }
  993. };
  994. Decoder.prototype._readUnionOrIntersection = function (schema) {
  995. var output;
  996. var idNum = this._reader.readUint();
  997. var _loop_4 = function (i) {
  998. var readId = this_4._reader.readUint();
  999. var lengthType = readId & 3;
  1000. var id = readId >> 2;
  1001. var member = schema.members.find(function (v) { return v.id === id; });
  1002. // 不可识别的Member,可能是新协议,跳过使兼容
  1003. if (!member) {
  1004. this_4._reader.skipByLengthType(lengthType);
  1005. return "continue";
  1006. }
  1007. this_4._skipIdLengthPrefix(this_4._validator.protoHelper.parseReference(member.type));
  1008. var value = this_4._read(member.type);
  1009. if (this_4._isObject(output) && this_4._isObject(value)) {
  1010. Object.assign(output, value);
  1011. }
  1012. else {
  1013. output = value;
  1014. }
  1015. };
  1016. var this_4 = this;
  1017. for (var i = 0; i < idNum; ++i) {
  1018. _loop_4();
  1019. }
  1020. if (this._undefinedAsNull(output, schema)) {
  1021. output = null;
  1022. }
  1023. return output;
  1024. };
  1025. Decoder.prototype._isObject = function (value) {
  1026. return typeof value === "object" && value !== null;
  1027. };
  1028. Decoder.prototype._getBufferValue = function (uint8Arr, schema) {
  1029. if (schema.arrayType) {
  1030. if (schema.arrayType === "BigInt64Array" || schema.arrayType === "BigUint64Array") {
  1031. throw new Error("Unsupported arrayType: " + schema.arrayType);
  1032. }
  1033. // Uint8Array 性能最高
  1034. else if (schema.arrayType === "Uint8Array") {
  1035. return uint8Arr;
  1036. }
  1037. // 其余TypedArray 可能需要内存拷贝 性能次之
  1038. else {
  1039. var typedArr = TypedArrays[schema.arrayType];
  1040. // 字节对齐,可以直接转,无需拷贝内存
  1041. if (uint8Arr.byteOffset % typedArr.BYTES_PER_ELEMENT === 0) {
  1042. return new typedArr(uint8Arr.buffer, uint8Arr.byteOffset, uint8Arr.byteLength / typedArr.BYTES_PER_ELEMENT);
  1043. }
  1044. // 字节不对齐,不能直接转,只能拷贝内存后再生成
  1045. else {
  1046. var arrBuf = uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
  1047. return new typedArr(arrBuf);
  1048. }
  1049. }
  1050. }
  1051. else {
  1052. return uint8Arr.byteLength === uint8Arr.buffer.byteLength && uint8Arr.byteOffset === 0
  1053. ? uint8Arr.buffer
  1054. : uint8Arr.buffer.slice(uint8Arr.byteOffset, uint8Arr.byteOffset + uint8Arr.byteLength);
  1055. }
  1056. };
  1057. return Decoder;
  1058. }());
  1059. /** @internal */
  1060. var Config = {
  1061. interface: {
  1062. maxExtendsNum: 9,
  1063. },
  1064. };
  1065. /**
  1066. * 用Op来串联 next
  1067. * Op包含 function next length
  1068. * 先度量长度再执行编码
  1069. * 一次性编码
  1070. * 使用BufferPool
  1071. * writer.uint32(xx).string(xxx).finish();
  1072. * @internal
  1073. */
  1074. var BufferWriter = /** @class */ (function () {
  1075. function BufferWriter() {
  1076. this._ops = [];
  1077. }
  1078. Object.defineProperty(BufferWriter.prototype, "ops", {
  1079. get: function () {
  1080. return this._ops;
  1081. },
  1082. enumerable: false,
  1083. configurable: true
  1084. });
  1085. BufferWriter.prototype.clear = function () {
  1086. this._ops = [];
  1087. };
  1088. BufferWriter.prototype.push = function (req) {
  1089. this._ops.push(this.req2op(req));
  1090. return this;
  1091. };
  1092. BufferWriter.prototype.req2op = function (req) {
  1093. if (req.type === "string" || req.type === "buffer") {
  1094. var valueLength = this.measureLength(req);
  1095. // Length
  1096. this.push({ type: "varint", value: Varint64.from(valueLength) });
  1097. // Value
  1098. return tslib.__assign(tslib.__assign({}, req), { length: valueLength });
  1099. }
  1100. else {
  1101. var length_1 = this.measureLength(req);
  1102. return tslib.__assign(tslib.__assign({}, req), { length: length_1 });
  1103. }
  1104. };
  1105. BufferWriter.prototype.measureLength = function (req) {
  1106. switch (req.type) {
  1107. case "varint":
  1108. return req.value.byteLength;
  1109. case "string":
  1110. return Utf8Coder.measureLength(req.value);
  1111. case "buffer":
  1112. return req.value.byteLength;
  1113. case "double":
  1114. return 8;
  1115. case "boolean":
  1116. return 1;
  1117. default:
  1118. return NaN;
  1119. }
  1120. };
  1121. BufferWriter.prototype.finish = function () {
  1122. var byteLength = this._ops.sum(function (v) { return v.length; });
  1123. var pos = 0;
  1124. var buf = new Uint8Array(byteLength);
  1125. var view = new DataView(buf.buffer);
  1126. for (var _i = 0, _a = this._ops; _i < _a.length; _i++) {
  1127. var op = _a[_i];
  1128. switch (op.type) {
  1129. case "varint":
  1130. var newPos = op.value.writeToBuffer(buf, pos);
  1131. if (newPos !== pos + op.length) {
  1132. throw new Error("Error varint measuredLength ".concat(op.length, ", actual is ").concat(newPos - pos, ", value is ").concat(op.value.toNumber()));
  1133. }
  1134. break;
  1135. case "double":
  1136. view.setFloat64(buf.byteOffset + pos, op.value);
  1137. break;
  1138. case "string":
  1139. var encLen = Utf8Coder.write(op.value, buf, pos);
  1140. if (encLen !== op.length) {
  1141. throw new Error("Expect ".concat(op.length, " bytes but encoded ").concat(encLen, " bytes"));
  1142. }
  1143. break;
  1144. case "buffer":
  1145. buf.subarray(pos, pos + op.length).set(op.value);
  1146. break;
  1147. case "boolean":
  1148. view.setUint8(buf.byteOffset + pos, op.value ? 255 : 0);
  1149. break;
  1150. }
  1151. pos += op.length;
  1152. }
  1153. return buf;
  1154. };
  1155. return BufferWriter;
  1156. }());
  1157. /** @internal */
  1158. var Encoder = /** @class */ (function () {
  1159. function Encoder(options) {
  1160. this._options = options;
  1161. this._writer = new BufferWriter();
  1162. this._validator = options.validator;
  1163. }
  1164. Encoder.prototype.encode = function (value, schema) {
  1165. this._writer.clear();
  1166. this._write(value, schema);
  1167. return this._writer.finish();
  1168. };
  1169. Encoder.prototype.encodeJSON = function (value, schema) {
  1170. var _this = this;
  1171. // JSON 能直接传输的类型,直接跳过
  1172. if (typeof value !== "object" ||
  1173. value === null ||
  1174. CoderUtil.isJsonCompatible(schema, "encode", this._validator.protoHelper)) {
  1175. return value;
  1176. }
  1177. switch (schema.type) {
  1178. case tsbufferSchema.SchemaType.Array:
  1179. if (!Array.isArray(value)) {
  1180. break;
  1181. }
  1182. return value.map(function (v) { return _this.encodeJSON(v, schema.elementType); });
  1183. case tsbufferSchema.SchemaType.Tuple: {
  1184. if (!Array.isArray(value)) {
  1185. break;
  1186. }
  1187. return value.map(function (v, i) { return _this.encodeJSON(v, schema.elementTypes[i]); });
  1188. }
  1189. case tsbufferSchema.SchemaType.Interface: {
  1190. if (value.constructor !== Object) {
  1191. break;
  1192. }
  1193. value = Object.assign({}, value);
  1194. var flatSchema = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  1195. var _loop_1 = function (key) {
  1196. var property = flatSchema.properties.find(function (v) { return v.name === key; });
  1197. if (property) {
  1198. value[key] = this_1.encodeJSON(value[key], property.type);
  1199. }
  1200. else if (flatSchema.indexSignature) {
  1201. value[key] = this_1.encodeJSON(value[key], flatSchema.indexSignature.type);
  1202. }
  1203. };
  1204. var this_1 = this;
  1205. for (var key in value) {
  1206. _loop_1(key);
  1207. }
  1208. return value;
  1209. }
  1210. case tsbufferSchema.SchemaType.Partial:
  1211. case tsbufferSchema.SchemaType.Pick:
  1212. case tsbufferSchema.SchemaType.Omit:
  1213. case tsbufferSchema.SchemaType.Overwrite:
  1214. var parsed = this._validator.protoHelper.parseMappedType(schema);
  1215. return this.encodeJSON(value, parsed);
  1216. case tsbufferSchema.SchemaType.Buffer:
  1217. if (!(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {
  1218. break;
  1219. }
  1220. if (schema.arrayType) {
  1221. if (schema.arrayType === "Uint8Array") {
  1222. return Base64Util.bufferToBase64(value);
  1223. }
  1224. var view = value;
  1225. var buf = view.byteLength === view.buffer.byteLength && view.byteOffset === 0
  1226. ? view.buffer
  1227. : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
  1228. return Base64Util.bufferToBase64(new Uint8Array(buf));
  1229. }
  1230. else {
  1231. return Base64Util.bufferToBase64(new Uint8Array(value));
  1232. }
  1233. case tsbufferSchema.SchemaType.IndexedAccess:
  1234. case tsbufferSchema.SchemaType.Reference:
  1235. case tsbufferSchema.SchemaType.Keyof:
  1236. return this.encodeJSON(value, this._validator.protoHelper.parseReference(schema));
  1237. case tsbufferSchema.SchemaType.Union:
  1238. case tsbufferSchema.SchemaType.Intersection: {
  1239. // 逐个编码 然后合并 (失败的会原值返回,所以不影响结果)
  1240. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1241. var member = _a[_i];
  1242. value = this.encodeJSON(value, member.type);
  1243. }
  1244. return value;
  1245. }
  1246. case tsbufferSchema.SchemaType.NonNullable:
  1247. return this.encodeJSON(value, schema.target);
  1248. case tsbufferSchema.SchemaType.Date:
  1249. if (!(value instanceof Date)) {
  1250. break;
  1251. }
  1252. return value.toJSON();
  1253. case tsbufferSchema.SchemaType.Custom:
  1254. if (schema.encodeJSON) {
  1255. return schema.encodeJSON(value);
  1256. }
  1257. else if (typeof (value === null || value === void 0 ? void 0 : value.toJSON) === "function") {
  1258. return value.toJSON();
  1259. }
  1260. else if (typeof (value === null || value === void 0 ? void 0 : value.toString) === "function") {
  1261. return value.toString();
  1262. }
  1263. return value;
  1264. default:
  1265. schema.type;
  1266. }
  1267. return value;
  1268. };
  1269. Encoder.prototype._write = function (value, schema, options) {
  1270. switch (schema.type) {
  1271. case tsbufferSchema.SchemaType.Boolean:
  1272. this._writer.push({ type: "boolean", value: value });
  1273. break;
  1274. case tsbufferSchema.SchemaType.Number:
  1275. this._writeNumber(value, schema);
  1276. break;
  1277. case tsbufferSchema.SchemaType.String:
  1278. this._writer.push({ type: "string", value: value });
  1279. break;
  1280. case tsbufferSchema.SchemaType.Array: {
  1281. var _v = value;
  1282. // 数组长度:Varint
  1283. this._writer.push({ type: "varint", value: Varint64.from(_v.length) });
  1284. // Element Payload
  1285. for (var i = 0; i < _v.length; ++i) {
  1286. this._write(_v[i], schema.elementType);
  1287. }
  1288. break;
  1289. }
  1290. case tsbufferSchema.SchemaType.Tuple: {
  1291. if (schema.elementTypes.length > 64) {
  1292. throw new Error("Elements oversized, maximum supported tuple elements is 64, now get " +
  1293. schema.elementTypes.length);
  1294. }
  1295. var _v = value;
  1296. // 计算maskPos(要编码的值的index)
  1297. var maskIndices = [];
  1298. for (var i = 0; i < _v.length; ++i) {
  1299. // undefined 不编码
  1300. // null as undefined
  1301. if (_v[i] === undefined || this._nullAsUndefined(_v[i], schema.elementTypes[i])) {
  1302. continue;
  1303. }
  1304. maskIndices.push(i);
  1305. }
  1306. // 生成PayloadMask:Varint64
  1307. var lo = 0;
  1308. var hi = 0;
  1309. for (var _i = 0, maskIndices_1 = maskIndices; _i < maskIndices_1.length; _i++) {
  1310. var v = maskIndices_1[_i];
  1311. if (v < 32) {
  1312. lo |= 1 << v;
  1313. }
  1314. else {
  1315. hi |= 1 << (v - 32);
  1316. }
  1317. }
  1318. this._writer.push({ type: "varint", value: new Varint64(hi, lo) });
  1319. // Element Payload
  1320. for (var _a = 0, maskIndices_2 = maskIndices; _a < maskIndices_2.length; _a++) {
  1321. var i = maskIndices_2[_a];
  1322. this._write(_v[i], schema.elementTypes[i]);
  1323. }
  1324. break;
  1325. }
  1326. case tsbufferSchema.SchemaType.Enum:
  1327. var enumItem = schema.members.find(function (v) { return v.value === value; });
  1328. if (!enumItem) {
  1329. throw new Error("Unexpect enum value: ".concat(value));
  1330. }
  1331. this._writer.push({ type: "varint", value: Varint64.from(enumItem.id) });
  1332. break;
  1333. case tsbufferSchema.SchemaType.Any:
  1334. if (value === undefined) {
  1335. this._writer.push({ type: "string", value: "undefined" });
  1336. }
  1337. else {
  1338. this._writer.push({ type: "string", value: JSON.stringify(value) });
  1339. }
  1340. break;
  1341. case tsbufferSchema.SchemaType.Object:
  1342. this._writer.push({ type: "string", value: JSON.stringify(value) });
  1343. break;
  1344. case tsbufferSchema.SchemaType.Literal:
  1345. break;
  1346. case tsbufferSchema.SchemaType.Interface:
  1347. this._writeInterface(value, schema, options);
  1348. break;
  1349. case tsbufferSchema.SchemaType.Buffer:
  1350. this._writeBuffer(value);
  1351. break;
  1352. case tsbufferSchema.SchemaType.IndexedAccess:
  1353. case tsbufferSchema.SchemaType.Reference:
  1354. case tsbufferSchema.SchemaType.Keyof:
  1355. this._write(value, this._validator.protoHelper.parseReference(schema), options);
  1356. break;
  1357. case tsbufferSchema.SchemaType.Partial:
  1358. case tsbufferSchema.SchemaType.Pick:
  1359. case tsbufferSchema.SchemaType.Omit:
  1360. case tsbufferSchema.SchemaType.Overwrite:
  1361. var parsed = this._validator.protoHelper.parseMappedType(schema);
  1362. if (parsed.type === tsbufferSchema.SchemaType.Interface) {
  1363. this._writePureMappedType(value, schema, options);
  1364. }
  1365. else if (parsed.type === tsbufferSchema.SchemaType.Union) {
  1366. this._writeUnion(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
  1367. }
  1368. else if (parsed.type === tsbufferSchema.SchemaType.Intersection) {
  1369. this._writeIntersection(value, parsed, options === null || options === void 0 ? void 0 : options.skipFields);
  1370. }
  1371. break;
  1372. case tsbufferSchema.SchemaType.Union:
  1373. this._writeUnion(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
  1374. break;
  1375. case tsbufferSchema.SchemaType.Intersection:
  1376. this._writeIntersection(value, schema, options === null || options === void 0 ? void 0 : options.skipFields);
  1377. break;
  1378. case tsbufferSchema.SchemaType.Date:
  1379. this._writer.push({ type: "varint", value: Varint64.from(value.getTime()) });
  1380. break;
  1381. case tsbufferSchema.SchemaType.NonNullable:
  1382. this._write(value, schema.target, options);
  1383. break;
  1384. case tsbufferSchema.SchemaType.Custom:
  1385. if (!schema.encode) {
  1386. throw new Error("Missing encode method for CustomTypeSchema");
  1387. }
  1388. var buf = schema.encode(value);
  1389. // 以 Buffer 形式写入
  1390. this._writeBuffer(buf);
  1391. break;
  1392. default:
  1393. // @ts-expect-error
  1394. throw new Error("Unrecognized schema type: ".concat(schema.type));
  1395. }
  1396. };
  1397. Encoder.prototype._writePureMappedType = function (value, schema, options) {
  1398. if (!options) {
  1399. options = {};
  1400. }
  1401. if (schema.type === "Pick") {
  1402. // 已存在 取交集
  1403. if (options.pickFields) {
  1404. var newPickFields = {};
  1405. for (var _i = 0, _a = schema.keys; _i < _a.length; _i++) {
  1406. var v = _a[_i];
  1407. if (options.pickFields[v]) {
  1408. newPickFields[v] = 1;
  1409. }
  1410. }
  1411. options.pickFields = newPickFields;
  1412. }
  1413. // 不存在 初始化
  1414. else {
  1415. options.pickFields = {};
  1416. for (var _b = 0, _c = schema.keys; _b < _c.length; _b++) {
  1417. var v = _c[_b];
  1418. options.pickFields[v] = 1;
  1419. }
  1420. }
  1421. }
  1422. else if (schema.type === "Omit") {
  1423. // 不存在 初始化
  1424. if (!(options === null || options === void 0 ? void 0 : options.skipFields)) {
  1425. if (!options) {
  1426. options = {};
  1427. }
  1428. options.skipFields = {};
  1429. }
  1430. // 取并集
  1431. for (var _d = 0, _e = schema.keys; _d < _e.length; _d++) {
  1432. var v = _e[_d];
  1433. options.skipFields[v] = 1;
  1434. }
  1435. }
  1436. else if (schema.type === "Overwrite") {
  1437. var parsed = this._parseOverwrite(value, schema);
  1438. // 写入Overwrite部分
  1439. this._write(parsed.overwriteValue, parsed.overwrite, options);
  1440. }
  1441. else if (schema.type === "Partial") ;
  1442. else {
  1443. // @ts-expect-error
  1444. throw new Error("Invalid PureMappedType child: " + schema.type);
  1445. }
  1446. // Write Interface
  1447. var parsedTarget = this._validator.protoHelper.parseReference(schema.target);
  1448. if (parsedTarget.type === "Interface") {
  1449. this._writeInterface(value, parsedTarget, options);
  1450. }
  1451. else {
  1452. this._writePureMappedType(value, parsedTarget, options);
  1453. }
  1454. };
  1455. Encoder.prototype._writeNumber = function (value, schema) {
  1456. // 默认为double
  1457. var scalarType = schema.scalarType || "double";
  1458. switch (scalarType) {
  1459. // 定长编码
  1460. case "double":
  1461. this._writer.push({ type: scalarType, value: value });
  1462. break;
  1463. // Varint编码
  1464. case "int":
  1465. this._writer.push({ type: "varint", value: Varint64.from(value).zzEncode() });
  1466. break;
  1467. case "uint":
  1468. this._writer.push({ type: "varint", value: Varint64.from(value) });
  1469. break;
  1470. default:
  1471. throw new Error("Scalar type not support : " + scalarType);
  1472. }
  1473. };
  1474. Encoder.prototype._writeInterface = function (value, schema, options) {
  1475. // skipFields默认值
  1476. if (!options) {
  1477. options = {};
  1478. }
  1479. if (!options.skipFields) {
  1480. options.skipFields = {};
  1481. }
  1482. // 记录起始op位置,用于最后插入BlockID数量
  1483. var opStartOps = this._writer.ops.length;
  1484. var blockIdCount = 0;
  1485. // 以下,interface
  1486. // extends
  1487. if (schema.extends) {
  1488. // 支持的继承数量有上限
  1489. if (schema.extends.length > Config.interface.maxExtendsNum) {
  1490. throw new Error("Max support ".concat(Config.interface.maxExtendsNum, " extends, actual: ").concat(schema.extends.length));
  1491. }
  1492. for (var _i = 0, _a = schema.extends; _i < _a.length; _i++) {
  1493. var extend = _a[_i];
  1494. // BlockID = extend.id + 1
  1495. var blockId = extend.id + 1;
  1496. this._writer.push({ type: "varint", value: Varint64.from(blockId) });
  1497. var blockIdPos = this._writer.ops.length - 1;
  1498. // 写入extend interface前 writeOps的长度
  1499. var opsLengthBeforeWrite = this._writer.ops.length;
  1500. // extend Block
  1501. var parsedExtend = this._validator.protoHelper.parseReference(extend.type);
  1502. this._writeInterface(value, parsedExtend, tslib.__assign(tslib.__assign({}, options), {
  1503. // 确保indexSignature是在最小层级编码
  1504. skipIndexSignature: !!schema.indexSignature || options.skipIndexSignature }));
  1505. // 写入前后writeOps只增加了一个(block length),说明该extend并未写入任何property字段,取消编码这个block
  1506. if (this._writer.ops.length === opsLengthBeforeWrite + 1) {
  1507. // 移除BlockID
  1508. this._writer.ops.splice(this._writer.ops.length - 2, 2);
  1509. }
  1510. // extend写入成功 blockId数量+1
  1511. else {
  1512. ++blockIdCount;
  1513. this._processIdWithLengthType(blockIdPos, extend.type);
  1514. }
  1515. }
  1516. }
  1517. // property
  1518. if (schema.properties) {
  1519. for (var _b = 0, _c = schema.properties; _b < _c.length; _b++) {
  1520. var property = _c[_b];
  1521. var parsedType = this._validator.protoHelper.parseReference(property.type);
  1522. var propValue = value[property.name];
  1523. // PickFields
  1524. if (options.pickFields && !options.pickFields[property.name]) {
  1525. continue;
  1526. }
  1527. // Literal不编码 直接跳过
  1528. if (parsedType.type === "Literal") {
  1529. options.skipFields[property.name] = 1;
  1530. continue;
  1531. }
  1532. // null as undefined
  1533. if (this._nullAsUndefined(propValue, property.type)) {
  1534. propValue = undefined;
  1535. }
  1536. // undefined不编码
  1537. if (propValue === undefined) {
  1538. continue;
  1539. }
  1540. // SkipFields
  1541. if (options.skipFields[property.name]) {
  1542. continue;
  1543. }
  1544. options.skipFields[property.name] = 1;
  1545. var blockId = property.id + Config.interface.maxExtendsNum + 1;
  1546. // BlockID (propertyID)
  1547. this._writer.push({ type: "varint", value: Varint64.from(blockId) });
  1548. var blockIdPos = this._writer.ops.length - 1;
  1549. // Value Payload
  1550. this._write(propValue, parsedType);
  1551. ++blockIdCount;
  1552. this._processIdWithLengthType(blockIdPos, parsedType);
  1553. }
  1554. }
  1555. // indexSignature
  1556. if (!options.skipIndexSignature) {
  1557. var flat = this._validator.protoHelper.getFlatInterfaceSchema(schema);
  1558. if (flat.indexSignature) {
  1559. for (var key in value) {
  1560. if (value[key] === undefined ||
  1561. this._nullAsUndefined(value[key], flat.indexSignature.type)) {
  1562. continue;
  1563. }
  1564. // PickFields
  1565. if (options.pickFields && !options.pickFields[key]) {
  1566. continue;
  1567. }
  1568. // SkipFields
  1569. if (options.skipFields[key]) {
  1570. continue;
  1571. }
  1572. options.skipFields[key] = 1;
  1573. // BlockID == 0
  1574. this._writer.push({ type: "varint", value: Varint64.from(0) });
  1575. var blockIdPos = this._writer.ops.length - 1;
  1576. // 字段名
  1577. this._writer.push({ type: "string", value: key });
  1578. var lengthPrefixPos = this._writer.ops.length;
  1579. // Value Payload
  1580. this._write(value[key], flat.indexSignature.type);
  1581. ++blockIdCount;
  1582. this._processIdWithLengthType(blockIdPos, flat.indexSignature.type, lengthPrefixPos);
  1583. }
  1584. }
  1585. }
  1586. this._writer.ops.splice(opStartOps, 0, this._writer.req2op({ type: "varint", value: Varint64.from(blockIdCount) }));
  1587. };
  1588. /** @internal 是否该null值小于当做undefined编码 */
  1589. Encoder.prototype._nullAsUndefined = function (value, type) {
  1590. return value === null && this._options.nullAsUndefined && !SchemaUtil.canBeLiteral(type, null);
  1591. // && SchemaUtil.canBeLiteral(type, undefined) 一定为true 因为先validate过了
  1592. };
  1593. Encoder.prototype._parseOverwrite = function (value, schema) {
  1594. var skipFields = {};
  1595. // 解引用
  1596. var target = this._validator.protoHelper.parseReference(schema.target);
  1597. var overwrite = this._validator.protoHelper.parseReference(schema.overwrite);
  1598. var flatTarget = this._validator.protoHelper.getFlatInterfaceSchema(target);
  1599. var flatOverwrite = this._validator.protoHelper.getFlatInterfaceSchema(overwrite);
  1600. // 先区分哪些字段进入Target块,哪些字段进入Overwrite块
  1601. var overwriteValue = {};
  1602. var targetValue = {};
  1603. // Overwrite块 property
  1604. if (flatOverwrite.properties) {
  1605. // 只要Overwrite中有此Property,即在Overwrite块编码
  1606. for (var _i = 0, _a = flatOverwrite.properties; _i < _a.length; _i++) {
  1607. var property = _a[_i];
  1608. // undefined不编码,跳过SkipFIelds
  1609. if (value[property.name] !== undefined && !skipFields[property.name]) {
  1610. overwriteValue[property.name] = value[property.name];
  1611. skipFields[property.name] = 1;
  1612. }
  1613. }
  1614. }
  1615. // Target块 property
  1616. if (flatTarget.properties) {
  1617. for (var _b = 0, _c = flatTarget.properties; _b < _c.length; _b++) {
  1618. var property = _c[_b];
  1619. // undefined不编码,跳过SkipFields
  1620. if (value[property.name] !== undefined && !skipFields[property.name]) {
  1621. targetValue[property.name] = value[property.name];
  1622. skipFields[property.name] = 1;
  1623. }
  1624. }
  1625. }
  1626. // indexSignature
  1627. var indexSignatureWriteValue; // indexSignature要写入的目标(overwrite或target)
  1628. var indexSignature;
  1629. // IndexSignature,优先使用Overwrite的
  1630. if (flatOverwrite.indexSignature) {
  1631. indexSignature = flatOverwrite.indexSignature;
  1632. indexSignatureWriteValue = overwriteValue;
  1633. }
  1634. else if (flatTarget.indexSignature) {
  1635. indexSignature = flatTarget.indexSignature;
  1636. indexSignatureWriteValue = targetValue;
  1637. }
  1638. if (indexSignature) {
  1639. for (var key in value) {
  1640. if (skipFields[key]) {
  1641. continue;
  1642. }
  1643. indexSignatureWriteValue[key] = value[key];
  1644. skipFields[key] = 1;
  1645. }
  1646. }
  1647. // 编码,此处不再需要SkipFields,因为已经筛选过
  1648. return {
  1649. target: target,
  1650. targetValue: targetValue,
  1651. overwrite: overwrite,
  1652. overwriteValue: overwriteValue,
  1653. };
  1654. };
  1655. Encoder.prototype._writeUnion = function (value, schema, skipFields, unionProperties) {
  1656. // 计算unionProperties
  1657. // if (!unionProperties) {
  1658. // unionProperties = skipFields ? Object.keys(skipFields) : [];
  1659. // }
  1660. // this._validator.protoHelper.getUnionProperties(schema).forEach(v => {
  1661. // unionProperties!.binaryInsert(v, true);
  1662. // })
  1663. if (skipFields === void 0) { skipFields = {}; }
  1664. // 记住编码起点
  1665. var encodeStartPos = this._writer.ops.length;
  1666. var idNum = 0;
  1667. // null as undefined
  1668. if (this._nullAsUndefined(value, schema)) {
  1669. value = undefined;
  1670. }
  1671. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1672. var member = _a[_i];
  1673. // 验证该member是否可以编码
  1674. var vRes = this._validator.validate(value, member.type, {
  1675. // 禁用excessPropertyChecks(以代替unionProperties)
  1676. excessPropertyChecks: false,
  1677. // 启用strictNullChecks(null as undefined已经前置处理)
  1678. // strictNullChecks: true
  1679. });
  1680. if (vRes.isSucc) {
  1681. // 编码
  1682. // Part2: ID
  1683. this._writer.push({ type: "varint", value: Varint64.from(member.id) });
  1684. var idPos = this._writer.ops.length - 1;
  1685. // Part3: Payload
  1686. if (member.type.type === "Union") {
  1687. this._writeUnion(value, member.type, skipFields);
  1688. }
  1689. else {
  1690. this._write(value, member.type, {
  1691. skipFields: skipFields,
  1692. });
  1693. }
  1694. idNum++;
  1695. this._processIdWithLengthType(idPos, member.type);
  1696. // 非object的value,类型一定互斥,只编码一个足矣
  1697. if (typeof value !== "object") {
  1698. break;
  1699. }
  1700. }
  1701. }
  1702. // 已经编码
  1703. if (idNum > 0) {
  1704. // 前置ID数量
  1705. this._writer.ops.splice(encodeStartPos, 0, this._writer.req2op({ type: "varint", value: Varint64.from(idNum) }));
  1706. return;
  1707. }
  1708. else {
  1709. // 未编码,没有任何条件满足,抛出异常
  1710. throw new Error("Non member is satisfied for union type");
  1711. }
  1712. };
  1713. Encoder.prototype._writeIntersection = function (value, schema, skipFields) {
  1714. if (skipFields === void 0) { skipFields = {}; }
  1715. // ID数量(member数量)
  1716. this._writer.push({ type: "varint", value: Varint64.from(schema.members.length) });
  1717. // 按Member依次编码
  1718. for (var _i = 0, _a = schema.members; _i < _a.length; _i++) {
  1719. var member = _a[_i];
  1720. // ID
  1721. this._writer.push({ type: "varint", value: Varint64.from(member.id) });
  1722. var idPos = this._writer.ops.length - 1;
  1723. // 编码块 - 为每个 member 创建新的 skipFields
  1724. var memberSkipFields = tslib.__assign({}, skipFields);
  1725. this._write(value, member.type, {
  1726. skipFields: memberSkipFields,
  1727. });
  1728. this._processIdWithLengthType(idPos, member.type);
  1729. }
  1730. };
  1731. Encoder.prototype._writeBuffer = function (value) {
  1732. // ArrayBuffer 转为Uint8Array
  1733. if (value instanceof ArrayBuffer) {
  1734. this._writer.push({ type: "buffer", value: new Uint8Array(value) });
  1735. }
  1736. // Uint8Array 直接写入
  1737. else if (value instanceof Uint8Array) {
  1738. this._writer.push({ type: "buffer", value: value });
  1739. }
  1740. // 其它TypedArray 转为Uint8Array
  1741. else {
  1742. var key = value.constructor.name;
  1743. var arrType = TypedArrays[key];
  1744. var uint8Arr = new Uint8Array(value.buffer, value.byteOffset, value.length * arrType.BYTES_PER_ELEMENT);
  1745. this._writer.push({ type: "buffer", value: uint8Arr });
  1746. }
  1747. };
  1748. // private _writeIdBlocks(blocks: IDBlockItem[]) {
  1749. // // 字段数量: Varint
  1750. // this._writer.push({ type: 'varint', value: Varint64.from(blocks.length) });
  1751. // // 依次编码
  1752. // for (let item of blocks) {
  1753. // // ID
  1754. // this._writer.push({ type: 'varint', value: Varint64.from(item.id) });
  1755. // // Payload
  1756. // this._write(item.value, item.schema)
  1757. // }
  1758. // }
  1759. /**
  1760. * 重新处理ID位,使其加入末位长度信息2Bit
  1761. * @param idPos
  1762. */
  1763. Encoder.prototype._processIdWithLengthType = function (idPos, payloadType, lengthPrefixPos) {
  1764. var idOp = this._writer.ops[idPos];
  1765. if (idOp.type !== "varint") {
  1766. throw new Error("Error idPos: " + idPos);
  1767. }
  1768. // 解引用
  1769. var parsedSchema = this._validator.protoHelper.parseReference(payloadType);
  1770. var lengthInfo = IdBlockUtil.getPayloadLengthInfo(parsedSchema, this._validator.protoHelper);
  1771. var newId = (idOp.value.toNumber() << 2) + lengthInfo.lengthType;
  1772. this._writer.ops[idPos] = this._writer.req2op({
  1773. type: "varint",
  1774. value: Varint64.from(newId),
  1775. });
  1776. if (lengthInfo.needLengthPrefix) {
  1777. var payloadByteLength = this._writer.ops.filter(function (v, i) { return i > idPos; }).sum(function (v) { return v.length; });
  1778. this._writer.ops.splice(lengthPrefixPos == undefined ? idPos + 1 : lengthPrefixPos, 0, this._writer.req2op({
  1779. type: "varint",
  1780. value: Varint64.from(payloadByteLength),
  1781. }));
  1782. }
  1783. };
  1784. return Encoder;
  1785. }());
  1786. /**
  1787. * @public
  1788. */
  1789. var TSBuffer = /** @class */ (function () {
  1790. function TSBuffer(proto, options) {
  1791. /** @internal 默认配置 */
  1792. this._options = {
  1793. excessPropertyChecks: true,
  1794. strictNullChecks: false,
  1795. skipEncodeValidate: false,
  1796. skipDecodeValidate: false,
  1797. cloneProto: true,
  1798. };
  1799. // but `options.validatorOptions` has higher priority to validate process (don't affect encode)
  1800. this._options = tslib.__assign(tslib.__assign({}, this._options), options);
  1801. this._proto = this._options.cloneProto ? Object.merge({}, proto) : proto;
  1802. Object.assign(this._proto, Object.merge({}, options === null || options === void 0 ? void 0 : options.customTypes));
  1803. this._validator = new tsbufferValidator.TSBufferValidator(this._proto, {
  1804. excessPropertyChecks: this._options.excessPropertyChecks,
  1805. strictNullChecks: this._options.strictNullChecks,
  1806. cloneProto: false,
  1807. });
  1808. this.validate = this._validator.validate.bind(this._validator);
  1809. this.prune = this._validator.prune.bind(this._validator);
  1810. this._encoder = new Encoder({
  1811. validator: this._validator,
  1812. // if !strictNullChecks, then encoder can convert null to undefined
  1813. nullAsUndefined: !this._options.strictNullChecks,
  1814. });
  1815. this._decoder = new Decoder({
  1816. validator: this._validator,
  1817. // if !strictNullChecks, then decoder can convert undefined to null
  1818. undefinedAsNull: !this._options.strictNullChecks,
  1819. });
  1820. }
  1821. /**
  1822. * 编码
  1823. * @param value - 要编码的值
  1824. * @param schemaOrId - Schema 或 SchemaID,例如`a/b.ts`下的`Test`类型,其ID为`a/b/Test`
  1825. */
  1826. TSBuffer.prototype.encode = function (value, schemaOrId, options) {
  1827. var _a;
  1828. var schema;
  1829. if (typeof schemaOrId === "string") {
  1830. schema = this._proto[schemaOrId];
  1831. if (!schema) {
  1832. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
  1833. }
  1834. }
  1835. else {
  1836. schema = schemaOrId;
  1837. }
  1838. // validate before encode
  1839. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
  1840. var vRes = this._validator.validate(value, schema, {
  1841. // 禁用excessPropertyChecks,因为不会编码excess property
  1842. excessPropertyChecks: false,
  1843. });
  1844. if (!vRes.isSucc) {
  1845. return vRes;
  1846. }
  1847. }
  1848. var buf;
  1849. try {
  1850. buf = this._encoder.encode(value, schema);
  1851. }
  1852. catch (e) {
  1853. return { isSucc: false, errMsg: e.message };
  1854. }
  1855. return { isSucc: true, buf: buf };
  1856. };
  1857. /**
  1858. * 解码
  1859. * @param buf - 待解码的二进制数据
  1860. * @param schemaOrId - Schema 或 SchemaID,例如`a/b.ts`下的`Test`类型,其ID为`a/b/Test`
  1861. */
  1862. TSBuffer.prototype.decode = function (buf, schemaOrId, options) {
  1863. var _a;
  1864. var schema;
  1865. if (typeof schemaOrId === "string") {
  1866. schema = this._proto[schemaOrId];
  1867. if (!schema) {
  1868. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
  1869. }
  1870. }
  1871. else {
  1872. schema = schemaOrId;
  1873. }
  1874. var value;
  1875. try {
  1876. value = this._decoder.decode(buf, schema);
  1877. }
  1878. catch (e) {
  1879. return { isSucc: false, errMsg: e.message, errPhase: "decode" };
  1880. }
  1881. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
  1882. var vRes = this._validator.validate(value, schema);
  1883. if (!vRes.isSucc) {
  1884. return tslib.__assign(tslib.__assign({}, vRes), { errPhase: "validate" });
  1885. }
  1886. }
  1887. return { isSucc: true, value: value };
  1888. };
  1889. /**
  1890. * 编码为 JSON Object,根据协议将 JSON 不支持的格式(如 ArrayBuffer、Date、ObjectId)转换成 JSON 可传输的格式
  1891. * @param value
  1892. * @param schemaOrId
  1893. * @param options
  1894. */
  1895. TSBuffer.prototype.encodeJSON = function (value, schemaOrId, options) {
  1896. var _a;
  1897. var schema;
  1898. if (typeof schemaOrId === "string") {
  1899. schema = this._proto[schemaOrId];
  1900. if (!schema) {
  1901. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId) };
  1902. }
  1903. }
  1904. else {
  1905. schema = schemaOrId;
  1906. }
  1907. // validate before encode
  1908. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipEncodeValidate)) {
  1909. var vRes = this._validator.prune(value, schema);
  1910. if (!vRes.isSucc) {
  1911. return vRes;
  1912. }
  1913. value = vRes.pruneOutput;
  1914. }
  1915. // TODO schema 里没有 Buffer 和 Custom 的自动跳过
  1916. var json;
  1917. try {
  1918. json = this._encoder.encodeJSON(value, schema);
  1919. }
  1920. catch (e) {
  1921. return { isSucc: false, errMsg: e.message };
  1922. }
  1923. return { isSucc: true, json: json };
  1924. };
  1925. /**
  1926. * 从 JSON Object 解码,根据协议将 ArrayBuffer、Date、ObjectId 等类型从 JSON 中还原
  1927. * @param json - JSON Object (是 JSON 对象,而非 JSON 字符串)
  1928. * @param schemaOrId
  1929. * @param options
  1930. */
  1931. TSBuffer.prototype.decodeJSON = function (json, schemaOrId, options) {
  1932. var _a;
  1933. var schema;
  1934. if (typeof schemaOrId === "string") {
  1935. schema = this._proto[schemaOrId];
  1936. if (!schema) {
  1937. return { isSucc: false, errMsg: "Cannot find schema\uFF1A ".concat(schemaOrId), errPhase: undefined };
  1938. }
  1939. }
  1940. else {
  1941. schema = schemaOrId;
  1942. }
  1943. // TODO schema 里没有 Buffer 和 Custom 的自动跳过
  1944. var value;
  1945. try {
  1946. value = this._decoder.decodeJSON(json, schema);
  1947. }
  1948. catch (e) {
  1949. return { isSucc: false, errMsg: e.message, errPhase: "decode" };
  1950. }
  1951. if (!((_a = options === null || options === void 0 ? void 0 : options.skipValidate) !== null && _a !== void 0 ? _a : this._options.skipDecodeValidate)) {
  1952. var vRes = this._validator.prune(value, schema);
  1953. if (!vRes.isSucc) {
  1954. vRes.errPhase = "validate";
  1955. return vRes;
  1956. }
  1957. return { isSucc: true, value: vRes.pruneOutput };
  1958. }
  1959. return { isSucc: true, value: value };
  1960. };
  1961. return TSBuffer;
  1962. }());
  1963. exports.Base64Util = Base64Util;
  1964. exports.TSBuffer = TSBuffer;
  1965. }).call(this,require("buffer").Buffer)
  1966. }
  1967. if (nodeEnv) {
  1968. __define(__module.exports, __require, __module);
  1969. }
  1970. else {
  1971. __quick_compile_project__.registerModuleFunc(__filename, function () {
  1972. __define(__module.exports, __require, __module);
  1973. });
  1974. }
  1975. })();