{"_id":"@fastify/ajv-compiler@4.0.6","bugs":{"url":"https://github.com/fastify/ajv-compiler/issues"},"dist":{"shasum":"f4f1ea994d7fb3e05906f7cba000200327d0c4a9","tarball":"http://registry-npm.ywwl.com/@fastify/ajv-compiler/download/@fastify/ajv-compiler-4.0.6.tgz","fileCount":22,"integrity":"sha512-NtuzM0SfaMJbGlnjr9LWQUN5LzgSrbB8tf/wRZNas+4E1O/Nmzl53e7ruT61HDZyRCJGC6FxIogmNZO1c5ETBA==","signatures":[{"sig":"MEUCIQDr6cluSOJRi59TB3pInheSWcj/wV3MWt7Gkk02l0mOkwIgTiX2lG58LGs6zZrHDU9KVcqo/pQSHH7/FQKO9EbAMJo=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEQCIG1ylsFRAIHH5RLK6uowMarXyjCo4uEiXUjbJoqnE5UNAiB08DsiZ50bs4Tglf3cegspeKmp7OK/mfAirAXjFQIsqA=="}],"unpackedSize":58274,"size":14075,"noattachment":false,"key":"/@fastify/ajv-compiler/-/@fastify/ajv-compiler-4.0.6.tgz"},"main":"index.js","name":"@fastify/ajv-compiler","type":"commonjs","types":"types/index.d.ts","author":{"url":"https://github.com/Eomm","name":"Manuel Spigolon","email":"behemoth89@gmail.com"},"funding":[{"url":"https://github.com/sponsors/fastify","type":"github"},{"url":"https://opencollective.com/fastify","type":"opencollective"}],"gitHead":"18da46820a1e8c05271ec21d7ddb65b404db58e4","license":"MIT","scripts":{"lint":"eslint","test":"npm run unit && npm run test:typescript","unit":"c8 --100 node --test","lint:fix":"eslint --fix","ajv:compile":"ajv compile -s test/source.json -o test/validate_schema.js","test:typescript":"tstyche"},"version":"4.0.6","_npmUser":{"name":"eomm","email":"behemoth89@gmail.com"},"homepage":"https://github.com/fastify/ajv-compiler#readme","keywords":["ajv","validator","schema","compiler","fastify"],"repository":{"url":"git+https://github.com/fastify/ajv-compiler.git","type":"git"},"_npmVersion":"11.11.0","description":"Build and manage the AJV instances for the fastify framework","directories":{"test":"test"},"maintainers":[{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"},{"name":"jsumners","email":"james.sumners@gmail.com"},{"name":"eomm","email":"behemoth89@gmail.com"},{"name":"climba03003","email":"kaka@kakawebsitedemo.com"},{"name":"metcoder95","email":"me@metcoder.dev"}],"_nodeVersion":"24.14.1","contributors":[{"name":"Matteo Collina","email":"hello@matteocollina.com"},{"name":"Aras Abbasi","email":"aras.abbasi@gmail.com"},{"url":"https://james.sumners.info","name":"James Sumners"},{"url":"https://github.com/fdawgs","name":"Frazer Smith","email":"frazer.dev@icloud.com"}],"dependencies":{"ajv":"^8.12.0","fast-uri":"^4.0.0","ajv-formats":"^3.0.1"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^12.0.0","eslint":"^9.17.0","ajv-cli":"^5.0.0","fastify":"^5.0.0","tstyche":"^7.0.0","ajv-i18n":"^4.2.0","ajv-errors":"^3.0.0","cronometro":"^6.0.2","neostandard":"^0.13.0","ajv-merge-patch":"^5.0.1","sanitize-filename":"^1.6.3","require-from-string":"^2.0.2"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/ajv-compiler_4.0.6_1786201244851_0.9541843900129525"},"readme":"# @fastify/ajv-compiler\n\n[![CI](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/ajv-compiler/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/@fastify/ajv-compiler.svg?style=flat)](https://www.npmjs.com/package/@fastify/ajv-compiler)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nThis module manages the [`ajv`](https://www.npmjs.com/package/ajv) instances for the Fastify framework.\nIt isolates the `ajv` dependency so that the AJV version is not tightly coupled to the Fastify version.\nThis allows the user to decide which version of AJV to use in their Fastify-based application.\n\n\n## Versions\n\n| `@fastify/ajv-compiler` | `ajv` | Default in `fastify` |\n|------------------------:|------:|---------------------:|\n|                    v4.x |  v8.x |                 ^5.x |\n|                    v3.x |  v8.x |                 ^4.x |\n|                    v2.x |  v8.x |                    - |\n|                    v1.x |  v6.x |                ^3.14 |\n\n### AJV Configuration\n\nThe Fastify's default [`ajv` options](https://github.com/ajv-validator/ajv/tree/v6#options) are:\n\n```js\n{\n  coerceTypes: 'array',\n  useDefaults: true,\n  removeAdditional: true,\n  uriResolver: require('fast-uri'),\n  addUsedSchema: false,\n  // Explicitly set allErrors to `false`.\n  // When set to `true`, a DoS attack is possible.\n  allErrors: false\n}\n```\n\nMoreover, the [`ajv-formats`](https://www.npmjs.com/package/ajv-formats) module is included by default.\nIf you need to customize it, check the _usage_ section below.\n\nTo customize the `ajv` options, see how in the [Fastify documentation](https://fastify.dev/docs/latest/Reference/Server/#ajv).\n\n\n## Usage\n\nThis module is already used as default by Fastify.\nIf you need to provide your server instance with a different version, refer to [the Fastify docs](https://fastify.dev/docs/latest/Reference/Server/#schemacontroller).\n\n### Customize the `ajv-formats` plugin\n\nThe `format` keyword is not part of the official `ajv` module since v7. To use it, you need to install the `ajv-formats` module and this module\ndoes it for you with the default configuration.\n\nIf you need to configure the `ajv-formats` plugin you can do it using the standard Fastify configuration:\n\n```js\nconst app = fastify({\n  ajv: {\n    plugins: [[require('ajv-formats'), { mode: 'fast' }]]\n  }\n})\n```\n\nIn this way, your setup will have precedence over the `@fastify/ajv-compiler` default configuration.\n\n### Customize the `ajv` instance\n\nIf you need to customize the `ajv` instance and take full control of its configuration, you can do it by\nusing the `onCreate` option in the Fastify configuration that accepts a synchronous function that receives the `ajv` instance:\n\n```js\nconst app = fastify({\n  ajv: {\n    onCreate: (ajv) => {\n      // Modify the ajv instance as you need.\n      ajv.addFormat('myFormat', (data) => typeof data === 'string')\n    }\n  }\n})\n```\n\n### Fastify with JTD\n\nThe [JSON Type Definition](https://www.rfc-editor.org/rfc/rfc8927.html) feature is supported by AJV v8.x and you can benefit from it in your Fastify application.\n\nWith Fastify v3.20.x and higher, you can use the `@fastify/ajv-compiler` module to load JSON Type Definitions like so:\n\n```js\nconst factory = require('@fastify/ajv-compiler')()\n\nconst app = fastify({\n  jsonShorthand: false,\n  ajv: {\n    customOptions: { }, // additional JTD options\n    mode: 'JTD'\n  },\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n```\n\nThe default AJV JTD options are the same as [Fastify's default options](#AJV-Configuration).\n\n#### Fastify with JTD and serialization\n\nYou can use JTD Schemas to serialize your response object too:\n\n```js\nconst factoryValidator = require('@fastify/ajv-compiler')()\nconst factorySerializer = require('@fastify/ajv-compiler')({ jtdSerializer: true })\n\nconst app = fastify({\n  jsonShorthand: false,\n  ajv: {\n    customOptions: { }, // additional JTD options\n    mode: 'JTD'\n  },\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factoryValidator,\n      buildSerializer: factorySerializer\n    }\n  }\n})\n```\n\n\n### AJV Standalone\n\nAJV v8 introduced a [standalone feature](https://ajv.js.org/standalone.html) that lets you pre-compile your schemas and use them in your application for a faster startup.\n\nTo use this feature, you must be aware of the following:\n\n1. You must generate and save the application's compiled schemas.\n2. Read the compiled schemas from the file and provide them back to your Fastify application.\n\n\n#### Generate and save the compiled schemas\n\nFastify helps you to generate the validation schemas functions and it is your choice to save them where you want.\nTo accomplish this, you must use a new compiler: `StandaloneValidator`.\n\nYou must provide 2 parameters to this compiler:\n\n- `readMode: false`: a boolean to indicate that you want to generate the schemas functions string.\n- `storeFunction`\" a sync function that must store the source code of the schemas functions. You may provide an async function too, but you must manage errors.\n\nWhen `readMode: false`, **the compiler is meant to be used in development ONLY**.\n\n\n```js\nconst { StandaloneValidator } = require('@fastify/ajv-compiler')\nconst factory = StandaloneValidator({\n  readMode: false,\n  storeFunction (routeOpts, schemaValidationCode) {\n    // routeOpts is like: { schema, method, url, httpPart }\n    // schemaValidationCode is a string source code that is the compiled schema function\n    const fileName = generateFileName(routeOpts)\n    fs.writeFileSync(path.join(__dirname, fileName), schemaValidationCode)\n  }\n})\n\nconst app = fastify({\n  jsonShorthand: false,\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n\n// ... add all your routes with schemas ...\n\napp.ready().then(() => {\n  // at this stage all your schemas are compiled and stored in the file system\n  // now it is important to turn off the readMode\n})\n```\n\n#### Read the compiled schemas functions\n\nAt this stage, you should have a file for every route's schema.\nTo use them, you must use the `StandaloneValidator` with the parameters:\n\n- `readMode: true`: a boolean to indicate that you want to read and use the schemas functions string.\n- `restoreFunction`\" a sync function that must return a function to validate the route.\n\nImportant keep away before you continue reading the documentation:\n\n- when you use the `readMode: true`, the application schemas are not compiled (they are ignored). So, if you change your schemas, you must recompile them!\n- as you can see, you must relate the route's schema to the file name using the `routeOpts` object. You may use the `routeOpts.schema.$id` field to do so, it is up to you to define a unique schema identifier.\n\n```js\nconst { StandaloneValidator } = require('@fastify/ajv-compiler')\nconst factory = StandaloneValidator({\n  readMode: true,\n  restoreFunction (routeOpts) {\n    // routeOpts is like: { schema, method, url, httpPart }\n    const fileName = generateFileName(routeOpts)\n    return require(path.join(__dirname, fileName))\n  }\n})\n\nconst app = fastify({\n  jsonShorthand: false,\n  schemaController: {\n    compilersFactory: {\n      buildValidator: factory\n    }\n  }\n})\n\n// ... add all your routes with schemas as before...\n\napp.listen({ port: 3000 })\n```\n\n### How it works\n\nThis module provides a factory function to produce [Validator Compilers](https://fastify.dev/docs/latest/Reference/Server/#validatorcompiler) functions.\n\nThe Fastify factory function is just one per server instance and it is called for every encapsulated context created by the application through the `fastify.register()` call.\n\nEvery Validator Compiler produced has a dedicated AJV instance, so this factory will try to produce as less as possible AJV instances to reduce the memory footprint and the startup time.\n\nThe variables involved to choose if a Validator Compiler can be reused are:\n\n- the AJV configuration: it is [one per server](https://fastify.dev/docs/latest/Reference/Server/#ajv)\n- the external JSON schemas: once a new schema is added to a fastify's context, calling `fastify.addSchema()`, it will cause a new AJV initialization\n\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","publish_time":1786201244931,"_cnpm_publish_time":1786201244931,"dist-tags":{"latest":"4.0.7","next":"4.0.0-pre.fv5.1"}}