Giter Club home page Giter Club logo

schema-utils's Introduction

npm node tests coverage GitHub Discussions size

schema-utils

Package for validate options in loaders and plugins.

Getting Started

To begin, you'll need to install schema-utils:

npm install schema-utils

API

schema.json

{
  "type": "object",
  "properties": {
    "option": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}
import schema from "./path/to/schema.json";
import { validate } from "schema-utils";

const options = { option: true };
const configuration = { name: "Loader Name/Plugin Name/Name" };

validate(schema, options, configuration);

schema

Type: String

JSON schema.

Simple example of schema:

{
  "type": "object",
  "properties": {
    "name": {
      "description": "This is description of option.",
      "type": "string"
    }
  },
  "additionalProperties": false
}

options

Type: Object

Object with options.

import schema from "./path/to/schema.json";
import { validate } from "schema-utils";

const options = { foo: "bar" };

validate(schema, { name: 123 }, { name: "MyPlugin" });

configuration

Allow to configure validator.

There is an alternative method to configure the name andbaseDataPath options via the title property in the schema. For example:

{
  "title": "My Loader options",
  "type": "object",
  "properties": {
    "name": {
      "description": "This is description of option.",
      "type": "string"
    }
  },
  "additionalProperties": false
}

The last word used for the baseDataPath option, other words used for the name option. Based on the example above the name option equals My Loader, the baseDataPath option equals options.

name

Type: Object Default: "Object"

Allow to setup name in validation errors.

import schema from "./path/to/schema.json";
import { validate } from "schema-utils";

const options = { foo: "bar" };

validate(schema, options, { name: "MyPlugin" });
Invalid configuration object. MyPlugin has been initialised using a configuration object that does not match the API schema.
 - configuration.optionName should be a integer.

baseDataPath

Type: String Default: "configuration"

Allow to setup base data path in validation errors.

import schema from "./path/to/schema.json";
import { validate } from "schema-utils";

const options = { foo: "bar" };

validate(schema, options, { name: "MyPlugin", baseDataPath: "options" });
Invalid options object. MyPlugin has been initialised using an options object that does not match the API schema.
 - options.optionName should be a integer.

postFormatter

Type: Function Default: undefined

Allow to reformat errors.

import schema from "./path/to/schema.json";
import { validate } from "schema-utils";

const options = { foo: "bar" };

validate(schema, options, {
  name: "MyPlugin",
  postFormatter: (formattedError, error) => {
    if (error.keyword === "type") {
      return `${formattedError}\nAdditional Information.`;
    }

    return formattedError;
  },
});
Invalid options object. MyPlugin has been initialized using an options object that does not match the API schema.
 - options.optionName should be a integer.
   Additional Information.

Examples

schema.json

{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "test": {
      "anyOf": [
        { "type": "array" },
        { "type": "string" },
        { "instanceof": "RegExp" }
      ]
    },
    "transform": {
      "instanceof": "Function"
    },
    "sourceMap": {
      "type": "boolean"
    }
  },
  "additionalProperties": false
}

Loader

import { getOptions } from "loader-utils";
import { validate } from "schema-utils";

import schema from "path/to/schema.json";

function loader(src, map) {
  const options = getOptions(this);

  validate(schema, options, {
    name: "Loader Name",
    baseDataPath: "options",
  });

  // Code...
}

export default loader;

Plugin

import { validate } from "schema-utils";

import schema from "path/to/schema.json";

class Plugin {
  constructor(options) {
    validate(schema, options, {
      name: "Plugin Name",
      baseDataPath: "options",
    });

    this.options = options;
  }

  apply(compiler) {
    // Code...
  }
}

export default Plugin;

Allow to disable and enable validation (the validate function do nothing)

This can be useful when you don't want to do validation for production builds.

import { disableValidation, enableValidation, validate } from "schema-utils";

// Disable validation
disableValidation();
// Do nothing
validate(schema, options);

// Enable validation
enableValidation();
// Will throw an error if schema is not valid
validate(schema, options);

// Allow to undestand do you need validation or not
const need = needValidate();

console.log(need);

Also you can enable/disable validation using the process.env.SKIP_VALIDATION env variable.

Supported values (case insensitive):

  • yes/y/true/1/on
  • no/n/false/0/off

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

schema-utils's People

Contributors

