index.js 51 KB

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