cfworker-provider.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. "use strict";
  2. /**
  3. * Cloudflare Worker-compatible JSON Schema validator provider
  4. *
  5. * This provider uses @cfworker/json-schema for validation without code generation,
  6. * making it compatible with edge runtimes like Cloudflare Workers that restrict
  7. * eval and new Function.
  8. */
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. exports.CfWorkerJsonSchemaValidator = void 0;
  11. const json_schema_1 = require("@cfworker/json-schema");
  12. /**
  13. *
  14. * @example
  15. * ```typescript
  16. * // Use with default configuration (2020-12, shortcircuit)
  17. * const validator = new CfWorkerJsonSchemaValidator();
  18. *
  19. * // Use with custom configuration
  20. * const validator = new CfWorkerJsonSchemaValidator({
  21. * draft: '2020-12',
  22. * shortcircuit: false // Report all errors
  23. * });
  24. * ```
  25. */
  26. class CfWorkerJsonSchemaValidator {
  27. /**
  28. * Create a validator
  29. *
  30. * @param options - Configuration options
  31. * @param options.shortcircuit - If true, stop validation after first error (default: true)
  32. * @param options.draft - JSON Schema draft version to use (default: '2020-12')
  33. */
  34. constructor(options) {
  35. this.shortcircuit = options?.shortcircuit ?? true;
  36. this.draft = options?.draft ?? '2020-12';
  37. }
  38. /**
  39. * Create a validator for the given JSON Schema
  40. *
  41. * Unlike AJV, this validator is not cached internally
  42. *
  43. * @param schema - Standard JSON Schema object
  44. * @returns A validator function that validates input data
  45. */
  46. getValidator(schema) {
  47. // Cast to the cfworker Schema type - our JsonSchemaType is structurally compatible
  48. const validator = new json_schema_1.Validator(schema, this.draft, this.shortcircuit);
  49. return (input) => {
  50. const result = validator.validate(input);
  51. if (result.valid) {
  52. return {
  53. valid: true,
  54. data: input,
  55. errorMessage: undefined
  56. };
  57. }
  58. else {
  59. return {
  60. valid: false,
  61. data: undefined,
  62. errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ')
  63. };
  64. }
  65. };
  66. }
  67. }
  68. exports.CfWorkerJsonSchemaValidator = CfWorkerJsonSchemaValidator;
  69. //# sourceMappingURL=cfworker-provider.js.map