alexander-akait avatar anshumanv avatar bebraw avatar dependabot[bot] avatar evilebottnawi avatar fahrradflucht avatar gribnoysup avatar jamesgeorge007 avatar joshwiens avatar michael-ciniawsky avatar ozyman42 avatar rishabh3112 avatar scrum avatar snitin315 avatar sokra avatar styfle avatar vankop avatar whiteand avatar wtgtybhertgeghgtwtg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

schema-utils's Issues

2.7 introduces Unexpected Token error on our build

  • Operating System: Azure
  • Node Version: v6.11.2
  • NPM Version: v3.10.10
  • webpack Version: 4.43.0
  • schema-utils Version: 2.7

Expected Behavior

Compile without errors.

Actual Behavior

With the release of 2.7, our nightly builds started failing with:

ERROR in ./wwwroot/source/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
D:_work\66\s\sites\Test\node_modules\schema-utils\dist\util\hints.js:16
const currentSchema = { ...schema
^^^

SyntaxError: Unexpected token ...

Code

ERROR in ./wwwroot/source/index.js
Module build failed (from ./node_modules/babel-loader/lib/index.js):
D:_work\66\s\sites\Test\node_modules\schema-utils\dist\util\hints.js:16
const currentSchema = { ...schema
^^^

SyntaxError: Unexpected token ...

How Do We Reproduce?

I can't actually post our project, obviously. Just letting ya'll know.

Inconvenient Schema Resolving

I thought so tbh 😛 and wasn't getting any mercy 😢

Theory

// In terms of ('./path/to/')
validateOptions('path/to/options.json', options, 'Name')

Practice

validateOptions(`node_modules/${name}-loader/path/to/options.json`)

Which is very ugly && inconvenient, how can we improve it without to much fuss ? 🙃

Relevant Code

Support "function" type

The schema should accept and validate function type since some functionality relies on it. This isn't in the standard and likely requires an Ajv extension to work.

Breaking changes for latest update disrespectful of semver

Recent changes 72f90b6
removed babel from project considering it as patch breaking our build on node v4.2.2

Details

We are using postcss-loader@^2.0.6 which has schema-utils@^0.4.0 as a dependency.

Error (Logs|Stacks)

ERROR in ./src/less/index.less
Module build failed: ModuleBuildError: Module build failed: SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)

at Module._compile (module.js:414:25)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/project/node_modules/postcss-loader/node_modules/schema-utils/src/validateOptions.js:10:25)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/project/node_modules/postcss-loader/node_modules/schema-utils/src/index.js:1:87)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object. (/project/node_modules/postcss-loader/lib/index.js:8:25)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at loadLoader (/project/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:13:17)
at iteratePitchingLoaders (/project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
at /project/node_modules/webpack/lib/NormalModule.js:192:19
at /project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:364:11
at /project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:170:18
at loadLoader (/project/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:27:11)
at iteratePitchingLoaders (/project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
at iteratePitchingLoaders (/project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:165:10)
at /project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:173:18
at loadLoader (/project/node_modules/webpack/node_modules/loader-runner/lib/loadLoader.js:36:3)
at iteratePitchingLoaders (/project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:169:2)
at runLoaders (/project/node_modules/webpack/node_modules/loader-runner/lib/LoaderRunner.js:362:2)
at NormalModule.doBuild (/project/node_modules/webpack/lib/NormalModule.js:179:3)
at NormalModule.build (/project/node_modules/webpack/lib/NormalModule.js:268:15)
at Compilation.buildModule (/project/node_modules/webpack/lib/Compilation.js:146:10)
at /project/node_modules/webpack/lib/Compilation.js:433:9
at /project/node_modules/webpack/lib/NormalModuleFactory.js:253:5
at /project/node_modules/webpack/lib/NormalModuleFactory.js:99:14
at /project/node_modules/webpack/node_modules/tapable/lib/Tapable.js:268:11
at NormalModuleFactory. (/project/node_modules/webpack/lib/CompatibilityPlugin.js:52:5)
at NormalModuleFactory.applyPluginsAsyncWaterfall (/project/node_modules/webpack/node_modules/tapable/lib/Tapable.js:272:13)
at /project/node_modules/webpack/lib/NormalModuleFactory.js:74:11
at /project/node_modules/webpack/lib/NormalModuleFactory.js:205:8
at doNTCallback0 (node.js:419:9)
at process._tickCallback (node.js:348:13)

@ ./src/index.js 9:0-27

Reproduction (Code)

By the time of creation issue unfortunately I cannot provide any code samples.
Please try compile webpack project using those dependencies:

webpack@^1.13.1
postcss-loader@^2.0.6

Environment

Node.js version: v4.2.2
NPM version: 2.14.7

OS node npm package
Linux RHEL6 4.2.2 2.14.7 latest I suppose

Security Vulnerability in version 3.0.0

  • Operating System: macOS
  • Node Version: v14.15.1
  • NPM Version: 7.18.1
  • webpack Version:
  • schema-utils Version: 3.0.0

Expected Behavior

Actual Behavior

Whitesource found a High Severity Bug in vesroin 3.0.0, I am not sure where it is and what it is, it could be a license issue

Screen Shot 2021-06-18 at 16 09 59

Typescript Support: Don't force consumers to enable esModuleInterop in tsconfig

Because of this line it means that any project which consumes schema-utils either as a direct or transitive dependency must use the esModuleInterop tsconfig.json compilerOptions setting in order to compile their typescript.

Ideally we should not be forcing typescript users to add this setting if they don't want it. It also isnt necessary since in

Here's a demo:

  1. git clone https://github.com/AlexLeung/webpack-schema-utils-ajv-typescript-error-demo
  2. npm install
  3. npm start

You will see the following output, including a tsc error

> @ start /home/alex/GitProjects/experiments/webpack-schema-utils-ajv-typescript-error-demo                                                                                                                                                                                               
> tsc                                                                                                                                                                                                                                                                                     
                                                                                                                                                                                                                                                                                          
node_modules/schema-utils/declarations/validate.d.ts:43:8 - error TS1259: Module '"/home/alex/GitProjects/experiments/webpack-schema-utils-ajv-typescript-error-demo/node_modules/ajv/lib/ajv"' can only be default-imported using the 'esModuleInterop' flag                             
                                                                                                                                                                                                                                                                                          
43 import Ajv from 'ajv';                                                                                                                                                                                                                                                                 
          ~~~                                                                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                                                          
  node_modules/ajv/lib/ajv.d.ts:396:1                                                                                                                                                                                                                                                     
    396 export = ajv;                                                                                                                                                                                                                                                                     
        ~~~~~~~~~~~~~                                                                                                                                                                                                                                                                     
    This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.                                                                                                                                                      
                                                                                                                                                                                                                                                                                          
                                                                                                                                                                                                                                                                                          
Found 1 error.                                                                                                                                                                                                                                                                            
                                                                                                                                                                                                                                                                                          
npm ERR! code ELIFECYCLE                                                                                                                                                                                                                                                                  
npm ERR! errno 2                                                                                                                                                                                                                                                                          
npm ERR! @ start: `tsc`                                                                                                                                                                                                                                                                   
npm ERR! Exit status 2                                                                                                                                                                                                                                                                    
npm ERR!                                                                                                                                                                                                                                                                                  
npm ERR! Failed at the @ start script.                                                                                                                                                                                                                                                    
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                          
npm ERR! A complete log of this run can be found in:                                                                                                                                                                                                                                      
npm ERR!     /home/alex/.npm/_logs/2020-08-25T08_10_43_693Z-debug.log      
  1. To fix you can navigate to ./node_modules/schema-utils/declarations/validate.d.ts then change line 43 from
import Ajv from 'ajv';

to

import * as Ajv from 'ajv';
  1. Run npm start again and now the compilation succeeds.

The change described in step 4 is fine because we are only exporting types from the ajv package.
I'll submit a PR for this shortly.

definitions tests

Feature Proposal

Add tests for typescript definitions

Feature Use Case

When typescript definitions will be generated code, we could test back forward compatibility

Blocked by: #49

docs: add API and usage docs

  1. Check the version of package you are using. If it's not the newest version, update and try again (see changelog while updating!).
  2. If the issue is still there, write a minimal project showing the problem and expected output.
  3. Link to the project and mention Node version and OS in your report.

IMPORTANT! You should use Stack Overflow for support related questions.

  • 0.1.0 is published to npm, need to document the api and usage for consumers.

TypeError: Ajv is not a constructor

Bug report

we recently updated our angular poject to v13.x.x now when i running ng serve i get an error:

Actual Behavior

[error] TypeError: Ajv is not a constructor
    at Object.<anonymous> (./node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/validate.js:66:13)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (./node_modules/mini-css-extract-plugin/node_modules/schema-utils/dist/index.js:6:5)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (./node_modules/mini-css-extract-plugin/dist/index.js:8:20)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

in the validate.js line 21
it says require("ajv").default which is undefined - only require("ajv") returns the correct object

Expected Behavior

How Do We Reproduce?

Please paste the results of npx webpack-cli info --aditional-package schema-utils here, and mention other relevant information

PS: ^-- there is a 'd' missing in the header

System:
OS: Linux 5.4 Ubuntu 20.04.2 LTS (Focal Fossa)
CPU: (16) x64 AMD Ryzen 9 5950X 16-Core Processor
Memory: 3.05 GB / 17.58 GB
Binaries:
Node: 16.13.1 - /usr/bin/node
npm: 8.3.0 - /usr/local/bin/npm
Browsers:
Firefox: 95.0.1
Packages:
babel-loader: ^8.2.3 => 8.2.3
compression-webpack-plugin: ^8.0.1 => 8.0.1
ts-loader: ^9.2.6 => 9.2.6
webpack: ^5.65.0 => 5.65.0
worker-loader: ^3.0.8 => 3.0.8

Performance Improvements

  • Operating System: Windows 10
  • Node Version: 12.14.10
  • NPM Version: 6.13.4

Feature Proposal

We can decrease time and memory complexity of validate function for array case of options parameter

Feature Use Case

Provide better default error message on invalid properties

Proposal

Use Case

I am writing a webpack plugin and want to make sure users don't add extraneous properties to the options. The user should know what specific extraneous property caused the error. Currently it just says

options should NOT have additional properties

which does not help the user find out what exactly caused the error.

In the previous release of schema-utils (0.4.x) you would get a message like this which is more helpful:

options['foo'] is an invalid additional property

Implementation

I believe this is caused by removing errorDataPath: 'property' from the ajv config as seen here: 1cbe4ef#diff-813a48919ee26ea79873f7a8e049091fL19

  • I'm open to work on this
    • I need help/mentorship
  • I'm unable to work on this

The errorDataPath: 'property' should be added back to the ajv config.

misleading error message: configuration.module.rules[].exclude

Bug report

What is the current behavior?
misleading error message: configuration.module.rules[].exclude
All other config property is removed here for clarity.

When I use string for exclude

  • config
// webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: 'node_modules',
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  }
};
  • error message
