Skip to content
This repository has been archived by the owner on Dec 12, 2024. It is now read-only.

Commit

Permalink
Replace require with import in compiled validators
Browse files Browse the repository at this point in the history
  • Loading branch information
Diane Huxley committed Mar 27, 2024
1 parent e7e5408 commit 7540d80
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
22 changes: 20 additions & 2 deletions packages/protocol/build/compile-validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,26 @@ for (const schemaName in schemas) {
validator.addSchema(schemas[schemaName], schemaName)
}

const moduleCode = standaloneCode(validator)
const generatedCode = standaloneCode(validator)

// https://github.com/ajv-validator/ajv/issues/2209
// ESM generation is broken in AJV standalone.
// In particular, it will "require" files from AJVs runtime directory instead of "import"ing.
function replaceRequireWithImport(inputString) {
const variableNameRegex = /\w+/; // Matches the variable name
const moduleNameRegex = /[^"']+/; // Matches the module name
const regex = new RegExp(
`const\\s+(${variableNameRegex.source})\\s*=\\s*require\\s*\\(\\s*[\"'](${moduleNameRegex.source})[\"']\\s*\\)\\.default`,
'g'
);

const replacedString = inputString.replace(regex, 'import { default as $1 } from "$2.js"');
return replacedString;
}
const moduleCode = replaceRequireWithImport(generatedCode)


const __dirname = url.fileURLToPath(new URL('.', import.meta.url))

await mkdirp(path.join(__dirname, '../generated'))
fs.writeFileSync(path.join(__dirname, '../generated/compiled-validators.cjs'), moduleCode)
fs.writeFileSync(path.join(__dirname, '../generated/compiled-validators.js'), moduleCode)
2 changes: 1 addition & 1 deletion packages/protocol/src/validator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { ErrorObject } from 'ajv'
// validator functions are compiled at build time. check ./build/compile-validators.js for more details
import * as compiledValidators from '../generated/compiled-validators.cjs'
import * as compiledValidators from '../generated/compiled-validators.js'

/**
* validates the payload against a json schema identified by name
Expand Down

0 comments on commit 7540d80

Please sign in to comment.