diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 415889c83..d374fbd9e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,9 +15,9 @@ jobs: node-version: [16.x, 18.x, 20.x, 21.x] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: use Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v2 + uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - run: npm install @@ -32,6 +32,6 @@ jobs: - run: npm run build - run: npm run test-ci - name: coveralls - uses: coverallsapp/github-action@master + uses: coverallsapp/github-action@v2 with: github-token: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2da03454b..35bf8ed67 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,21 +8,21 @@ jobs: publish-npm: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - uses: actions/setup-node@v2 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: - node-version: 14 + node-version: 18 registry-url: https://registry.npmjs.org/ - run: npm install - run: git submodule update --init - run: npm run test-ci - name: Publish beta version to npm - if: "github.event.release.prerelease" + if: ${{ github.event.release.prerelease }} run: npm publish --tag beta env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} - name: Publish to npm - if: "!github.event.release.prerelease" + if: ${{ !github.event.release.prerelease }} run: npm publish env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/README.md b/README.md index c10422e63..d8ee276ce 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The fastest JSON validator for Node.js and browser. Supports JSON Schema draft-04/06/07/2019-09/2020-12 ([draft-04 support](https://ajv.js.org/json-schema.html#draft-04) requires ajv-draft-04 package) and JSON Type Definition [RFC8927](https://datatracker.ietf.org/doc/rfc8927/). -[![build](https://github.com/ajv-validator/ajv/workflows/build/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) +[![build](https://github.com/ajv-validator/ajv/actions/workflows/build.yml/badge.svg)](https://github.com/ajv-validator/ajv/actions?query=workflow%3Abuild) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) diff --git a/docs/json-schema.md b/docs/json-schema.md index ac2d82d84..c888c636d 100644 --- a/docs/json-schema.md +++ b/docs/json-schema.md @@ -280,6 +280,10 @@ The value of the keyword should be a number. The data to be valid should be a mu ### `maxLength` / `minLength` +::: warning Grapheme clusters will count as multiple characters +Certain charsets have characters that are made up of multiple Unicode code points. These [grapheme clusters](https://www.unicode.org/reports/tr29/tr29-17.html#Grapheme_Cluster_Boundaries) are counted as multiple in length calculations. +::: + The value of the keywords should be a number. The data to be valid should have length satisfying this rule. Unicode pairs are counted as a single character. **Examples** diff --git a/docs/options.md b/docs/options.md index c4a303680..6f74b02b3 100644 --- a/docs/options.md +++ b/docs/options.md @@ -240,7 +240,7 @@ An array or object of schemas that will be added to the instance. In case you pa ### logger -Sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). +Sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](./api.md#error-logging). Option values: diff --git a/docs/packages/README.md b/docs/packages/README.md index e16bd3483..1d6bf48db 100644 --- a/docs/packages/README.md +++ b/docs/packages/README.md @@ -14,11 +14,11 @@ If you have published a useful plugin please submit a PR to add it to the next s ## Related packages -- [ajv-formats](./ajv-formats.md) - formats defined in JSON Schema specification -- [ajv-keywords](./ajv-keywords) - additional validation keywords (select, typeof, etc.) -- [ajv-errors](./ajv-errors.md) - defining error messages in the schema -- [ajv-i18n](./ajv-i18n) - internationalised error messages -- [ajv-cli](./ajv-cli.md) - command line interface +- [ajv-formats](https://github.com/ajv-validator/ajv-formats) - formats defined in JSON Schema specification +- [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - additional validation keywords (select, typeof, etc.) +- [ajv-errors](https://github.com/ajv-validator/ajv-errors) - defining error messages in the schema +- [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages +- [ajv-cli](https://github.com/ajv-validator/ajv-cli) - command line interface - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - MongoDB's bsonType formats - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - formats for draft-2019-09 that are not included in [ajv-formats](./ajv-formats.md) (`idn-hostname`, `idn-email`, `iri` and `iri-reference`) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - keywords $merge and $patch diff --git a/docs/security.md b/docs/security.md index 7ecf8b031..da851ce5e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -93,7 +93,7 @@ If you use Ajv to validate data from untrusted sources **it is strongly recommen - making assessment of "format" implementations in [ajv-formats](https://github.com/ajv-validator/ajv-formats). - passing `"fast"` option to ajv-formats plugin (see its docs) that simplifies some of the regular expressions (although it does not guarantee that they are safe). -- replacing format implementations provided by ajv-formats with your own implementations of "format" keyword that either use different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. +- replacing format implementations provided by ajv-formats with your own implementations of "format" keyword that either use different regular expressions or another approach to format validation. Please see [addFormat](https://github.com/ajv-validator/ajv/blob/master/docs/api.md#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by ajv-formats as potentially unsafe and make your own assessment of their suitability for your validation scenarios. diff --git a/lib/2019.ts b/lib/2019.ts index 45a3fa535..3f7194f1b 100644 --- a/lib/2019.ts +++ b/lib/2019.ts @@ -10,7 +10,7 @@ import addMetaSchema2019 from "./refs/json-schema-2019-09" const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema" -class Ajv2019 extends AjvCore { +export class Ajv2019 extends AjvCore { constructor(opts: Options = {}) { super({ ...opts, @@ -44,6 +44,7 @@ class Ajv2019 extends AjvCore { } module.exports = exports = Ajv2019 +module.exports.Ajv2019 = Ajv2019 Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv2019 diff --git a/lib/2020.ts b/lib/2020.ts index afbdda200..cfb36af9d 100644 --- a/lib/2020.ts +++ b/lib/2020.ts @@ -7,7 +7,7 @@ import addMetaSchema2020 from "./refs/json-schema-2020-12" const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema" -class Ajv2020 extends AjvCore { +export class Ajv2020 extends AjvCore { constructor(opts: Options = {}) { super({ ...opts, @@ -38,6 +38,7 @@ class Ajv2020 extends AjvCore { } module.exports = exports = Ajv2020 +module.exports.Ajv2020 = Ajv2020 Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv2020 diff --git a/lib/ajv.ts b/lib/ajv.ts index 7f87c8aea..8275b93a8 100644 --- a/lib/ajv.ts +++ b/lib/ajv.ts @@ -8,7 +8,7 @@ const META_SUPPORT_DATA = ["/properties"] const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema" -class Ajv extends AjvCore { +export class Ajv extends AjvCore { _addVocabularies(): void { super._addVocabularies() draft7Vocabularies.forEach((v) => this.addVocabulary(v)) @@ -32,6 +32,7 @@ class Ajv extends AjvCore { } module.exports = exports = Ajv +module.exports.Ajv = Ajv Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv diff --git a/lib/compile/codegen/index.ts b/lib/compile/codegen/index.ts index 9d29055dc..5a6d1ee58 100644 --- a/lib/compile/codegen/index.ts +++ b/lib/compile/codegen/index.ts @@ -41,7 +41,11 @@ abstract class Node { } class Def extends Node { - constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) { + constructor( + private readonly varKind: Name, + private readonly name: Name, + private rhs?: SafeExpr + ) { super() } @@ -63,7 +67,11 @@ class Def extends Node { } class Assign extends Node { - constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) { + constructor( + readonly lhs: Code, + public rhs: SafeExpr, + private readonly sideEffects?: boolean + ) { super() } @@ -84,7 +92,12 @@ class Assign extends Node { } class AssignOp extends Assign { - constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) { + constructor( + lhs: Code, + private readonly op: Code, + rhs: SafeExpr, + sideEffects?: boolean + ) { super(lhs, rhs, sideEffects) } @@ -211,7 +224,10 @@ class Else extends BlockNode { class If extends BlockNode { static readonly kind = "if" else?: If | Else - constructor(private condition: Code | boolean, nodes?: ChildNode[]) { + constructor( + private condition: Code | boolean, + nodes?: ChildNode[] + ) { super(nodes) } @@ -331,7 +347,11 @@ class ForIter extends For { class Func extends BlockNode { static readonly kind = "func" - constructor(public name: Name, public args: Code, public async?: boolean) { + constructor( + public name: Name, + public args: Code, + public async?: boolean + ) { super() } diff --git a/lib/compile/validate/dataType.ts b/lib/compile/validate/dataType.ts index b315c2ce9..d8142b3e1 100644 --- a/lib/compile/validate/dataType.ts +++ b/lib/compile/validate/dataType.ts @@ -30,6 +30,7 @@ export function getSchemaTypes(schema: AnySchemaObject): JSONType[] { return types } +// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents export function getJSONTypes(ts: unknown | unknown[]): JSONType[] { const types: unknown[] = Array.isArray(ts) ? ts : ts ? [ts] : [] if (types.every(isJSONType)) return types diff --git a/lib/core.ts b/lib/core.ts index 3686ffe76..e41ca3e2a 100644 --- a/lib/core.ts +++ b/lib/core.ts @@ -343,14 +343,17 @@ export default class Ajv { validate(schema: JTDSchemaType, data: unknown): data is T // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars validate( schema: T, data: unknown ): data is JTDDataType + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents validate(schema: AsyncSchema, data: unknown | T): Promise validate(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise validate( schemaKeyRef: AnySchema | string, // key, ref or schema object + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents data: unknown | T // to be validated ): boolean | Promise { let v: AnyValidateFunction | undefined @@ -374,6 +377,7 @@ export default class Ajv { compile(schema: JTDSchemaType, _meta?: boolean): ValidateFunction // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload + // eslint-disable-next-line @typescript-eslint/no-unused-vars compile( schema: T, _meta?: boolean diff --git a/lib/jtd.ts b/lib/jtd.ts index 96eb7b9dc..a7e7bce3b 100644 --- a/lib/jtd.ts +++ b/lib/jtd.ts @@ -35,7 +35,7 @@ type JTDOptions = CurrentOptions & { multipleOfPrecision?: never } -class Ajv extends AjvCore { +export class Ajv extends AjvCore { constructor(opts: JTDOptions = {}) { super({ ...opts, @@ -93,6 +93,7 @@ class Ajv extends AjvCore { } module.exports = exports = Ajv +module.exports.Ajv = Ajv Object.defineProperty(exports, "__esModule", {value: true}) export default Ajv diff --git a/lib/types/index.ts b/lib/types/index.ts index 123d9df16..b5ef53eeb 100644 --- a/lib/types/index.ts +++ b/lib/types/index.ts @@ -48,6 +48,7 @@ export interface DataValidationCxt } export interface ValidateFunction { + // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents (this: Ajv | any, data: any, dataCxt?: DataValidationCxt): data is T errors?: null | ErrorObject[] evaluated?: Evaluated @@ -138,9 +139,12 @@ export interface DataValidateFunction { } export interface SchemaValidateFunction { - (schema: any, data: any, parentSchema?: AnySchemaObject, dataCxt?: DataValidationCxt): - | boolean - | Promise + ( + schema: any, + data: any, + parentSchema?: AnySchemaObject, + dataCxt?: DataValidationCxt + ): boolean | Promise errors?: Partial[] } diff --git a/lib/vocabularies/discriminator/index.ts b/lib/vocabularies/discriminator/index.ts index 98f0f8cfb..19ae6049f 100644 --- a/lib/vocabularies/discriminator/index.ts +++ b/lib/vocabularies/discriminator/index.ts @@ -3,6 +3,7 @@ import type {KeywordCxt} from "../../compile/validate" import {_, getProperty, Name} from "../../compile/codegen" import {DiscrError, DiscrErrorObj} from "../discriminator/types" import {resolveRef, SchemaEnv} from "../../compile" +import MissingRefError from "../../compile/ref_error" import {schemaHasRulesButRef} from "../../compile/util" export type DiscriminatorError = DiscrErrorObj | DiscrErrorObj @@ -66,8 +67,10 @@ const def: CodeKeywordDefinition = { for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i] if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { - sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch?.$ref) + const ref = sch.$ref + sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref) if (sch instanceof SchemaEnv) sch = sch.schema + if (sch === undefined) throw new MissingRefError(it.opts.uriResolver, it.baseId, ref) } const propSch = sch?.properties?.[tagName] if (typeof propSch != "object") { diff --git a/package.json b/package.json index 8ddabaa04..ca56231a8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "ajv", - "version": "8.12.0", + "version": "8.16.0", "description": "Another JSON Schema Validator", "main": "dist/ajv.js", "types": "dist/ajv.d.ts", @@ -64,25 +64,25 @@ "uri-js": "^4.4.1" }, "devDependencies": { - "@ajv-validator/config": "^0.3.0", + "@ajv-validator/config": "^0.5.0", "@rollup/plugin-commonjs": "^25.0.7", "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-typescript": "^11.1.6", "@types/chai": "^4.3.11", "@types/mocha": "^10.0.6", - "@types/node": "^20.11.19", + "@types/node": "^20.11.30", "@types/require-from-string": "^1.2.3", - "@typescript-eslint/eslint-plugin": "^3.10.1", - "@typescript-eslint/parser": "^3.10.1", - "ajv-formats": "^3.0.0-rc.0", + "@typescript-eslint/eslint-plugin": "^7.3.1", + "@typescript-eslint/parser": "^7.3.1", + "ajv-formats": "^3.0.1", "browserify": "^17.0.0", "chai": "^4.4.1", "cross-env": "^7.0.3", "dayjs": "^1.11.10", "dayjs-plugin-utc": "^0.1.2", - "eslint": "^7.32.0", - "eslint-config-prettier": "^7.2.0", + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", "fast-uri": "^2.3.0", "glob": "^10.3.10", "husky": "^9.0.11", @@ -98,13 +98,13 @@ "module-from-string": "^3.3.0", "node-fetch": "^3.3.2", "nyc": "^15.1.0", - "prettier": "^2.8.8", + "prettier": "3.0.3", "re2": "^1.20.9", "rollup": "^2.79.1", "rollup-plugin-terser": "^7.0.2", "ts-node": "^10.9.2", "tsify": "^5.0.4", - "typescript": "^4.9.5" + "typescript": "5.3.3" }, "collective": { "type": "opencollective", diff --git a/spec/discriminator.spec.ts b/spec/discriminator.spec.ts index 28ff12146..74ba33ef0 100644 --- a/spec/discriminator.spec.ts +++ b/spec/discriminator.spec.ts @@ -159,6 +159,67 @@ describe("discriminator keyword", function () { }) }) + describe("schema with external $refs", () => { + const schemas = { + main: { + type: "object", + discriminator: {propertyName: "foo"}, + required: ["foo"], + oneOf: [ + { + $ref: "schema1", + }, + { + $ref: "schema2", + }, + ], + }, + schema1: { + type: "object", + properties: { + foo: {const: "x"}, + }, + }, + schema2: { + type: "object", + properties: { + foo: {enum: ["y", "z"]}, + }, + }, + } + + const data = {foo: "x"} + const badData = {foo: "w"} + + it("compile should resolve each $ref to a schema that was added with addSchema", () => { + const opts = { + discriminator: true, + } + const ajv = new _Ajv(opts) + ajv.addSchema(schemas.main, "https://host/main") + ajv.addSchema(schemas.schema1, "https://host/schema1") + ajv.addSchema(schemas.schema2, "https://host/schema2") + + const validate = ajv.compile({$ref: "https://host/main"}) + assert.strictEqual(validate(data), true) + assert.strictEqual(validate(badData), false) + }) + it("compileAsync should loadSchema each $ref", async () => { + const opts = { + discriminator: true, + loadSchema(url) { + if (!url.startsWith("https://host/")) return undefined + const name = url.substring("https://host/".length) + return schemas[name] + }, + } + const ajv = new _Ajv(opts) + const validate = await ajv.compileAsync({$ref: "https://host/main"}) + assert.strictEqual(validate(data), true) + assert.strictEqual(validate(badData), false) + }) + }) + describe("validation with deeply referenced schemas", () => { const schema = [ { diff --git a/spec/types/async-validate.spec.ts b/spec/types/async-validate.spec.ts index 8e3f0588c..83a61417a 100644 --- a/spec/types/async-validate.spec.ts +++ b/spec/types/async-validate.spec.ts @@ -109,10 +109,10 @@ describe("$async validation and type guards", () => { const data: unknown = {foo: 1} let result: boolean | Promise if ((result = validate(data))) { - if (typeof result == "boolean") { - data.foo.should.equal(1) - } else { + if (result instanceof Promise) { await result.then((_data) => _data.foo.should.equal(1)) + } else { + should.fail() } } else { should.fail()