## error
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module.rules[0].exclude should be one of these:
   RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? } | [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
   -> One or multiple rule conditions
   Details:
    * configuration.module.rules[0].exclude should be an instance of RegExp
    * configuration.module.rules[0].exclude: The provided value "node_modules" is not an absolute path!
    * configuration.module.rules[0].exclude should be an instance of function
    * configuration.module.rules[0].exclude should be an array:
      [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
    * configuration.module.rules[0].exclude should be an object.
    * configuration.module.rules[0].exclude should be an array:
      [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]

If I use array of string for exclude

  • config
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: ['node_modules'],
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  }
};
  • error message
✖ 「wds」: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema.
 - configuration.module.rules[0].exclude should be one of these:
   RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? } | [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
   -> One or multiple rule conditions
   Details:
    * configuration.module.rules[0].exclude should be an instance of RegExp
    * configuration.module.rules[0].exclude should be a string.
    * configuration.module.rules[0].exclude should be an instance of function
    * configuration.module.rules[0].exclude[0] should be an instance of RegExp
    * configuration.module.rules[0].exclude[0]: The provided value "node_modules" is not an absolute path!
    * configuration.module.rules[0].exclude[0] should be an instance of function
    * configuration.module.rules[0].exclude[0] should be an array:
      [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
    * configuration.module.rules[0].exclude[0] should be an object.
    * configuration.module.rules[0].exclude should be an object.
    * configuration.module.rules[0].exclude[0] should be an instance of RegExp
    * configuration.module.rules[0].exclude[0]: The provided value "node_modules" is not an absolute path!
    * configuration.module.rules[0].exclude[0] should be an instance of function
    * configuration.module.rules[0].exclude[0] should be an array:
      [RegExp | string | function | [(recursive)] | object { and?, exclude?, include?, not?, or?, test? }]
    * configuration.module.rules[0].exclude[0] should be an object.

If the current behavior is a bug, please provide the steps to reproduce.

  1. use below config and run webpack-dev-server --config webpack.config.js
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: ['node_modules'],
        use: [
          {
            loader: 'babel-loader'
          }
        ]
      }
    ]
  }
};

