UNPKG

2.71 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.intRange = void 0;
4const codegen_1 = require("../../compile/codegen");
5const timestamp_1 = require("../../runtime/timestamp");
6const util_1 = require("../../compile/util");
7const metadata_1 = require("./metadata");
8const error_1 = require("./error");
9exports.intRange = {
10 int8: [-128, 127, 3],
11 uint8: [0, 255, 3],
12 int16: [-32768, 32767, 5],
13 uint16: [0, 65535, 5],
14 int32: [-2147483648, 2147483647, 10],
15 uint32: [0, 4294967295, 10],
16};
17const error = {
18 message: (cxt) => (0, error_1.typeErrorMessage)(cxt, cxt.schema),
19 params: (cxt) => (0, error_1.typeErrorParams)(cxt, cxt.schema),
20};
21function timestampCode(cxt) {
22 const { gen, data, it } = cxt;
23 const { timestamp, allowDate } = it.opts;
24 if (timestamp === "date")
25 return (0, codegen_1._) `${data} instanceof Date `;
26 const vts = (0, util_1.useFunc)(gen, timestamp_1.default);
27 const allowDateArg = allowDate ? (0, codegen_1._) `, true` : codegen_1.nil;
28 const validString = (0, codegen_1._) `typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`;
29 return timestamp === "string" ? validString : (0, codegen_1.or)((0, codegen_1._) `${data} instanceof Date`, validString);
30}
31const def = {
32 keyword: "type",
33 schemaType: "string",
34 error,
35 code(cxt) {
36 (0, metadata_1.checkMetadata)(cxt);
37 const { data, schema, parentSchema, it } = cxt;
38 let cond;
39 switch (schema) {
40 case "boolean":
41 case "string":
42 cond = (0, codegen_1._) `typeof ${data} == ${schema}`;
43 break;
44 case "timestamp": {
45 cond = timestampCode(cxt);
46 break;
47 }
48 case "float32":
49 case "float64":
50 cond = (0, codegen_1._) `typeof ${data} == "number"`;
51 break;
52 default: {
53 const sch = schema;
54 cond = (0, codegen_1._) `typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`;
55 if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
56 if (sch === "uint32")
57 cond = (0, codegen_1._) `${cond} && ${data} >= 0`;
58 }
59 else {
60 const [min, max] = exports.intRange[sch];
61 cond = (0, codegen_1._) `${cond} && ${data} >= ${min} && ${data} <= ${max}`;
62 }
63 }
64 }
65 cxt.pass(parentSchema.nullable ? (0, codegen_1.or)((0, codegen_1._) `${data} === null`, cond) : cond);
66 },
67};
68exports.default = def;
69//# sourceMappingURL=type.js.map
\No newline at end of file