Skip to content

Commit

Permalink
chore: work around Ajv module bug in generated code (#256)
Browse files Browse the repository at this point in the history
JavaScript module inconsistency strikes again.

In some cases, Ajv will inject `require` calls into generated code even
if you ask it to generate ESM. [This is a bug][0].

For example, here's something it adds if you use [the string `minLength`
or `maxLength` properties][1]:

    // ...
    const func2 = require("ajv/dist/runtime/ucs2length").default;
    // ...

That won't work in an ESM environment.

As a workaround, I inject the following into our generated code:

    import { createRequire } from 'node:module';
    const require = createRequire(import.meta.url);

This, along with moving `ajv` to production dependencies, should work
around this issue until the bug is fixed.

[0]: ajv-validator/ajv#2209
[1]: https://json-schema.org/understanding-json-schema/reference/string#length
  • Loading branch information
EvanHahn authored Sep 12, 2024
1 parent 887b2e6 commit 149845f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 11 deletions.
13 changes: 4 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
"@json-schema-tools/dereferencer": "^1.6.3",
"@types/compact-encoding": "^2.15.0",
"@types/json-schema": "^7.0.12",
"ajv": "^8.12.0",
"c8": "^8.0.1",
"cpy-cli": "^5.0.0",
"eslint": "^8.46.0",
Expand All @@ -61,6 +60,7 @@
"typescript": "^5.5.4"
},
"dependencies": {
"ajv": "^8.12.0",
"compact-encoding": "^2.12.0",
"protobufjs": "^7.2.5",
"type-fest": "^4.26.0"
Expand Down
10 changes: 9 additions & 1 deletion scripts/lib/generate-validations.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,13 @@ export function generateValidations(config, jsonSchemas) {
ajv.addKeyword('meta:enum')

// generate validation code
return '// @ts-nocheck\n' + standaloneCode(ajv, schemaExports)
return [
'// @ts-nocheck',
// AJV has [a bug when generating ESM code][0]: it includes `require` in the
// output. We should be able to remove this once the bug is fixed.
// [0]: https://github.com/ajv-validator/ajv/issues/2209
"import { createRequire } from 'node:module';",
'const require = createRequire(import.meta.url);',
standaloneCode(ajv, schemaExports),
].join('\n')
}

0 comments on commit 149845f

Please sign in to comment.