What is the expected behavior?

string should be removed from allowed object in error message.

Other relevant information:
webpack version: ^4.29.6
Node.js version: 8.11.1
Operating System: ubuntu 18.04
webpack-dev-server: ^3.2.1

Can't refer to ValidationError as a type in Typescript

  • Operating System: Linux
  • Node Version: 12.18.3
  • NPM Version: 6.14.6
  • webpack Version: master
  • schema-utils Version: 3.0.0

Code

import { ValidationError } from 'schema-utils'
function f(v: ValidationError) {
  console.log(v.errors.length)
}

Expected Behavior

No error in my editor (or when compiling with tsc).

Actual Behavior

error on v: ValidationError: "ValidationError refers to a value, but is being used as a type here."

How Do We Reproduce?

Paste above code into a file, tsc --init, npm i schema-utils@3.

Or open webpack's source to lib/util/registerExternalSerializer.js, it has the same problem. You might have to use typescript@next or typescript@beta to reproduce since I changed the way require type checks in Javascript recently.

Probable Fix

index.d.ts should use the re-export syntax, not exports of import types. I'll put up a PR shortly.

Yarn v2 + Typescript: Typings Issue @types/json-schema missing from dependencies

  • Operating System: Ubuntu 18.04
  • Node Version: 13.14.0
  • NPM Version: Yarn v2 (Berry)
  • webpack Version: 5.0.0-beta.15
  • schema-utils Version: 2.6.6
  • typescript Version: 3.8.3

Expected Behavior

When using Yarn v2 Berry Plug-n-Play module resolution, typescript to transpile, and requiring webpack 5 as a dependency, the code should compile without issue.

yarn tsc -b

Actual Behavior

typescript gives this error when trying to compile

.yarn/cache/schema-utils-npm-2.6.6-31a26805d3-2.zip/node_modules/schema-utils/declarations/ValidationError.d.ts:94:16 - error TS2307: Cannot find module 'json-schema'.
94       | import('json-schema').JSONSchema7

Yarn v2 Plug-n-Play is strict (which is a good thing) in that it does not allow a package/workspace to require dependencies which are not listed in its package.json dependencies. Even if I add @types/json-schema to my own repo's dev dependencies, it still won't fix the issue. The only way I can solve this issue is to modify the yarn lockfile to add "@types/json-schema": ^7.0.4 to the dependencies of schema-utils.

Code

import * as webpack from 'webpack';
webpack;
console.log("hello world");

How Do We Reproduce?

I've created a demo repository

  1. Ensure you have latest stable yarn installed
  2. git clone https://github.com/AlexLeung/schema-utils-typescript-issue-demo
  3. cd schema-utils-typescript-issue-demo
  4. yarn install
  5. yarn start

Notice all these TypeScript errors related to json-schema being missing

To fix, you can:

  1. Open yarn.lock
  2. Go to line 923 to the lockfile dependencies of schema-utils and add a new line "@types/json-schema": ^7.0.4
  3. yarn install
  4. yarn start

Now you'll notice that all those json-schema errors are gone, but I'll need to open a similar issue on the webpack repo itself to solve the issue with estree.

How Do We Solve?

Move @types/json-schema from devDependencies to dependencies.

As a general rule, whenever you're writing typescript definitions such as the one for schema-utils, if you're going to include another library's types in the definitions which you export, you need to include that library's types as a dependency rather than a devDependency.

Please review the official TypeScript guidelines on Publishing. https://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html See the "Dependencies" section.

ValidationError: UglifyJs Plugin Invalid Options

So heres my issue, I run the command npm run production and the following error is output:

  • @ production C:\Users\foo
  • node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=producti
    on node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

C:\Users\foo\node_modules\schema-utils\dist\validateOptions.js:44
throw new _ValidationError2.default(ajv.errors, name);
^

ValidationError: UglifyJs Plugin Invalid Options

options should be object

If I run my command npm run watch everything is fine. Any idea what the heck is wrong?

In attempting to fix this I have updated the following packages to the latest versions but the error still occurs; uglify-js, schema-utils, ajv.

  • Operating System: Windows 10
  • Node Version: 6.11.3
  • NPM Version: 3.10.10
  • webpack Version:
  • schema-utils Version: 0.4.5

