UNPKG

2.86 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.getAjv = void 0;
4const ajv_1 = require("ajv");
5const AJV_OPTIONS = {
6 removeAdditional: true,
7 allErrors: true,
8 // https://ajv.js.org/options.html#usedefaults
9 useDefaults: 'empty',
10 // these are important and kept same as default:
11 // https://ajv.js.org/options.html#coercetypes
12 coerceTypes: false, // while `false` - it won't mutate your input
13};
14/**
15 * Create Ajv with modified defaults.
16 *
17 * https://ajv.js.org/options.html
18 */
19function getAjv(opt) {
20 const ajv = new ajv_1.default({
21 ...AJV_OPTIONS,
22 ...opt,
23 });
24 // Add custom formats
25 addCustomAjvFormats(ajv);
26 // Adds ajv "formats"
27 // https://ajv.js.org/guide/formats.html
28 require('ajv-formats')(ajv);
29 // https://ajv.js.org/packages/ajv-keywords.html
30 require('ajv-keywords')(ajv, [
31 'transform',
32 'uniqueItemProperties',
33 'instanceof',
34 ]);
35 // Adds $merge, $patch keywords
36 // https://github.com/ajv-validator/ajv-merge-patch
37 require('ajv-merge-patch')(ajv);
38 return ajv;
39}
40exports.getAjv = getAjv;
41const TS_2500 = 16725225600; // 2500-01-01
42const TS_2000 = 946684800; // 2000-01-01
43function addCustomAjvFormats(ajv) {
44 return (ajv
45 .addFormat('id', /^[a-z0-9_]{6,64}$/)
46 .addFormat('slug', /^[a-z0-9-]+$/)
47 .addFormat('semVer', /^[0-9]+\.[0-9]+\.[0-9]+$/)
48 // IETF language tag (https://en.wikipedia.org/wiki/IETF_language_tag)
49 .addFormat('languageTag', /^[a-z]{2}(-[A-Z]{2})?$/)
50 .addFormat('countryCode', /^[A-Z]{2}$/)
51 .addFormat('currency', /^[A-Z]{3}$/)
52 .addFormat('unixTimestamp', {
53 type: 'number',
54 validate: (n) => {
55 return n >= 0 && n < TS_2500;
56 },
57 })
58 .addFormat('unixTimestamp2000', {
59 type: 'number',
60 validate: (n) => {
61 return n >= TS_2000 && n < TS_2500;
62 },
63 })
64 .addFormat('unixTimestampMillis', {
65 type: 'number',
66 validate: (n) => {
67 return n >= 0 && n < TS_2500 * 1000;
68 },
69 })
70 .addFormat('unixTimestampMillis2000', {
71 type: 'number',
72 validate: (n) => {
73 return n >= TS_2000 * 1000 && n < TS_2500 * 1000;
74 },
75 })
76 .addFormat('utcOffset', {
77 type: 'number',
78 validate: (n) => {
79 // min: -14 hours
80 // max +14 hours
81 // multipleOf 15 (minutes)
82 return n >= -14 * 60 && n <= 14 * 60 && Number.isInteger(n);
83 },
84 })
85 .addFormat('utcOffsetHours', {
86 type: 'number',
87 validate: (n) => {
88 // min: -14 hours
89 // max +14 hours
90 // multipleOf 15 (minutes)
91 return n >= -14 && n <= 14 && Number.isInteger(n);
92 },
93 }));
94}