index.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103
  1. /*!
  2. * TSBuffer Validator v2.1.2
  3. * -----------------------------------------
  4. * MIT LICENSE
  5. * KingWorks (C) Copyright 2023
  6. * https://github.com/k8w/tsbuffer-validator
  7. */
  8. 'use strict';
  9. Object.defineProperty(exports, '__esModule', { value: true });
  10. require('k8w-extend-native');
  11. var tslib = require('tslib');
  12. var tsbufferSchema = require('tsbuffer-schema');
  13. var ProtoHelper = /** @class */ (function () {
  14. function ProtoHelper(proto) {
  15. this._schemaWithUuids = [];
  16. this._unionPropertiesCache = {};
  17. this._flatInterfaceSchemaCache = {};
  18. this._parseMappedTypeCache = new WeakMap();
  19. this.proto = proto;
  20. }
  21. /** 将ReferenceTypeSchema层层转换为它最终实际引用的类型 */
  22. ProtoHelper.prototype.parseReference = function (schema) {
  23. // Reference
  24. if (schema.type === tsbufferSchema.SchemaType.Reference) {
  25. var parsedSchema = this.proto[schema.target];
  26. if (!parsedSchema) {
  27. throw new Error("Cannot find reference target: ".concat(schema.target));
  28. }
  29. if (this.isTypeReference(parsedSchema)) {
  30. return this.parseReference(parsedSchema);
  31. }
  32. else {
  33. return parsedSchema;
  34. }
  35. }
  36. // IndexedAccess
  37. else if (schema.type === tsbufferSchema.SchemaType.IndexedAccess) {
  38. if (!this.isInterface(schema.objectType)) {
  39. throw new Error("Error objectType: ".concat(schema.objectType.type));
  40. }
  41. // find prop item
  42. var flat = this.getFlatInterfaceSchema(schema.objectType);
  43. var propItem = flat.properties.find(function (v) { return v.name === schema.index; });
  44. var propType = void 0;
  45. if (propItem) {
  46. propType = propItem.type;
  47. }
  48. else {
  49. if (flat.indexSignature) {
  50. propType = flat.indexSignature.type;
  51. }
  52. else {
  53. throw new Error("Error index: ".concat(schema.index));
  54. }
  55. }
  56. // optional -> | undefined
  57. if (propItem && propItem.optional && // 引用的字段是optional
  58. (propItem.type.type !== tsbufferSchema.SchemaType.Union // 自身不为Union
  59. // 或自身为Union,但没有undefined成员条件
  60. || propItem.type.members.findIndex(function (v) { return v.type.type === tsbufferSchema.SchemaType.Literal && v.type.literal === undefined; }) === -1)) {
  61. propType = {
  62. type: tsbufferSchema.SchemaType.Union,
  63. members: [
  64. { id: 0, type: propType },
  65. {
  66. id: 1,
  67. type: {
  68. type: tsbufferSchema.SchemaType.Literal,
  69. literal: undefined
  70. }
  71. }
  72. ]
  73. };
  74. }
  75. return this.isTypeReference(propType) ? this.parseReference(propType) : propType;
  76. }
  77. else if (schema.type === tsbufferSchema.SchemaType.Keyof) {
  78. var flatInterface = this.getFlatInterfaceSchema(schema.target);
  79. return {
  80. type: tsbufferSchema.SchemaType.Union,
  81. members: flatInterface.properties.map(function (v, i) { return ({
  82. id: i,
  83. type: {
  84. type: tsbufferSchema.SchemaType.Literal,
  85. literal: v.name
  86. }
  87. }); })
  88. };
  89. }
  90. else {
  91. return schema;
  92. }
  93. };
  94. ProtoHelper.prototype.isInterface = function (schema, excludeReference) {
  95. if (excludeReference === void 0) { excludeReference = false; }
  96. if (!excludeReference && this.isTypeReference(schema)) {
  97. var parsed = this.parseReference(schema);
  98. return this.isInterface(parsed, excludeReference);
  99. }
  100. else {
  101. return schema.type === tsbufferSchema.SchemaType.Interface || this.isMappedType(schema) && this.parseMappedType(schema).type === tsbufferSchema.SchemaType.Interface;
  102. }
  103. };
  104. ProtoHelper.prototype.isMappedType = function (schema) {
  105. return schema.type === tsbufferSchema.SchemaType.Pick ||
  106. schema.type === tsbufferSchema.SchemaType.Partial ||
  107. schema.type === tsbufferSchema.SchemaType.Omit ||
  108. schema.type === tsbufferSchema.SchemaType.Overwrite;
  109. };
  110. ProtoHelper.prototype.isTypeReference = function (schema) {
  111. return schema.type === tsbufferSchema.SchemaType.Reference || schema.type === tsbufferSchema.SchemaType.IndexedAccess || schema.type === tsbufferSchema.SchemaType.Keyof;
  112. };
  113. ProtoHelper.prototype._getSchemaUuid = function (schema) {
  114. var schemaWithUuid = schema;
  115. if (!schemaWithUuid.uuid) {
  116. schemaWithUuid.uuid = this._schemaWithUuids.push(schemaWithUuid);
  117. }
  118. return schemaWithUuid.uuid;
  119. };
  120. ProtoHelper.prototype.getUnionProperties = function (schema) {
  121. var uuid = this._getSchemaUuid(schema);
  122. if (!this._unionPropertiesCache[uuid]) {
  123. this._unionPropertiesCache[uuid] = this._addUnionProperties([], schema.members.map(function (v) { return v.type; }));
  124. }
  125. return this._unionPropertiesCache[uuid];
  126. };
  127. /**
  128. * unionProperties: 在Union或Intersection类型中,出现在任意member中的字段
  129. */
  130. ProtoHelper.prototype._addUnionProperties = function (unionProperties, schemas) {
  131. for (var i = 0, len = schemas.length; i < len; ++i) {
  132. var schema = this.parseReference(schemas[i]);
  133. // Interface及其Ref 加入interfaces
  134. if (this.isInterface(schema)) {
  135. var flat = this.getFlatInterfaceSchema(schema);
  136. flat.properties.forEach(function (v) {
  137. unionProperties.binaryInsert(v.name, true);
  138. });
  139. if (flat.indexSignature) {
  140. var key = "[[".concat(flat.indexSignature.keyType, "]]");
  141. unionProperties.binaryInsert(key, true);
  142. }
  143. }
  144. // Intersection/Union 递归合并unionProperties
  145. else if (schema.type === tsbufferSchema.SchemaType.Intersection || schema.type === tsbufferSchema.SchemaType.Union) {
  146. this._addUnionProperties(unionProperties, schema.members.map(function (v) { return v.type; }));
  147. }
  148. else if (this.isMappedType(schema)) {
  149. this._addUnionProperties(unionProperties, [this.parseMappedType(schema)]);
  150. }
  151. }
  152. return unionProperties;
  153. };
  154. /**
  155. * 将unionProperties 扩展到 InterfaceTypeSchema中(optional的any类型)
  156. * 以此来跳过对它们的检查(用于Intersection/Union)
  157. */
  158. ProtoHelper.prototype.applyUnionProperties = function (schema, unionProperties) {
  159. var newSchema = tslib.__assign(tslib.__assign({}, schema), { properties: schema.properties.slice() });
  160. var _loop_1 = function (prop) {
  161. if (prop === '[[String]]') {
  162. newSchema.indexSignature = newSchema.indexSignature || {
  163. keyType: tsbufferSchema.SchemaType.String,
  164. type: { type: tsbufferSchema.SchemaType.Any }
  165. };
  166. }
  167. else if (prop === '[[Number]]') {
  168. newSchema.indexSignature = newSchema.indexSignature || {
  169. keyType: tsbufferSchema.SchemaType.Number,
  170. type: { type: tsbufferSchema.SchemaType.Any }
  171. };
  172. }
  173. else if (!schema.properties.find(function (v) { return v.name === prop; })) {
  174. newSchema.properties.push({
  175. id: -1,
  176. name: prop,
  177. optional: true,
  178. type: {
  179. type: tsbufferSchema.SchemaType.Any
  180. }
  181. });
  182. }
  183. };
  184. for (var _i = 0, unionProperties_1 = unionProperties; _i < unionProperties_1.length; _i++) {
  185. var prop = unionProperties_1[_i];
  186. _loop_1(prop);
  187. }
  188. return newSchema;
  189. };
  190. /**
  191. * 将interface及其引用转换为展平的schema
  192. */
  193. ProtoHelper.prototype.getFlatInterfaceSchema = function (schema) {
  194. var uuid = this._getSchemaUuid(schema);
  195. // from cache
  196. if (this._flatInterfaceSchemaCache[uuid]) {
  197. return this._flatInterfaceSchemaCache[uuid];
  198. }
  199. if (this.isTypeReference(schema)) {
  200. var parsed = this.parseReference(schema);
  201. if (parsed.type !== tsbufferSchema.SchemaType.Interface) {
  202. throw new Error("Cannot flatten non interface type: ".concat(parsed.type));
  203. }
  204. this._flatInterfaceSchemaCache[uuid] = this.getFlatInterfaceSchema(parsed);
  205. }
  206. else if (schema.type === tsbufferSchema.SchemaType.Interface) {
  207. this._flatInterfaceSchemaCache[uuid] = this._flattenInterface(schema);
  208. }
  209. else if (this.isMappedType(schema)) {
  210. this._flatInterfaceSchemaCache[uuid] = this._flattenMappedType(schema);
  211. }
  212. else {
  213. // @ts-expect-error
  214. throw new Error('Invalid interface type: ' + schema.type);
  215. }
  216. return this._flatInterfaceSchemaCache[uuid];
  217. };
  218. /**
  219. * 展平interface
  220. */
  221. ProtoHelper.prototype._flattenInterface = function (schema) {
  222. var properties = {};
  223. var indexSignature;
  224. // 自身定义的properties和indexSignature优先级最高
  225. if (schema.properties) {
  226. for (var _i = 0, _a = schema.properties; _i < _a.length; _i++) {
  227. var prop = _a[_i];
  228. properties[prop.name] = {
  229. optional: prop.optional,
  230. type: prop.type
  231. };
  232. }
  233. }
  234. if (schema.indexSignature) {
  235. indexSignature = schema.indexSignature;
  236. }
  237. // extends的优先级次之,补全没有定义的字段
  238. if (schema.extends) {
  239. for (var _b = 0, _c = schema.extends; _b < _c.length; _b++) {
  240. var extend = _c[_b];
  241. // 解引用
  242. var parsedExtRef = this.parseReference(extend.type);
  243. if (this.isMappedType(parsedExtRef)) {
  244. parsedExtRef = this._flattenMappedType(parsedExtRef);
  245. }
  246. if (!this.isInterface(parsedExtRef)) {
  247. throw new Error('SchemaError: extends must from interface but from ' + parsedExtRef.type);
  248. }
  249. // 递归展平extends
  250. var flatenExtendsSchema = this.getFlatInterfaceSchema(parsedExtRef);
  251. // properties
  252. if (flatenExtendsSchema.properties) {
  253. for (var _d = 0, _e = flatenExtendsSchema.properties; _d < _e.length; _d++) {
  254. var prop = _e[_d];
  255. if (!properties[prop.name]) {
  256. properties[prop.name] = {
  257. optional: prop.optional,
  258. type: prop.type
  259. };
  260. }
  261. }
  262. }
  263. // indexSignature
  264. if (flatenExtendsSchema.indexSignature && !indexSignature) {
  265. indexSignature = flatenExtendsSchema.indexSignature;
  266. }
  267. }
  268. }
  269. return {
  270. type: tsbufferSchema.SchemaType.Interface,
  271. properties: Object.entries(properties).map(function (v, i) { return ({
  272. id: i,
  273. name: v[0],
  274. optional: v[1].optional,
  275. type: v[1].type
  276. }); }),
  277. indexSignature: indexSignature
  278. };
  279. };
  280. /** 将MappedTypeSchema转换为展平的Interface
  281. */
  282. ProtoHelper.prototype._flattenMappedType = function (schema) {
  283. // target 解引用
  284. var target;
  285. if (this.isTypeReference(schema.target)) {
  286. var parsed = this.parseReference(schema.target);
  287. target = parsed;
  288. }
  289. else {
  290. target = schema.target;
  291. }
  292. var flatTarget;
  293. // 内层仍然为MappedType 递归之
  294. if (target.type === tsbufferSchema.SchemaType.Pick || target.type === tsbufferSchema.SchemaType.Partial || target.type === tsbufferSchema.SchemaType.Omit || target.type === tsbufferSchema.SchemaType.Overwrite) {
  295. flatTarget = this._flattenMappedType(target);
  296. }
  297. else if (target.type === tsbufferSchema.SchemaType.Interface) {
  298. flatTarget = this._flattenInterface(target);
  299. }
  300. else {
  301. throw new Error("Invalid target.type: ".concat(target.type));
  302. }
  303. // 开始执行Mapped逻辑
  304. if (schema.type === tsbufferSchema.SchemaType.Pick) {
  305. var properties = [];
  306. var _loop_2 = function (key) {
  307. var propItem = flatTarget.properties.find(function (v) { return v.name === key; });
  308. if (propItem) {
  309. properties.push({
  310. id: properties.length,
  311. name: key,
  312. optional: propItem.optional,
  313. type: propItem.type
  314. });
  315. }
  316. else if (flatTarget.indexSignature) {
  317. properties.push({
  318. id: properties.length,
  319. name: key,
  320. type: flatTarget.indexSignature.type
  321. });
  322. }
  323. };
  324. for (var _i = 0, _a = schema.keys; _i < _a.length; _i++) {
  325. var key = _a[_i];
  326. _loop_2(key);
  327. }
  328. return {
  329. type: tsbufferSchema.SchemaType.Interface,
  330. properties: properties
  331. };
  332. }
  333. else if (schema.type === tsbufferSchema.SchemaType.Partial) {
  334. for (var _b = 0, _c = flatTarget.properties; _b < _c.length; _b++) {
  335. var v = _c[_b];
  336. v.optional = true;
  337. }
  338. return flatTarget;
  339. }
  340. else if (schema.type === tsbufferSchema.SchemaType.Omit) {
  341. var _loop_3 = function (key) {
  342. flatTarget.properties.removeOne(function (v) { return v.name === key; });
  343. };
  344. for (var _d = 0, _e = schema.keys; _d < _e.length; _d++) {
  345. var key = _e[_d];
  346. _loop_3(key);
  347. }
  348. return flatTarget;
  349. }
  350. else if (schema.type === tsbufferSchema.SchemaType.Overwrite) {
  351. var overwrite = this.getFlatInterfaceSchema(schema.overwrite);
  352. if (overwrite.indexSignature) {
  353. flatTarget.indexSignature = overwrite.indexSignature;
  354. }
  355. var _loop_4 = function (prop) {
  356. flatTarget.properties.removeOne(function (v) { return v.name === prop.name; });
  357. flatTarget.properties.push(prop);
  358. };
  359. for (var _f = 0, _g = overwrite.properties; _f < _g.length; _f++) {
  360. var prop = _g[_f];
  361. _loop_4(prop);
  362. }
  363. return flatTarget;
  364. }
  365. else {
  366. throw new Error("Unknown type: ".concat(schema.type));
  367. }
  368. };
  369. ProtoHelper.prototype.parseMappedType = function (schema) {
  370. var cache = this._parseMappedTypeCache.get(schema);
  371. if (cache) {
  372. return cache;
  373. }
  374. // 解嵌套,例如:Pick<Pick<Omit, XXX, 'a'|'b'>>>
  375. var parents = [];
  376. var child = schema;
  377. do {
  378. parents.push(child);
  379. child = this.parseReference(child.target);
  380. } while (this.isMappedType(child));
  381. // 最内层是 interface,直接返回(validator 会验证 key 匹配)
  382. if (child.type === tsbufferSchema.SchemaType.Interface) {
  383. this._parseMappedTypeCache.set(schema, child);
  384. return child;
  385. }
  386. // PickOmit<A|B> === PickOmit<A> | PickOmit<B>
  387. else if (child.type === tsbufferSchema.SchemaType.Union || child.type === tsbufferSchema.SchemaType.Intersection) {
  388. var newSchema = {
  389. type: child.type,
  390. members: child.members.map(function (v) {
  391. // 从里面往外装
  392. var type = v.type;
  393. for (var i = parents.length - 1; i > -1; --i) {
  394. var parent_1 = parents[i];
  395. type = tslib.__assign(tslib.__assign({}, parent_1), { target: type });
  396. }
  397. return {
  398. id: v.id,
  399. type: type
  400. };
  401. })
  402. };
  403. this._parseMappedTypeCache.set(schema, newSchema);
  404. return newSchema;
  405. }
  406. else {
  407. throw new Error("Unsupported pattern ".concat(schema.type, "<").concat(child.type, ">"));
  408. }
  409. };
  410. return ProtoHelper;
  411. }());
  412. var _a;
  413. /** @internal */
  414. var ErrorType;
  415. (function (ErrorType) {
  416. ErrorType["TypeError"] = "TypeError";
  417. ErrorType["InvalidScalarType"] = "InvalidScalarType";
  418. ErrorType["TupleOverLength"] = "TupleOverLength";
  419. ErrorType["InvalidEnumValue"] = "InvalidEnumValue";
  420. ErrorType["InvalidLiteralValue"] = "InvalidLiteralValue";
  421. ErrorType["MissingRequiredProperty"] = "MissingRequiredProperty";
  422. ErrorType["ExcessProperty"] = "ExcessProperty";
  423. ErrorType["InvalidNumberKey"] = "InvalidNumberKey";
  424. ErrorType["UnionTypesNotMatch"] = "UnionTypesNotMatch";
  425. ErrorType["UnionMembersNotMatch"] = "UnionMembersNotMatch";
  426. ErrorType["CustomError"] = "CustomError";
  427. })(ErrorType || (ErrorType = {}));
  428. /** @internal */
  429. var ErrorMsg = (_a = {},
  430. _a[ErrorType.TypeError] = function (expect, actual) { return "Expected type to be `".concat(expect, "`, actually `").concat(actual, "`."); },
  431. _a[ErrorType.InvalidScalarType] = function (value, scalarType) { return "`".concat(value, "` is not a valid `").concat(scalarType, "`."); },
  432. _a[ErrorType.TupleOverLength] = function (valueLength, schemaLength) { return "Value has ".concat(valueLength, " elements but schema allows only ").concat(schemaLength, "."); },
  433. _a[ErrorType.InvalidEnumValue] = function (value) { return "`".concat(value, "` is not a valid enum member."); },
  434. _a[ErrorType.InvalidLiteralValue] = function (expected, actual) { return "Expected to equals `".concat(stringify(expected), "`, actually `").concat(stringify(actual), "`"); },
  435. _a[ErrorType.MissingRequiredProperty] = function (propName) { return "Missing required property `".concat(propName, "`."); },
  436. _a[ErrorType.ExcessProperty] = function (propName) { return "Excess property `".concat(propName, "` should not exists."); },
  437. _a[ErrorType.InvalidNumberKey] = function (key) { return "`".concat(key, "` is not a valid key, the key here should be a `number`."); },
  438. // Union
  439. _a[ErrorType.UnionTypesNotMatch] = function (value, types) { return "`".concat(stringify(value), "` is not matched to `").concat(types.join(' | '), "`"); },
  440. _a[ErrorType.UnionMembersNotMatch] = function (memberErrors) { return "No union member matched, detail:\n".concat(memberErrors.map(function (v, i) { return " <".concat(i, "> ").concat(v.errMsg); }).join('\n')); },
  441. _a[ErrorType.CustomError] = function (errMsg) { return errMsg; },
  442. _a);
  443. /** @internal */
  444. function stringify(value) {
  445. if (typeof value === 'string') {
  446. var output = JSON.stringify(value);
  447. return "'" + output.substr(1, output.length - 2) + "'";
  448. }
  449. return JSON.stringify(value);
  450. }
  451. /** @internal */
  452. var ValidateResultError = /** @class */ (function () {
  453. function ValidateResultError(error) {
  454. this.isSucc = false;
  455. this.error = error;
  456. }
  457. Object.defineProperty(ValidateResultError.prototype, "errMsg", {
  458. get: function () {
  459. return ValidateResultError.getErrMsg(this.error);
  460. },
  461. enumerable: false,
  462. configurable: true
  463. });
  464. ValidateResultError.getErrMsg = function (error) {
  465. var _a;
  466. var errMsg = ErrorMsg[error.type].apply(ErrorMsg, error.params);
  467. if ((_a = error.inner) === null || _a === void 0 ? void 0 : _a.property.length) {
  468. return "Property `".concat(error.inner.property.join('.'), "`: ").concat(errMsg);
  469. }
  470. else {
  471. return errMsg;
  472. }
  473. };
  474. return ValidateResultError;
  475. }());
  476. /** @internal */
  477. var ValidateResultUtil = /** @class */ (function () {
  478. function ValidateResultUtil() {
  479. }
  480. ValidateResultUtil.error = function (type) {
  481. var params = [];
  482. for (var _i = 1; _i < arguments.length; _i++) {
  483. params[_i - 1] = arguments[_i];
  484. }
  485. return new ValidateResultError({
  486. type: type,
  487. params: params
  488. });
  489. };
  490. ValidateResultUtil.innerError = function (property, value, schema, error) {
  491. var _a;
  492. if (error.error.inner) {
  493. if (typeof property === 'string') {
  494. error.error.inner.property.unshift(property);
  495. }
  496. else {
  497. (_a = error.error.inner.property).unshift.apply(_a, property);
  498. }
  499. }
  500. else {
  501. error.error.inner = {
  502. property: typeof property === 'string' ? [property] : property,
  503. value: value,
  504. schema: schema
  505. };
  506. }
  507. return error;
  508. };
  509. ValidateResultUtil.succ = { isSucc: true };
  510. return ValidateResultUtil;
  511. }());
  512. var typedArrays = {
  513. Int8Array: Int8Array,
  514. Int16Array: Int16Array,
  515. Int32Array: Int32Array,
  516. BigInt64Array: typeof BigInt64Array !== 'undefined' ? BigInt64Array : undefined,
  517. Uint8Array: Uint8Array,
  518. Uint16Array: Uint16Array,
  519. Uint32Array: Uint32Array,
  520. BigUint64Array: typeof BigUint64Array !== 'undefined' ? BigUint64Array : undefined,
  521. Float32Array: Float32Array,
  522. Float64Array: Float64Array
  523. };
  524. /**
  525. * TSBuffer Schema Validator
  526. * @public
  527. */
  528. var TSBufferValidator = /** @class */ (function () {
  529. function TSBufferValidator(proto, options) {
  530. /**
  531. * Default options
  532. */
  533. this.options = {
  534. excessPropertyChecks: true,
  535. strictNullChecks: false,
  536. cloneProto: true
  537. };
  538. if (options) {
  539. this.options = tslib.__assign(tslib.__assign({}, this.options), options);
  540. }
  541. this.proto = this.options.cloneProto ? Object.merge({}, proto) : proto;
  542. this.protoHelper = new ProtoHelper(this.proto);
  543. }
  544. /**
  545. * Validate whether the value is valid to the schema
  546. * @param value - Value to be validated.
  547. * @param schemaId - Schema or schema ID.
  548. * For example, the schema ID for type `Test` in `a/b.ts` may be `a/b/Test`.
  549. */
  550. TSBufferValidator.prototype.validate = function (value, schemaOrId, options) {
  551. var _a, _b;
  552. var schema;
  553. var schemaId;
  554. // Get schema
  555. if (typeof schemaOrId === 'string') {
  556. schemaId = schemaOrId;
  557. schema = this.proto[schemaId];
  558. if (!schema) {
  559. throw new Error("Cannot find schema: ".concat(schemaId));
  560. }
  561. }
  562. else {
  563. schema = schemaOrId;
  564. }
  565. // Merge default options
  566. return this._validate(value, schema, tslib.__assign(tslib.__assign({}, options), { excessPropertyChecks: (_a = options === null || options === void 0 ? void 0 : options.excessPropertyChecks) !== null && _a !== void 0 ? _a : this.options.excessPropertyChecks, strictNullChecks: (_b = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _b !== void 0 ? _b : this.options.strictNullChecks }));
  567. };
  568. TSBufferValidator.prototype._validate = function (value, schema, options) {
  569. var _a;
  570. var vRes;
  571. // Validate
  572. switch (schema.type) {
  573. case tsbufferSchema.SchemaType.Boolean:
  574. vRes = this._validateBooleanType(value, schema);
  575. break;
  576. case tsbufferSchema.SchemaType.Number:
  577. vRes = this._validateNumberType(value, schema);
  578. break;
  579. case tsbufferSchema.SchemaType.String:
  580. vRes = this._validateStringType(value, schema);
  581. break;
  582. case tsbufferSchema.SchemaType.Array:
  583. vRes = this._validateArrayType(value, schema, options);
  584. break;
  585. case tsbufferSchema.SchemaType.Tuple:
  586. vRes = this._validateTupleType(value, schema, options);
  587. break;
  588. case tsbufferSchema.SchemaType.Enum:
  589. vRes = this._validateEnumType(value, schema);
  590. break;
  591. case tsbufferSchema.SchemaType.Any:
  592. vRes = this._validateAnyType(value);
  593. break;
  594. case tsbufferSchema.SchemaType.Literal:
  595. vRes = this._validateLiteralType(value, schema, (_a = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _a !== void 0 ? _a : this.options.strictNullChecks);
  596. break;
  597. case tsbufferSchema.SchemaType.Object:
  598. vRes = this._validateObjectType(value, schema);
  599. break;
  600. case tsbufferSchema.SchemaType.Interface:
  601. vRes = this._validateInterfaceType(value, schema, options);
  602. break;
  603. case tsbufferSchema.SchemaType.Buffer:
  604. vRes = this._validateBufferType(value, schema);
  605. break;
  606. case tsbufferSchema.SchemaType.IndexedAccess:
  607. case tsbufferSchema.SchemaType.Reference:
  608. case tsbufferSchema.SchemaType.Keyof:
  609. vRes = this._validateReferenceType(value, schema, options);
  610. break;
  611. case tsbufferSchema.SchemaType.Union:
  612. vRes = this._validateUnionType(value, schema, options);
  613. break;
  614. case tsbufferSchema.SchemaType.Intersection:
  615. vRes = this._validateIntersectionType(value, schema, options);
  616. break;
  617. case tsbufferSchema.SchemaType.Pick:
  618. case tsbufferSchema.SchemaType.Omit:
  619. case tsbufferSchema.SchemaType.Partial:
  620. case tsbufferSchema.SchemaType.Overwrite:
  621. vRes = this._validateMappedType(value, schema, options);
  622. break;
  623. case tsbufferSchema.SchemaType.Date:
  624. vRes = this._validateDateType(value);
  625. break;
  626. case tsbufferSchema.SchemaType.NonNullable:
  627. vRes = this._validateNonNullableType(value, schema, options);
  628. break;
  629. case tsbufferSchema.SchemaType.Custom:
  630. var res = schema.validate(value);
  631. vRes = res.isSucc ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.CustomError, res.errMsg);
  632. break;
  633. // 错误的type
  634. default:
  635. // @ts-expect-error
  636. throw new Error("Unsupported schema type: ".concat(schema.type));
  637. }
  638. // prune
  639. if (options === null || options === void 0 ? void 0 : options.prune) {
  640. // don't need prune, return original value
  641. if (options.prune.output === undefined) {
  642. options.prune.output = value;
  643. }
  644. // output to parent
  645. if (options.prune.parent) {
  646. options.prune.parent.value[options.prune.parent.key] = options.prune.output;
  647. }
  648. }
  649. return vRes;
  650. };
  651. /**
  652. * 修剪 Object,移除 Schema 中未定义的 Key
  653. * 需要确保 value 类型合法
  654. * @param value - value to be validated
  655. * @param schemaOrId -Schema or schema ID.
  656. * @returns Validate result and pruned value. if validate failed, `pruneOutput` would be undefined.
  657. */
  658. TSBufferValidator.prototype.prune = function (value, schemaOrId, options) {
  659. var _a;
  660. var schema = typeof schemaOrId === 'string' ? this.proto[schemaOrId] : schemaOrId;
  661. if (!schema) {
  662. throw new Error('Cannot find schema: ' + schemaOrId);
  663. }
  664. var prune = {};
  665. var vRes = this._validate(value, schema, tslib.__assign(tslib.__assign({}, options), { prune: prune, excessPropertyChecks: false, strictNullChecks: (_a = options === null || options === void 0 ? void 0 : options.strictNullChecks) !== null && _a !== void 0 ? _a : this.options.strictNullChecks }));
  666. if (vRes.isSucc) {
  667. vRes.pruneOutput = prune.output;
  668. }
  669. return vRes;
  670. };
  671. TSBufferValidator.prototype._validateBooleanType = function (value, schema) {
  672. var type = this._getTypeof(value);
  673. if (type === 'boolean') {
  674. return ValidateResultUtil.succ;
  675. }
  676. else {
  677. return ValidateResultUtil.error(ErrorType.TypeError, 'boolean', type);
  678. }
  679. };
  680. TSBufferValidator.prototype._validateNumberType = function (value, schema) {
  681. // 默认为double
  682. var scalarType = schema.scalarType || 'double';
  683. // Wrong Type
  684. var type = this._getTypeof(value);
  685. var rightType = scalarType.indexOf('big') > -1 ? 'bigint' : 'number';
  686. if (type !== rightType) {
  687. return ValidateResultUtil.error(ErrorType.TypeError, rightType, type);
  688. }
  689. // scalarType类型检测
  690. // 整形却为小数
  691. if (scalarType !== 'double' && type === 'number' && !Number.isInteger(value)) {
  692. return ValidateResultUtil.error(ErrorType.InvalidScalarType, value, scalarType);
  693. }
  694. // 无符号整形却为负数
  695. if (scalarType.indexOf('uint') > -1 && value < 0) {
  696. return ValidateResultUtil.error(ErrorType.InvalidScalarType, value, scalarType);
  697. }
  698. return ValidateResultUtil.succ;
  699. };
  700. TSBufferValidator.prototype._validateStringType = function (value, schema) {
  701. var type = this._getTypeof(value);
  702. return type === 'string' ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'string', type);
  703. };
  704. TSBufferValidator.prototype._validateArrayType = function (value, schema, options) {
  705. // is Array type
  706. var type = this._getTypeof(value);
  707. if (type !== tsbufferSchema.SchemaType.Array) {
  708. return ValidateResultUtil.error(ErrorType.TypeError, tsbufferSchema.SchemaType.Array, type);
  709. }
  710. // prune output
  711. var prune = options.prune;
  712. if (prune) {
  713. prune.output = Array.from({ length: value.length });
  714. }
  715. // validate elementType
  716. for (var i = 0; i < value.length; ++i) {
  717. var elemValidateResult = this._validate(value[i], schema.elementType, tslib.__assign(tslib.__assign({}, options), { prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
  718. parent: {
  719. value: prune.output,
  720. key: i
  721. }
  722. } : undefined }));
  723. if (!elemValidateResult.isSucc) {
  724. return ValidateResultUtil.innerError('' + i, value[i], schema.elementType, elemValidateResult);
  725. }
  726. }
  727. return ValidateResultUtil.succ;
  728. };
  729. TSBufferValidator.prototype._validateTupleType = function (value, schema, options) {
  730. // is Array type
  731. var type = this._getTypeof(value);
  732. if (type !== tsbufferSchema.SchemaType.Array) {
  733. return ValidateResultUtil.error(ErrorType.TypeError, tsbufferSchema.SchemaType.Array, type);
  734. }
  735. var prune = options.prune;
  736. // validate length
  737. // excessPropertyChecks 与 prune互斥
  738. if (!prune && options.excessPropertyChecks && value.length > schema.elementTypes.length) {
  739. return ValidateResultUtil.error(ErrorType.TupleOverLength, value.length, schema.elementTypes.length);
  740. }
  741. // prune output
  742. if (prune) {
  743. prune.output = Array.from({ length: Math.min(value.length, schema.elementTypes.length) });
  744. }
  745. // validate elementType
  746. for (var i = 0; i < schema.elementTypes.length; ++i) {
  747. // MissingRequiredProperty: NotOptional && is undefined
  748. if (value[i] === undefined || value[i] === null && !options.strictNullChecks) {
  749. var canBeNull = this._canBeNull(schema.elementTypes[i]);
  750. var canBeUndefined = schema.optionalStartIndex !== undefined && i >= schema.optionalStartIndex || this._canBeUndefined(schema.elementTypes[i]);
  751. var isOptional = canBeUndefined || !options.strictNullChecks && canBeNull;
  752. // skip undefined property
  753. if (isOptional) {
  754. // Prune null & undefined->null
  755. if (prune === null || prune === void 0 ? void 0 : prune.output) {
  756. if (value[i] === null && canBeNull
  757. || value[i] === undefined && !canBeUndefined && canBeNull) {
  758. prune.output[i] = null;
  759. }
  760. }
  761. continue;
  762. }
  763. else {
  764. return ValidateResultUtil.error(ErrorType.MissingRequiredProperty, i);
  765. }
  766. }
  767. // element type check
  768. var elemValidateResult = this._validate(value[i], schema.elementTypes[i], {
  769. prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
  770. parent: {
  771. value: prune.output,
  772. key: i
  773. }
  774. } : undefined,
  775. strictNullChecks: options.strictNullChecks,
  776. excessPropertyChecks: options.excessPropertyChecks
  777. });
  778. if (!elemValidateResult.isSucc) {
  779. return ValidateResultUtil.innerError('' + i, value[i], schema.elementTypes[i], elemValidateResult);
  780. }
  781. }
  782. return ValidateResultUtil.succ;
  783. };
  784. TSBufferValidator.prototype._canBeUndefined = function (schema) {
  785. var _this = this;
  786. if (schema.type === tsbufferSchema.SchemaType.Union) {
  787. return schema.members.some(function (v) { return _this._canBeUndefined(v.type); });
  788. }
  789. if (schema.type === tsbufferSchema.SchemaType.Literal && schema.literal === undefined) {
  790. return true;
  791. }
  792. return false;
  793. };
  794. TSBufferValidator.prototype._canBeNull = function (schema) {
  795. var _this = this;
  796. if (schema.type === tsbufferSchema.SchemaType.Union) {
  797. return schema.members.some(function (v) { return _this._canBeNull(v.type); });
  798. }
  799. if (schema.type === tsbufferSchema.SchemaType.Literal && schema.literal === null) {
  800. return true;
  801. }
  802. return false;
  803. };
  804. TSBufferValidator.prototype._validateEnumType = function (value, schema) {
  805. // must be string or number
  806. var type = this._getTypeof(value);
  807. if (type !== 'string' && type !== 'number') {
  808. return ValidateResultUtil.error(ErrorType.TypeError, 'string | number', type);
  809. }
  810. // 有值与预设相同
  811. if (schema.members.some(function (v) { return v.value === value; })) {
  812. return ValidateResultUtil.succ;
  813. }
  814. else {
  815. return ValidateResultUtil.error(ErrorType.InvalidEnumValue, value);
  816. }
  817. };
  818. TSBufferValidator.prototype._validateAnyType = function (value) {
  819. return ValidateResultUtil.succ;
  820. };
  821. TSBufferValidator.prototype._validateLiteralType = function (value, schema, strictNullChecks) {
  822. // 非strictNullChecks严格模式,null undefined同等对待
  823. if (!strictNullChecks && (schema.literal === null || schema.literal === undefined)) {
  824. return value === null || value === undefined ?
  825. ValidateResultUtil.succ
  826. : ValidateResultUtil.error(ErrorType.InvalidLiteralValue, schema.literal, value);
  827. }
  828. return value === schema.literal ?
  829. ValidateResultUtil.succ
  830. : ValidateResultUtil.error(ErrorType.InvalidLiteralValue, schema.literal, value);
  831. };
  832. TSBufferValidator.prototype._validateObjectType = function (value, schema) {
  833. var type = this._getTypeof(value);
  834. return type === 'Object' || type === 'Array' ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'Object', type);
  835. };
  836. TSBufferValidator.prototype._validateInterfaceType = function (value, schema, options) {
  837. var type = this._getTypeof(value);
  838. if (type !== 'Object') {
  839. return ValidateResultUtil.error(ErrorType.TypeError, 'Object', type);
  840. }
  841. // 先展平
  842. var flatSchema = this.protoHelper.getFlatInterfaceSchema(schema);
  843. // From union or intersecton type
  844. if (options.unionProperties) {
  845. flatSchema = this.protoHelper.applyUnionProperties(flatSchema, options.unionProperties);
  846. }
  847. return this._validateFlatInterface(value, flatSchema, options);
  848. };
  849. TSBufferValidator.prototype._validateMappedType = function (value, schema, options) {
  850. var parsed = this.protoHelper.parseMappedType(schema);
  851. if (parsed.type === tsbufferSchema.SchemaType.Interface) {
  852. return this._validateInterfaceType(value, schema, options);
  853. }
  854. else if (parsed.type === tsbufferSchema.SchemaType.Union) {
  855. return this._validateUnionType(value, parsed, options);
  856. }
  857. else if (parsed.type === tsbufferSchema.SchemaType.Intersection) {
  858. return this._validateIntersectionType(value, parsed, options);
  859. }
  860. // @ts-expect-error
  861. throw new Error("Invalid ".concat(schema.type, " target type: ").concat(parsed.type));
  862. };
  863. TSBufferValidator.prototype._validateFlatInterface = function (value, schema, options) {
  864. // interfaceSignature强制了key必须是数字的情况
  865. if (schema.indexSignature && schema.indexSignature.keyType === tsbufferSchema.SchemaType.Number) {
  866. for (var key in value) {
  867. if (!this._isNumberKey(key)) {
  868. return ValidateResultUtil.error(ErrorType.InvalidNumberKey, key);
  869. }
  870. }
  871. }
  872. var prune = options.prune;
  873. if (prune) {
  874. prune.output = {};
  875. }
  876. // Excess property check (与prune互斥)
  877. if (!prune && options.excessPropertyChecks && !schema.indexSignature) {
  878. var validProperties_1 = schema.properties.map(function (v) { return v.name; });
  879. var firstExcessProperty = Object.keys(value).find(function (v) { return validProperties_1.indexOf(v) === -1; });
  880. if (firstExcessProperty) {
  881. return ValidateResultUtil.error(ErrorType.ExcessProperty, firstExcessProperty);
  882. }
  883. }
  884. // 校验properties
  885. if (schema.properties) {
  886. for (var _i = 0, _a = schema.properties; _i < _a.length; _i++) {
  887. var property = _a[_i];
  888. // MissingRequiredProperty: is undefined && !isOptional
  889. if (value[property.name] === undefined || value[property.name] === null && !options.strictNullChecks) {
  890. var canBeNull = this._canBeNull(property.type);
  891. var canBeUndefined = property.optional || this._canBeUndefined(property.type);
  892. var isOptional = canBeUndefined || !options.strictNullChecks && canBeNull;
  893. // skip undefined optional property
  894. if (isOptional) {
  895. // Prune null & undefined->null
  896. if (prune === null || prune === void 0 ? void 0 : prune.output) {
  897. if (value[property.name] === null && canBeNull
  898. || value[property.name] === undefined && !canBeUndefined && canBeNull) {
  899. prune.output[property.name] = null;
  900. }
  901. }
  902. continue;
  903. }
  904. else {
  905. return ValidateResultUtil.error(ErrorType.MissingRequiredProperty, property.name);
  906. }
  907. }
  908. // property本身验证
  909. var vRes = this._validate(value[property.name], property.type, {
  910. prune: (prune === null || prune === void 0 ? void 0 : prune.output) && property.id > -1 ? {
  911. parent: {
  912. value: prune.output,
  913. key: property.name
  914. }
  915. } : undefined,
  916. strictNullChecks: options.strictNullChecks,
  917. excessPropertyChecks: options.excessPropertyChecks
  918. });
  919. if (!vRes.isSucc) {
  920. return ValidateResultUtil.innerError(property.name, value[property.name], property.type, vRes);
  921. }
  922. }
  923. }
  924. // 检测indexSignature
  925. if (schema.indexSignature) {
  926. for (var key in value) {
  927. // only prune is (property is pruned already)
  928. // let memberPrune: ValidatePruneOptions | undefined = schema.properties.some(v => v.name === key) ? undefined : {};
  929. // validate each field
  930. var vRes = this._validate(value[key], schema.indexSignature.type, {
  931. prune: (prune === null || prune === void 0 ? void 0 : prune.output) ? {
  932. parent: {
  933. value: prune.output,
  934. key: key
  935. }
  936. } : undefined,
  937. strictNullChecks: options.strictNullChecks,
  938. excessPropertyChecks: options.excessPropertyChecks
  939. });
  940. if (!vRes.isSucc) {
  941. return ValidateResultUtil.innerError(key, value[key], schema.indexSignature.type, vRes);
  942. }
  943. }
  944. }
  945. return ValidateResultUtil.succ;
  946. };
  947. TSBufferValidator.prototype._validateBufferType = function (value, schema) {
  948. var _a, _b;
  949. var type = this._getTypeof(value);
  950. if (type !== 'Object') {
  951. return ValidateResultUtil.error(ErrorType.TypeError, schema.arrayType || 'ArrayBuffer', type);
  952. }
  953. else if (schema.arrayType) {
  954. var typeArrayClass = typedArrays[schema.arrayType];
  955. if (!typeArrayClass) {
  956. throw new Error("Error TypedArray type: ".concat(schema.arrayType));
  957. }
  958. return value instanceof typeArrayClass ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, schema.arrayType, (_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name);
  959. }
  960. else {
  961. return value instanceof ArrayBuffer ? ValidateResultUtil.succ : ValidateResultUtil.error(ErrorType.TypeError, 'ArrayBuffer', (_b = value === null || value === void 0 ? void 0 : value.constructor) === null || _b === void 0 ? void 0 : _b.name);
  962. }
  963. };
  964. TSBufferValidator.prototype._validateReferenceType = function (value, schema, options) {
  965. return this._validate(value, this.protoHelper.parseReference(schema), options);
  966. };
  967. TSBufferValidator.prototype._validateUnionType = function (value, schema, options) {
  968. var _this = this;
  969. options.unionProperties = options.unionProperties || this.protoHelper.getUnionProperties(schema);
  970. var isObjectPrune = false;
  971. var prune = options.prune;
  972. if (prune && value && Object.getPrototypeOf(value) === Object.prototype) {
  973. isObjectPrune = true;
  974. prune.output = {};
  975. }
  976. // 有一成功则成功
  977. var isSomeSucc = false;
  978. var memberErrors = [];
  979. for (var i = 0; i < schema.members.length; ++i) {
  980. var member = schema.members[i];
  981. var memberType = this.protoHelper.isTypeReference(member.type) ? this.protoHelper.parseReference(member.type) : member.type;
  982. var memberPrune = prune ? {} : undefined;
  983. var vRes = this._validate(value, memberType, tslib.__assign(tslib.__assign({}, options), { prune: memberPrune }));
  984. if (vRes.isSucc) {
  985. isSomeSucc = true;
  986. // if prune object: must prune all members
  987. if (isObjectPrune) {
  988. prune.output = tslib.__assign(tslib.__assign({}, prune.output), memberPrune.output);
  989. }
  990. // not prune object: stop checking after 1st member matched
  991. else {
  992. break;
  993. }
  994. }
  995. else {
  996. memberErrors.push(vRes);
  997. }
  998. }
  999. // 有一成功则成功;
  1000. if (isSomeSucc) {
  1001. return ValidateResultUtil.succ;
  1002. }
  1003. // 全部失败,则失败
  1004. else {
  1005. // All member error is the same, return the first
  1006. var msg0_1 = memberErrors[0].errMsg;
  1007. if (memberErrors.every(function (v) { return v.errMsg === msg0_1; })) {
  1008. return memberErrors[0];
  1009. }
  1010. // mutual exclusion: return the only one
  1011. var nonLiteralErrors = memberErrors.filter(function (v) { return v.error.type !== ErrorType.InvalidLiteralValue; });
  1012. if (nonLiteralErrors.length === 1) {
  1013. return nonLiteralErrors[0];
  1014. }
  1015. // All member error without inner: show simple msg
  1016. if (memberErrors.every(function (v) { return !v.error.inner && (v.error.type === ErrorType.TypeError || v.error.type === ErrorType.InvalidLiteralValue); })) {
  1017. var valueType = this._getTypeof(value);
  1018. var expectedTypes = memberErrors.map(function (v) { return v.error.type === ErrorType.TypeError ? v.error.params[0] : _this._getTypeof(v.error.params[0]); }).distinct();
  1019. // Expected type A|B|C, actually type D
  1020. if (expectedTypes.indexOf(valueType) === -1) {
  1021. return ValidateResultUtil.error(ErrorType.TypeError, expectedTypes.join(' | '), this._getTypeof(value));
  1022. }
  1023. // `'D'` is not matched to `'A'|'B'|'C'`
  1024. if (valueType !== 'Object' && valueType !== tsbufferSchema.SchemaType.Array) {
  1025. var types = memberErrors.map(function (v) { return v.error.type === ErrorType.TypeError ? v.error.params[0] : stringify(v.error.params[0]); }).distinct();
  1026. return ValidateResultUtil.error(ErrorType.UnionTypesNotMatch, value, types);
  1027. }
  1028. }
  1029. // other errors
  1030. return ValidateResultUtil.error(ErrorType.UnionMembersNotMatch, memberErrors);
  1031. }
  1032. };
  1033. TSBufferValidator.prototype._validateIntersectionType = function (value, schema, options) {
  1034. options.unionProperties = options.unionProperties || this.protoHelper.getUnionProperties(schema);
  1035. var isObjectPrune = false;
  1036. var prune = options.prune;
  1037. if (prune && value && Object.getPrototypeOf(value) === Object.prototype) {
  1038. prune.output = {};
  1039. isObjectPrune = true;
  1040. }
  1041. // 有一失败则失败
  1042. for (var i = 0, len = schema.members.length; i < len; ++i) {
  1043. // 验证member
  1044. var memberType = schema.members[i].type;
  1045. memberType = this.protoHelper.isTypeReference(memberType) ? this.protoHelper.parseReference(memberType) : memberType;
  1046. var memberPrune = prune ? {} : undefined;
  1047. var vRes = this._validate(value, memberType, tslib.__assign(tslib.__assign({}, options), { prune: memberPrune }));
  1048. // 有一失败则失败
  1049. if (!vRes.isSucc) {
  1050. return vRes;
  1051. }
  1052. if (isObjectPrune) {
  1053. prune.output = tslib.__assign(tslib.__assign({}, prune.output), memberPrune.output);
  1054. }
  1055. }
  1056. // 全成功则成功
  1057. return ValidateResultUtil.succ;
  1058. };
  1059. TSBufferValidator.prototype._validateDateType = function (value) {
  1060. if (value instanceof Date) {
  1061. return ValidateResultUtil.succ;
  1062. }
  1063. else {
  1064. return ValidateResultUtil.error(ErrorType.TypeError, 'Date', this._getTypeof(value));
  1065. }
  1066. };
  1067. TSBufferValidator.prototype._validateNonNullableType = function (value, schema, options) {
  1068. var type = this._getTypeof(value);
  1069. if ((type === 'null' || type === 'undefined') && schema.target.type !== 'Any') {
  1070. return ValidateResultUtil.error(ErrorType.TypeError, 'NonNullable', type);
  1071. }
  1072. return this._validate(value, schema.target, options);
  1073. };
  1074. TSBufferValidator.prototype._isNumberKey = function (key) {
  1075. var int = parseInt(key);
  1076. return !(isNaN(int) || ('' + int) !== key);
  1077. };
  1078. TSBufferValidator.prototype._getTypeof = function (value) {
  1079. var type = typeof value;
  1080. if (type === 'object') {
  1081. if (value === null) {
  1082. return 'null';
  1083. }
  1084. else if (Array.isArray(value)) {
  1085. return tsbufferSchema.SchemaType.Array;
  1086. }
  1087. else {
  1088. return 'Object';
  1089. }
  1090. }
  1091. return type;
  1092. };
  1093. return TSBufferValidator;
  1094. }());
  1095. exports.ProtoHelper = ProtoHelper;
  1096. exports.TSBufferValidator = TSBufferValidator;