This issue is for a:

  • bug

Code

CLI Command

    "production": "node node_modules/cross-env/dist/bin/cross-env.js NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",

webpack-defaults upgrade

Addition of webpack-defaults & associated refactoring as a part of the next Major release

Issue exists for status tracking across the organization.

Please do not close

Remove "data" from error message

Now we see message like "Error: data.sourceDirectory is a required property", but data isn't proper name for the object (we don't know real variable name anyway).

It would be nice to format it like "Error: sourceDirectory is a....".

Figure out how to support migrations

We need something like const { migrate } = require('schema-utils') to describe how to map fields as they change (name, type, etc.). Maybe there's something we could reuse here instead of re-inventing the wheel?

Types of property 'type' are incompatible

  • Operating System: N/A
  • Node Version: 12.16.0
  • NPM Version: 6.14.2
  • webpack Version: N/A
  • schema-utils Version: 2.6.6

Expected Behavior

Expected property type 'string' to be valid.

Actual Behavior

Property type 'string' is not valid according to TSC.

Code

import validate from 'schema-utils'

const schema = { // using "const schema: any =" bypasses the problem
    type: 'object', // this is fine
    properties: {
        output: {
            type: 'string' // this gets flagged as an error
        }
    }
}

validate(schema, configFromSomewhere)

I guess this error could be occurring due to the allowed property type values coming from a TS enum behind the scenes, but there appears to be no access to that enum from the schema-utils package. There also appears to be no way to properly declare the schema type.

TypeScript Error Message

Argument of type '{ type: string; properties: { output: { type: string; }; }; }' is not
assignable to parameter of type 'JSONSchema4 | JSONSchema6 | JSONSchema7'

Type '{ type: string; properties: { output: { type: string; }; }; }' is not assignable to
type 'JSONSchema7'

Types of property 'type' are incompatible.

Type 'string' is not assignable to type '"string" | "number" | "boolean" | "object" |
    "integer" | "array" | "null" | JSONSchema7TypeName[] | undefined'

How Do We Reproduce?

Set a schema property type to 'string' in a TypeScript project.

improve error reporting in some cases

  • Operating System: any
  • Node Version: any
  • NPM Version: any
  • webpack Version: any
  • schema-utils Version: 2.0.0

Feature Proposal

Supports:

  • better errors for not keyword, for example ({ "not": { "minimum": 3 } } should output should not be < 3 | should be any non-number)
  • improve message for objects like object { key: string }

Feature Use Case

Better error reporting

Correct custom error messages example

Type

  • Wrong

Details

schema.json

{
  "type": "object",
  "properties": {
    "option": {
      "type": [ "boolean" ]
    }
  },
  // Overrides the default err.message for option
  "errorMessage": {
+  "properties": {
      "option": "should be {Boolean} (https:/github.com/org/repo#anchor)"
+   }
  }
  "additionalProperties": false
}

Location

  • README

custom keyword definition is invalid error

I ran yarn install followed by yarn run test and got the following error.

    custom keyword definition is invalid: data/errors should be boolean

Details

I believe this is due to the incompatibility of ajv-errors that requires ajv@^5.0.0.

Error (Logs|Stacks)

https://gist.github.com/ksato9700/86071b00242cb39c537dc916e030400c

Reproduction (Code)

$ git clone https://github.com/webpack-contrib/schema-utils.git
$ cd schema-utils/
$ yarn install
$ yarn run test

Environment

OS node npm/yarn package
macOS 10.14.2 v10.15.1 yarn 1.13.0 6ca2322

Add Schema type declaration

  • Operating System: Ubuntu 16.04 LTS
  • Node Version: 14.15.3
  • NPM Version: 6.14.10
  • webpack Version: ^4
  • schema-utils Version: ^3

Feature Proposal

Please add standalone Schema type declaration.

Currently is possible to import it manually from validate method type declarations, but it is not convenient:

import * as schemaUtils from "schema-utils";
import { Schema } from "schema-utils/declarations/validate";

Feature Use Case

To use typed schema object, that is passed into validate method.

