Unverified Commit 45ae757f authored by Sukka's avatar Sukka Committed by GitHub

feat(config): implement a human readable ajv errors (#39291)

parent 2f49a4f9
(()=>{"use strict";var e={97:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.AggregateAjvError=t.AjvError=void 0;const i=r(852);const a=r(610);const n={fieldLabels:"title",includeOriginalError:false,includeData:false};class AjvError extends Error{constructor(e,t={}){super();this.options={};this.redundant=false;this.options={...n,...t};this.pointer=e.instancePath;this.path=a.jsonPath(e.instancePath);const r=i.getMessage(e,this.options);if(r===null){this.redundant=true;return}this.message=`${a.capitalize(r)}.`;if(this.options.includeOriginalError){this.original=e}if(this.options.includeData){this.data=e.data}}toJSON(){const e={path:this.path,pointer:this.pointer,message:this.message};if(this.options.includeOriginalError){e.original=this.original}if(this.options.includeData){e.data=this.data}return e}}t.AjvError=AjvError;class AggregateAjvError extends Error{constructor(e,t={}){super();this.name="AggregateAjvError";this.errors=(e!==null&&e!==void 0?e:[]).map((e=>new AjvError(e,t))).filter((e=>!e.redundant));this.message=this.errors.map((e=>e.message)).join(" ")}toJSON(){return this.errors.map((e=>e.toJSON()))}*[Symbol.iterator](){for(const e of this.errors){yield e}}}t.AggregateAjvError=AggregateAjvError},852:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:true});t.getMessage=t.fieldPreamble=void 0;const i=r(610);const a={"date-time":"date and time",time:"time",date:"date",email:"email address",hostname:"hostname",ipv4:"IPv4 address",ipv6:"IPv6 address",uri:"URI","uri-reference":"URI Reference","uri-template":"URI-template","json-pointer":"JSON Pointer","relative-json-pointer":"relative JSON Pointer",regex:"regular expression"};const fieldPreamble=({instancePath:e,parentSchema:t},{fieldLabels:r})=>{switch(r){case"js":if(e===""){return"the root value"}return`the value at ${i.jsonPath(e).replace(/^\$/,"")}`;case"jsonPath":return`the value at ${i.jsonPath(e)}`;case"jsonPointer":case"instancePath":if(e===""){return"the root value"}return`the value at ${e}`;case"title":if(t===null||t===void 0?void 0:t.title){return t.title}if(e===""){return"the root value"}return`the value at ${e}`;default:throw new Error(`invalid fieldLabels value: ${r}`)}};t.fieldPreamble=fieldPreamble;const getMessage=({data:e,keyword:r,message:n,params:s,parentSchema:o,schemaPath:u,instancePath:l},{fieldLabels:c})=>{const h=t.fieldPreamble({instancePath:l,parentSchema:o},{fieldLabels:c});if(o===null||o===void 0?void 0:o.errorMessage){return`${h} ${o.errorMessage}`}switch(r){case"enum":{const e=s.allowedValues.map(JSON.stringify);const t=i.humanizeList(e,"or");return`${h} must be one of: ${t}`}case"type":{const t=Array.isArray(s.type)?s.type:s.type.split(",");const r=i.humanizeList(t,"or");const a=i.humanizeTypeOf(e);return`${h} must be ${i.indefiniteArticle(r)} ${r} but it was ${a}`}case"minLength":{const t=s.limit;const r=i.pluralize("character",t);const a=e.length;const n=i.pluralize("character",a);return`${h} must be ${t} ${r} or more but it was ${a} ${n}`}case"maxLength":{const t=s.limit;const r=i.pluralize("character",t);const a=e.length;const n=i.pluralize("character",a);return`${h} must be ${t} ${r} or fewer but it was ${a} ${n}`}case"pattern":{if(u.endsWith("propertyNames/pattern"))return null;const e=o===null||o===void 0?void 0:o.patternLabel;if(e){return`${h} must be ${e} but it was not`}else{return`${h} is an invalid string`}}case"format":{const e=a[s.format]||s.format;return`${h} must be a valid ${e} string but it was not`}case"multipleOf":{return`${h} must be a multiple of ${s.multipleOf}`}case"minimum":{return`${h} must be equal to or greater than ${s.limit}`}case"exclusiveMinimum":{return`${h} must be greater than ${s.limit}`}case"maximum":{return`${h} must be equal to or less than ${s.limit}`}case"exclusiveMaximum":{return`${h} must be less than ${s.limit}`}case"additionalProperties":{const e=Object.keys(o===null||o===void 0?void 0:o.properties).join(", ");const t=s.additionalProperty;return`${h} has an unexpected property, ${t}, which is not in the list of allowed properties (${e})`}case"required":{const e=s.missingProperty;return`${h} is missing the required field '${e}'`}case"propertyNames":{return`${h} has an invalid property name ${JSON.stringify(s.propertyName)}`}case"minProperties":{const t=s.limit;const r=Object.keys(e).length;return`${h} must have ${t} or more properties but it has ${r}`}case"maxProperties":{const t=s.limit;const r=Object.keys(e).length;return`${h} must have ${t} or fewer properties but it has ${r}`}case"dependencies":{const e=s.property;const t=s.missingProperty;return`${h} must have property ${t} when ${e} is present`}case"minItems":{const t=s.limit;const r=e.length;return`${h} must have ${t} or more items but it has ${r}`}case"maxItems":{const t=s.limit;const r=e.length;return`${h} must have ${t} or fewer items but it has ${r}`}case"uniqueItems":{const{i:e,j:t}=s;return`${h} must be unique but elements ${t} and ${e} are the same`}default:return`${h} ${n}`}};t.getMessage=getMessage},610:(e,t)=>{Object.defineProperty(t,"__esModule",{value:true});t.humanizeList=t.humanizeTypeOf=t.indefiniteArticle=t.humanizePath=t.jsonPath=t.pluralize=t.capitalize=void 0;const capitalize=e=>{if(typeof e!=="string"||e.length===0){return e}return e.charAt(0).toUpperCase()+e.slice(1)};t.capitalize=capitalize;const pluralize=(e,t)=>{if(t===1){return e}return`${e}s`};t.pluralize=pluralize;const jsonPath=e=>{if(e===""){return"$"}const t=e.substring(1).split(/\//).map((e=>e.replace(/~1/g,"/").replace(/~0/g,"~").replace(/\./g,"\\."))).map((e=>{if(/^\d+$/.exec(e)){return`[${e}]`}return`.${e}`})).join("");return"$"+t};t.jsonPath=jsonPath;const humanizePath=e=>{if(e===""){return"the root value"}return`the value at ${t.jsonPath(e)}`};t.humanizePath=humanizePath;const indefiniteArticle=e=>{switch(e[0]){case"a":case"e":case"i":case"o":case"u":return"an";default:return"a"}};t.indefiniteArticle=indefiniteArticle;const humanizeTypeOf=e=>{const r=typeof e;switch(r){case"object":if(e===null){return"null"}if(Array.isArray(e)){return"an array"}return"an object";case"undefined":return"undefined";default:return`${t.indefiniteArticle(r)} ${r}`}};t.humanizeTypeOf=humanizeTypeOf;const humanizeList=(e,t="and")=>{if(e.length===0){return"nothing"}if(e.length===1){return e[0]}if(e.length===2){return`${e[0]} ${t} ${e[1]}`}return`${e.slice(0,-1).join(", ")}, ${t} ${e[e.length-1]}`};t.humanizeList=humanizeList}};var t={};function __nccwpck_require__(r){var i=t[r];if(i!==undefined){return i.exports}var a=t[r]={exports:{}};var n=true;try{e[r](a,a.exports,__nccwpck_require__);n=false}finally{if(n)delete t[r]}return a.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r={};(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:true});e.AggregateAjvError=void 0;var t=__nccwpck_require__(97);Object.defineProperty(e,"AggregateAjvError",{enumerable:true,get:function(){return t.AggregateAjvError}})})();module.exports=r})();
\ No newline at end of file
{"name":"@segment/ajv-human-errors","main":"index.js","license":"MIT"}
......@@ -126,6 +126,7 @@
"@next/react-dev-overlay": "12.2.4-canary.10",
"@next/react-refresh-utils": "12.2.4-canary.10",
"@next/swc": "12.2.4-canary.10",
"@segment/ajv-human-errors": "2.1.2",
"@taskr/clear": "1.1.0",
"@taskr/esnext": "1.1.0",
"@taskr/watch": "1.1.0",
......
......@@ -393,6 +393,7 @@ const configSchema = {
},
exportPathMap: {
isFunction: true,
errorMessage: 'must be a function that returns a Promise',
} as any,
future: {
additionalProperties: false,
......@@ -401,12 +402,14 @@ const configSchema = {
},
generateBuildId: {
isFunction: true,
errorMessage: 'must be a function that returns a Promise',
} as any,
generateEtags: {
type: 'boolean',
},
headers: {
isFunction: true,
errorMessage: 'must be a function that returns a Promise',
} as any,
httpAgentOptions: {
additionalProperties: false,
......@@ -560,9 +563,11 @@ const configSchema = {
},
redirects: {
isFunction: true,
errorMessage: 'must be a function that returns a Promise',
} as any,
rewrites: {
isFunction: true,
errorMessage: 'must be a function that returns a Promise',
} as any,
sassOptions: {
type: 'object',
......@@ -597,6 +602,8 @@ const configSchema = {
},
webpack: {
isFunction: true,
errorMessage:
'must be a function that returns a webpack configuration object',
} as any,
},
} as JSONSchemaType<NextConfig>
......
......@@ -772,8 +772,18 @@ export default async function loadConfig(
if (validateResult.errors) {
Log.warn(`Invalid next.config.js options detected: `)
// Only load @segment/ajv-human-errors when invalid config is detected
const { AggregateAjvError } =
require('next/dist/compiled/@segment/ajv-human-errors') as typeof import('next/dist/compiled/@segment/ajv-human-errors')
const aggregatedAjvErrors = new AggregateAjvError(validateResult.errors, {
fieldLabels: 'js',
})
for (const error of aggregatedAjvErrors) {
console.error(` - ${error.message}`)
}
console.error(
JSON.stringify(validateResult.errors, null, 2),
'\nSee more info here: https://nextjs.org/docs/messages/invalid-next-config'
)
}
......
......@@ -188,7 +188,15 @@ export async function compile_config_schema(task, opts) {
// eslint-disable-next-line
const standaloneCode = require('ajv/dist/standalone').default
// eslint-disable-next-line
const ajv = new Ajv({ code: { source: true }, allErrors: true })
const ajv = new Ajv({
code: { source: true },
allErrors: true,
verbose: true,
})
// errorMessage keyword will be consumed by @segment/ajv-human-errors to provide a custom error message
ajv.addKeyword('errorMessage')
ajv.addKeyword({
keyword: 'isFunction',
schemaType: 'boolean',
......@@ -951,6 +959,19 @@ export async function ncc_async_sema(task, opts) {
.ncc({ packageName: 'async-sema', externals })
.target('compiled/async-sema')
}
// eslint-disable-next-line camelcase
export async function ncc_segment_ajv_human_errors(task, opts) {
await task
.source(
opts.src ||
relative(__dirname, require.resolve('@segment/ajv-human-errors/'))
)
.ncc({
packageName: '@segment/ajv-human-errors/',
externals,
})
.target('compiled/@segment/ajv-human-errors')
}
const babelCorePackages = {
'code-frame': 'next/dist/compiled/babel/code-frame',
......@@ -1803,6 +1824,7 @@ export async function ncc(task, opts) {
'ncc_arg',
'ncc_async_retry',
'ncc_async_sema',
'ncc_segment_ajv_human_errors',
'ncc_assert',
'ncc_browser_zlib',
'ncc_buffer',
......
......@@ -329,6 +329,11 @@ declare module 'next/dist/compiled/@edge-runtime/primitives' {
export = m
}
declare module 'next/dist/compiled/@segment/ajv-human-errors' {
import * as m from '@segment/ajv-human-errors'
export = m
}
declare module 'pnp-webpack-plugin' {
import webpack from 'webpack4'
......
......@@ -426,6 +426,7 @@ importers:
'@next/react-dev-overlay': 12.2.4-canary.10
'@next/react-refresh-utils': 12.2.4-canary.10
'@next/swc': 12.2.4-canary.10
'@segment/ajv-human-errors': 2.1.2
'@swc/helpers': 0.4.3
'@taskr/clear': 1.1.0
'@taskr/esnext': 1.1.0
......@@ -618,6 +619,7 @@ importers:
'@next/react-dev-overlay': link:../react-dev-overlay
'@next/react-refresh-utils': link:../react-refresh-utils
'@next/swc': link:../next-swc
'@segment/ajv-human-errors': 2.1.2_ajv@8.11.0
'@taskr/clear': 1.1.0
'@taskr/esnext': 1.1.0
'@taskr/watch': 1.1.0
......@@ -5014,6 +5016,14 @@ packages:
rxjs: 6.6.2
dev: true
/@segment/ajv-human-errors/2.1.2_ajv@8.11.0:
resolution: {integrity: sha512-d1uQndRFLRO01+xW1y5m+joxDgHf5SLJ70YCY2ArLoo2FJ50o6AoX2mEbuGvnKz/IdwnvDugm9Ti3mZQkW1OoA==}
peerDependencies:
ajv: ^8.0.0
dependencies:
ajv: 8.11.0
dev: true
/@sidvind/better-ajv-errors/0.6.10_ajv@6.12.6:
resolution: {integrity: sha512-vPv8ks6J1KQW1LPYgxmANxcHniE6LFuekxNpcoUUkotJ2srxP4qXZ+y9qpo5LAXhnLoNP0AH8cninimK68gS6A==}
engines: {node: '>= 8.0'}
......@@ -7764,7 +7774,7 @@ packages:
mississippi: 3.0.0
mkdirp: 0.5.5
move-concurrently: 1.0.1
promise-inflight: 1.0.1
promise-inflight: 1.0.1_bluebird@3.7.2
rimraf: 2.7.1
ssri: 6.0.1
unique-filename: 1.1.1
......@@ -10433,6 +10443,7 @@ packages:
eslint: ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0
dependencies:
eslint: 7.32.0
dev: false
/eslint-plugin-react/7.23.2_eslint@7.24.0:
resolution: {integrity: sha512-AfjgFQB+nYszudkxRkTFu0UR1zEQig0ArVMPloKhxwlwkzaw/fBiH0QWcBBhZONlXqQC51+nfqFrkn4EzHcGBw==}
......@@ -18196,6 +18207,17 @@ packages:
optional: true
dev: true
/promise-inflight/1.0.1_bluebird@3.7.2:
resolution: {integrity: sha512-6zWPyEOFaQBJYcGMHBKTKJ3u6TBsnMFOIZSa6ce1e/ZrrsOlnHRHbabMjLiBYKp+n44X9eUI6VUPaukCXHuG4g==}
peerDependencies:
bluebird: '*'
peerDependenciesMeta:
bluebird:
optional: true
dependencies:
bluebird: 3.7.2
dev: true
/promise-polyfill/6.1.0:
resolution: {integrity: sha512-g0LWaH0gFsxovsU7R5LrrhHhWAWiHRnh1GPrhXnPgYsDkIqjRYUYSZEsej/wtleDrz5xVSIDbeKfidztp2XHFQ==}
dev: true
......@@ -20830,7 +20852,7 @@ packages:
worker-farm: 1.7.0
dev: true
/terser-webpack-plugin/5.2.4_webpack@5.74.0:
/terser-webpack-plugin/5.2.4:
resolution: {integrity: sha512-E2CkNMN+1cho04YpdANyRrn8CyN4yMy+WdFKZIySFZrGXZxJwJP6PMNGGc/Mcr6qygQHUUqRxnAPmi0M9f00XA==}
engines: {node: '>= 10.13.0'}
peerDependencies:
......@@ -20852,7 +20874,6 @@ packages:
serialize-javascript: 6.0.0
source-map: 0.6.1
terser: 5.14.1
webpack: 5.74.0
dev: true
/terser/4.8.0:
......@@ -21203,7 +21224,7 @@ packages:
typescript: 4.6.3
/tty-browserify/0.0.0:
resolution: {integrity: sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=}
resolution: {integrity: sha512-JVa5ijo+j/sOoHGjw0sxw734b1LhBkQ3bvUGNdxnVXDCX81Yx7TFgnZygxrIIWn23hbfTaMYLwRmAxFyDuFmIw==}
dev: true
/tty-browserify/0.0.1:
......@@ -22286,7 +22307,7 @@ packages:
neo-async: 2.6.2
schema-utils: 3.1.1
tapable: 2.2.0
terser-webpack-plugin: 5.2.4_webpack@5.74.0
terser-webpack-plugin: 5.2.4
watchpack: 2.4.0
webpack-sources: 3.2.3
transitivePeerDependencies:
......
......@@ -18,13 +18,9 @@ describe('next.config.js validation', () => {
}
`,
outputs: [
'/images/loader',
'must be equal to one of the allowed values',
'imgix',
'/rewrites',
'must pass \\"isFunction\\" keyword validation',
'/swcMinify',
'must be boolean',
'The value at .images.loader must be one of',
'The value at .rewrites must be a function that returns a Promise',
'The value at .swcMinify must be a boolean but it was a string',
],
},
{
......@@ -38,10 +34,8 @@ describe('next.config.js validation', () => {
}
`,
outputs: [
'nonExistent',
'must NOT have additional properties',
'anotherNonExistent',
'must NOT have additional properties',
'The root value has an unexpected property, nonExistent,',
'The value at .experimental has an unexpected property, anotherNonExistent',
],
},
])(
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment