UNPKG

2.56 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;
41function addCustomAjvFormats(ajv) {
42 return (ajv
43 .addFormat('id', /^[a-z0-9_]{6,64}$/)
44 .addFormat('slug', /^[a-z0-9-]+$/)
45 .addFormat('semVer', /^[0-9]+\.[0-9]+\.[0-9]+$/)
46 // IETF language tag (https://en.wikipedia.org/wiki/IETF_language_tag)
47 .addFormat('languageTag', /^[a-z]{2}(-[A-Z]{2})?$/)
48 .addFormat('countryCode', /^[A-Z]{2}$/)
49 .addFormat('currency', /^[A-Z]{3}$/)
50 .addFormat('unixTimestamp', {
51 type: 'number',
52 validate: (n) => {
53 // 16725225600 is 2500-01-01 in seconds
54 return n >= 0 && n < 16725225600;
55 },
56 })
57 .addFormat('unixTimestampMillis', {
58 type: 'number',
59 validate: (n) => {
60 // 16725225600000 is 2500-01-01 in milliseconds
61 return n >= 0 && n < 16725225600000;
62 },
63 })
64 .addFormat('utcOffset', {
65 type: 'number',
66 validate: (n) => {
67 // min: -14 hours
68 // max +14 hours
69 // multipleOf 15 (minutes)
70 return n >= -14 * 60 && n <= 14 * 60 && Number.isInteger(n);
71 },
72 })
73 .addFormat('utcOffsetHours', {
74 type: 'number',
75 validate: (n) => {
76 // min: -14 hours
77 // max +14 hours
78 // multipleOf 15 (minutes)
79 return n >= -14 && n <= 14 && Number.isInteger(n);
80 },
81 }));
82}