can not build package with sass-loader and babel-loader

 /app/web/node_modules/sass-loader/node_modules/schema-utils/dist/util/hints.js:16
      const currentSchema = { ...schema
                              ^^^
    SyntaxError: Unexpected token ...

  • Operating System: Ubuntu 20
  • Node Version: 7.10
  • NPM Version: 4.2.0
  • webpack Version: 4.20.2
  • schema-utils Version: [email protected] requeries schema-utils"@^2.1.0

Expected Behavior

can build old bundles with node 7.10

Actual Behavior

Broken build in 2 loaders (sass-loader, babel-loader)

Enabled CI

Travis CI is currently not triggered when pushing to this repo, it either needs to be granted permissions again or the CI config changes needs to be reverted to use CircleCI

Deps issues due to major bump of ajv

Hello!

Recently #22 was released as part of a patch update. Unfortunately, bumping a peer dep a major version causes all sorts of deps 🔥s up the tree and my tests are now all failing on npm ls.

Can we undo this change and republish as a major?

@ljharb @gabergg @airbnb/webinfra

Add declarations to git

Expected Behavior / Situation

dist folder presented in git, so we can see changes in types on each PR

Actual Behavior / Situation

dist folder is not presented in git

Modification Proposal

I suggest to follow same approach as core repo, I agree with @sokra idea webpack/webpack#9939 (comment)

So we can check declarations changes as we check snapshot changes

improve output in some cases

  • Operating System: no matter
  • Node Version: no matter
  • NPM Version: no matter
  • webpack Version: no matter
  • schema-utils Version: 2.1.0

Feature Proposal

Example:

 optimization: {
        runtimeChunk: {
            name: /fef/
        }
    }

Feature Use Case

Actual output:

 - configuration.optimization.runtimeChunk should be one of these:
   boolean | "single" | "multiple" | object { name? }
   -> Create an additional chunk which contains only the webpack runtime and chunk hash maps
   Details:
    * configuration.optimization.runtimeChunk.name should be a string.
    * configuration.optimization.runtimeChunk.name should be an instance of function.
    * configuration.optimization.runtimeChunk.name should be one of these:
      string | function
      -> The name or name factory for the runtime chunks

Expected output:

 - configuration.optimization.runtimeChunk should be one of these:
   boolean | "single" | "multiple" | object { name? }
   -> Create an additional chunk which contains only the webpack runtime and chunk hash maps
   Details:
    * configuration.optimization.runtimeChunk.name should be one of these:
      string | function
      -> The name or name factory for the runtime chunks
     Details:
      * configuration.optimization.runtimeChunk.name should be a string.
      * configuration.optimization.runtimeChunk.name should be an instance of function.

Array<object>

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

Did not find how to describe the entities of the array

Your Proposal for Changes

{
  "directives": {
    "type": ["object"],
    "property": {
      "name": {
        "type": "string"
      },
      "start": {
        "type": "string"
      },
      "end": {
        "type": "string"
      }
    }
  }
}

Where are the brackets [ ] means an array and property describes the essence of an array i.e. object in this case

or

{
  "directives": {
    "type": "array",
    "property": {
      "type": "object",
      "property": {
        "name": {
          "type": "string"
        },
        "start": {
          "type": "string"
        },
        "end": {
          "type": "string"
        }
      }
    }
  }
}

it seems a little more confusing

Bug with declarations exports

  • Node Version: 10
  • schema-utils Version: master

Expected Behavior / Situation

expect correct export

Actual Behavior / Situation

Incorrect
Снимок экрана 2019-11-08 в 16 54 39

Modification Proposal

export default function validate() instead of function validate(); export default validate

Снимок экрана 2019-11-08 в 16 56 23

console highlight for npm install umatches other instances

Documentation Is:

  • Missing
  • Needed
  • Confusing
  • Not Sure?

Please Explain in Detail...

currently, the 'npm install schema-utils' command in the README.md appears in blue font because of 'console' tag in the readme markdown. It doesn't match other instances of 'npm install webpack' and 'npm install webpack-cli' in the org's repos.

Your Proposal for Changes

I believe removing the console tag would help.

support typescript loaders

  • Operating System: any
  • Node Version: any
  • NPM Version: any
  • webpack Version: @4
  • schema-utils Version: latest

Feature Proposal

I'm writing loader on TypeScript and it will be awesome if schema-utils will provide definitions respecting JSON schema specification (see @types/json-schema) + I did not found out (from small documentation on webpack.js.org) is it possible to increase DX (change error message, show possible options, i.e. developer made mistake in option name and I want provide suggestions)

Feature Use Case

Increase DX, TypeScript support

UPD: found out from code that webpack show suggestions depending on provided schema

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.