ata-validator 1.48.0 → 1.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/aot-impl.js CHANGED
@@ -113,6 +113,9 @@ function toStandalone(validator) {
113
113
  // Also capture error function source for zero-compile standalone load
114
114
  const jsErrFn = compileToJSCodegenWithErrors(
115
115
  typeof validator._schemaObj === 'object' ? validator._schemaObj : {},
116
+ null,
117
+ null,
118
+ { noOrdinal: true },
116
119
  );
117
120
  const errSrc = jsErrFn && jsErrFn._errSource ? jsErrFn._errSource : '';
118
121
 
@@ -349,7 +352,10 @@ function toStandaloneModule(validator, opts) {
349
352
  const jsFn = validator._jsFn;
350
353
  if (!jsFn || !jsFn._source) return null;
351
354
  const format = (opts && opts.format) || 'esm';
352
- const abortEarly = !!(opts && opts.abortEarly);
355
+ // A compact module (toCompactModule) carries the verdict and its schema, and
356
+ // takes its errors from the shared runtime at this import specifier.
357
+ const errorRuntime = opts && typeof opts._errorRuntime === 'string' ? opts._errorRuntime : null;
358
+ const abortEarly = !!(opts && opts.abortEarly) || errorRuntime !== null;
353
359
  const source = !!(opts && opts.source);
354
360
  const sourceMap = opts && opts.sourceMap ? opts.sourceMap : null;
355
361
  const schemaFile = opts && opts.schemaFile ? opts.schemaFile : null;
@@ -388,11 +394,14 @@ function toStandaloneModule(validator, opts) {
388
394
  `const _ER = function(e) { _ataStamp(e); this.valid = false; this.errors = e; };\n` +
389
395
  `${codeTableSource(onePass.keywords, onePass.formats)}const _vC = (function() {\n${onePass.core}\n})();\n`;
390
396
  } else if (!abortEarly) {
397
+ // A module returns the collector's errors as they are and never sorts
398
+ // them, so the ordinal the runtime sorts by (`_o`) has no reader there;
399
+ // it leaked into every error object a module reported.
391
400
  jsErrFn = compileToJSCodegenWithErrors(
392
401
  typeof validator._schemaObj === 'object' ? validator._schemaObj : {},
393
402
  null,
394
403
  validator._userFormats,
395
- (source && sourceMap && schemaFile) ? { sourceMap, schemaFile, frames: sourceFrames } : null,
404
+ (source && sourceMap && schemaFile) ? { sourceMap, schemaFile, frames: sourceFrames, noOrdinal: true } : { noOrdinal: true },
396
405
  );
397
406
  const errSrc = jsErrFn && jsErrFn._errSource ? jsErrFn._errSource : '';
398
407
  if (errSrc && jsErrFn._errFactory) {
@@ -482,7 +491,43 @@ function toStandaloneModule(validator, opts) {
482
491
  const fmt = emitFormatDecls(jsFn._formatClosures, opts && opts.formatMode, 'const');
483
492
  const formatDecls = fmt.decls;
484
493
 
485
- const validBody = onePass !== null
494
+ // A compact module takes the linear-time pattern engine from the runtime,
495
+ // which carries it anyway, instead of embedding a copy (2.9 KB gzipped,
496
+ // minified) in every module that has a pattern the platform RegExp does not
497
+ // run.
498
+ const usesSafeRe = errorRuntime !== null && ((jsFn && jsFn._usesSafeRe) || (jsErrFn && jsErrFn._usesSafeRe));
499
+ let compactCore = '';
500
+ if (errorRuntime !== null) {
501
+ const { stripAnnotations } = require('./schema-strip');
502
+ const { isV1Dialect } = require('./dialect');
503
+ const sch = typeof validator._schemaObj === 'object' ? validator._schemaObj : validator._schemaObj;
504
+ // Embedded as JSON text and parsed: a literal would turn a "__proto__"
505
+ // key into the object's prototype, and V8 reads JSON faster than an
506
+ // object literal of the same size.
507
+ const text = JSON.stringify(JSON.stringify(stripAnnotations(sch))).replace(/</g, '\\u003c');
508
+ const v1 = sch !== null && typeof sch === 'object' && isV1Dialect(sch);
509
+ // No embedded resource and no anchor anywhere (a key of that name inside
510
+ // a value counts too): the runtime can skip indexing the schema.
511
+ const flat = (() => {
512
+ const seen = new Set();
513
+ const walk = (n, root) => {
514
+ if (n === null || typeof n !== 'object' || seen.has(n)) return true;
515
+ seen.add(n);
516
+ if (Array.isArray(n)) return n.every((x) => walk(x, false));
517
+ if ('$anchor' in n || '$dynamicAnchor' in n || (!root && '$id' in n)) return false;
518
+ return Object.keys(n).every((k) => walk(n[k], false));
519
+ };
520
+ return walk(stripAnnotations(sch), true);
521
+ })();
522
+ const rtOpts = [v1 ? 'v1: true' : '', flat ? 'flat: true' : ''].filter(Boolean).join(', ');
523
+ // Nothing of it runs at import: the schema is parsed and the runtime
524
+ // set up on the first rejected document whose errors are read, so a
525
+ // module that only accepts costs no more to load than its verdict.
526
+ compactCore = `let _ataErrs = null;\nfunction _ataErrors(d) { if (_ataErrs === null) _ataErrs = _ataCreateErrors(JSON.parse(${text})${rtOpts ? ', { ' + rtOpts + ' }' : ''}); return _ataErrs(d); }\n`;
527
+ }
528
+ const validBody = errorRuntime !== null
529
+ ? 'if (_fn(data)) return VALID; const e = _ataErrors(data); return e === null ? ABORT : { valid: false, errors: e }'
530
+ : onePass !== null
486
531
  ? 'return _vC(data)'
487
532
  : errCore
488
533
  ? 'return _fn(data) ? VALID : { valid: false, errors: errFn(data, true).errors }'
@@ -559,7 +604,7 @@ function validateJSON(text) {
559
604
  // schema as the caller wrote it (before dialect normalization), so a build
560
605
  // can compare it against schemaHash(currentSchema) and know the module is
561
606
  // stale without embedding its own fingerprint.
562
- const hashSrc = schemaHash(validator._rawSchema !== undefined ? validator._rawSchema : validator._schemaObj);
607
+ const hashSrc = hashOf(validator);
563
608
  // The schema hash answers "is this module built from a different schema" and
564
609
  // nothing else. Upgrading ata and not re-running the generate step leaves the
565
610
  // hash matching, so the stale module reads as current. The module cannot ask
@@ -583,11 +628,11 @@ function validateJSON(text) {
583
628
  degradedNote += '// NOTE: parse() was requested but could not be generated for this schema;\n// the module has no parse export. Validate and strip with the runtime Validator.\n';
584
629
  }
585
630
  return `// Auto-generated by ata-validator ${ATA_VERSION}, do not edit.
586
- // Schema is embedded; runtime has zero dependency on ata-validator.
631
+ ${errorRuntime === null ? '// Schema is embedded; runtime has zero dependency on ata-validator.' : '// Compact module: the verdict and the schema; errors come from the runtime it imports.'}
587
632
  // Re-run the build after upgrading ata: the version above is what wrote this.
588
633
  ${degradedNote}'use strict';
589
- ${_CP_LEN_SOURCE}
590
- ${safeRePrelude(jsFn, jsErrFn, onePass !== null && onePass.usesSafeRe ? { _usesSafeRe: true } : null)}${schemaSourceConst}const VALID = Object.freeze({ valid: true, errors: Object.freeze([]) });
634
+ ${errorRuntime === null ? '' : format === 'esm' ? `import { createErrors as _ataCreateErrors${usesSafeRe ? ', compileSafe as _ataCompileSafe' : ''} } from ${JSON.stringify(errorRuntime)};\n` : `const { createErrors: _ataCreateErrors${usesSafeRe ? ', compileSafe: _ataCompileSafe' : ''} } = require(${JSON.stringify(errorRuntime)});\n`}${_CP_LEN_SOURCE}
635
+ ${errorRuntime !== null ? (usesSafeRe ? 'const __ataSafeRe = _ataCompileSafe;\n' : '') : safeRePrelude(jsFn, jsErrFn, onePass !== null && onePass.usesSafeRe ? { _usesSafeRe: true } : null)}${schemaSourceConst}const VALID = Object.freeze({ valid: true, errors: Object.freeze([]) });
591
636
  const ABORT = Object.freeze({
592
637
  valid: false,
593
638
  errors: Object.freeze([Object.freeze({
@@ -600,11 +645,155 @@ const ABORT = Object.freeze({
600
645
  ${closureDecls}${sharedBlock}${preambleDecls}${formatDecls}const _fn = function(d) {
601
646
  ${src}
602
647
  };
603
- ${errCore}function isValid(data) { return _fn(data); }
648
+ ${errCore}${compactCore}function isValid(data) { return _fn(data); }
604
649
  function validate(data) { ${validBody}; }
605
650
  ${parseCore}${positionsCore}${hashDecl}${exports}`;
606
651
  }
607
652
 
653
+ // Why a validator cannot be written as a compact module, or null when it can.
654
+ // The error runtime walks the embedded schema with the interpreted engine and
655
+ // knows nothing the schema does not say, so anything the validator adds from
656
+ // outside the schema keeps the module self-contained.
657
+ // The error runtime's generator reads the library's own files with fs, and
658
+ // runs in Node only (ata build, errorRuntimeSource). It is required through a
659
+ // name rather than a literal so that a bundler following this module, in a
660
+ // build of the package for a runtime without fs, does not try to bring fs
661
+ // along: 1.49.0 bundled for such runtimes, and the generator must not break
662
+ // that.
663
+ const ERROR_RUNTIME_MODULE = './error-runtime';
664
+ function loadErrorRuntime() { return require(ERROR_RUNTIME_MODULE); }
665
+
666
+ // The schema hash a module stamps, once per validator: a plugin writes both
667
+ // modules of a schema (self-contained and compact) from one validator, and
668
+ // hashing a large schema canonically is not free.
669
+ const _hashes = new WeakMap();
670
+ function hashOf(validator) {
671
+ let h = _hashes.get(validator);
672
+ if (h === undefined) {
673
+ h = schemaHash(validator._rawSchema !== undefined ? validator._rawSchema : validator._schemaObj);
674
+ _hashes.set(validator, h);
675
+ }
676
+ return h;
677
+ }
678
+
679
+ // True when every $ref and $dynamicRef in the schema resolves inside it, by
680
+ // the interpreter's own resolver.
681
+ function hasRefKey(n, seen) {
682
+ if (n === null || typeof n !== 'object' || seen.has(n)) return false;
683
+ seen.add(n);
684
+ if (Array.isArray(n)) { for (const x of n) if (hasRefKey(x, seen)) return true; return false; }
685
+ if ('$ref' in n || '$dynamicRef' in n) return true;
686
+ for (const k of Object.keys(n)) if (hasRefKey(n[k], seen)) return true;
687
+ return false;
688
+ }
689
+
690
+ function refsResolveWithin(schema) {
691
+ // No reference anywhere (a key of that name inside a value counts too):
692
+ // nothing to resolve, and no index to build.
693
+ if (!hasRefKey(schema, new Set())) return true;
694
+ const { indexSchemas, resolveRef } = require('./interpreter-core')._refInternals;
695
+ let state;
696
+ try { state = indexSchemas(schema, null); } catch { return false; }
697
+ for (const [node, base] of state.nodeBase) {
698
+ if (node === null || typeof node !== 'object') continue;
699
+ for (const k of ['$ref', '$dynamicRef']) {
700
+ const r = node[k];
701
+ if (r === undefined) continue;
702
+ if (typeof r !== 'string') return false;
703
+ let hit;
704
+ try { hit = resolveRef(r, base, state); } catch { return false; }
705
+ if (hit.node === undefined) return false;
706
+ }
707
+ }
708
+ return true;
709
+ }
710
+
711
+ const COMPACT_OPTIONS = new Set(['engine', 'strictSchema', 'logger', 'source']);
712
+ function compactDecline(validator) {
713
+ // Options are allowed by name, not refused by name: one this list does not
714
+ // know (assertFormat: false, baseURI, a future one) may change what the
715
+ // verdict means, and the runtime would not know to follow it.
716
+ // What the validator registers beside its schema (a meta-schema it
717
+ // resolves, for one) is known only once it has compiled.
718
+ validator._ensureCompiled();
719
+ const o = validator._options || {};
720
+ for (const k of Object.keys(o)) {
721
+ if (o[k] === undefined || COMPACT_OPTIONS.has(k)) continue;
722
+ return 'option ' + k;
723
+ }
724
+ if (validator._usesKeywords || validator._externalChecks) return 'custom keywords';
725
+ if (validator._userFormats && Object.keys(validator._userFormats).length) return 'custom formats';
726
+ if (validator._schemaMap && validator._schemaMap.size > 0) return 'schemas registered beside the root';
727
+ if (validator._schemaObj === null || typeof validator._schemaObj !== 'object') return 'boolean schema';
728
+ // The runtime has the embedded schema and nothing else: a reference that
729
+ // lands outside it (a meta-schema the runtime Validator resolves from its
730
+ // vendored copies, a schema registered later) would come back unresolved,
731
+ // and the errors with it. The check runs on the schema as embedded.
732
+ const { stripAnnotations } = require('./schema-strip');
733
+ if (!refsResolveWithin(stripAnnotations(validator._schemaObj))) return 'a reference outside the schema';
734
+ return null;
735
+ }
736
+
737
+ // A module that carries its verdict and its schema without the descriptive
738
+ // keywords, and imports its errors from the shared runtime at `errorRuntime`
739
+ // (written beside it by the build, see errorRuntimeSource). Null when the
740
+ // validator cannot be written this way; the caller writes the
741
+ // self-contained module instead.
742
+ function toCompactModule(validator, opts) {
743
+ assertEmittable(validator, 'toCompactModule');
744
+ if (!opts || typeof opts.errorRuntime !== 'string') throw new TypeError('toCompactModule: opts.errorRuntime (the import specifier of the error runtime) is required');
745
+ if (compactDecline(validator) !== null) return null;
746
+ return toStandaloneModule(validator, { format: opts.format, formatMode: opts.formatMode, _errorRuntime: opts.errorRuntime });
747
+ }
748
+
749
+ // A schema module: the schema without its descriptive keywords and a few lines
750
+ // that hand it to the runtime at `opts.runtime`, which answers both the
751
+ // verdict and the errors with the interpreted engine. Smaller and quicker to
752
+ // load than generated code, slower per check once warm (about five times on
753
+ // SchemaStore documents). Answers as toCompactModule's module does. Null
754
+ // where toCompactModule would be null.
755
+ function toSchemaModule(validator, opts) {
756
+ assertEmittable(validator, 'toSchemaModule');
757
+ if (!opts || typeof opts.runtime !== 'string') throw new TypeError('toSchemaModule: opts.runtime (the import specifier of the schema runtime) is required');
758
+ if (compactDecline(validator) !== null) return null;
759
+ const format = opts.format || 'esm';
760
+ const { stripAnnotations } = require('./schema-strip');
761
+ const { isV1Dialect } = require('./dialect');
762
+ const sch = validator._schemaObj;
763
+ const stripped = stripAnnotations(sch);
764
+ const text = JSON.stringify(JSON.stringify(stripped)).replace(/</g, '\\u003c');
765
+ const seen = new Set();
766
+ const flatWalk = (n, root) => {
767
+ if (n === null || typeof n !== 'object' || seen.has(n)) return true;
768
+ seen.add(n);
769
+ if (Array.isArray(n)) return n.every((x) => flatWalk(x, false));
770
+ if ('$anchor' in n || '$dynamicAnchor' in n || (!root && '$id' in n)) return false;
771
+ return Object.keys(n).every((k) => flatWalk(n[k], false));
772
+ };
773
+ const rtOpts = [isV1Dialect(sch) ? 'v1: true' : '', flatWalk(stripped, true) ? 'flat: true' : ''].filter(Boolean).join(', ');
774
+ const hashSrc = hashOf(validator);
775
+ const spec = JSON.stringify(opts.runtime);
776
+ const imp = format === 'esm'
777
+ ? `import { createValidator as _ataCreateValidator } from ${spec};\n`
778
+ : `const { createValidator: _ataCreateValidator } = require(${spec});\n`;
779
+ const exp = format === 'esm'
780
+ ? 'export { validate, isValid, schemaHash, ataVersion };\nexport default { validate, isValid, schemaHash, ataVersion };\n'
781
+ : 'module.exports = { validate, isValid, schemaHash, ataVersion };\nmodule.exports.default = module.exports;\n';
782
+ return `// Auto-generated by ata-validator ${ATA_VERSION}, do not edit.
783
+ // Schema module: the schema; the verdict and the errors come from the runtime it imports.
784
+ // Re-run the build after upgrading ata: the version above is what wrote this.
785
+ 'use strict';
786
+ ${imp}const VALID = Object.freeze({ valid: true, errors: Object.freeze([]) });
787
+ const ABORT = Object.freeze({ valid: false, errors: Object.freeze([Object.freeze({ code: 'ATA9000', message: 'validation failed', keyword: '__abort_early__', path: '' })]) });
788
+ let _ataV = null;
789
+ function _ataGet() { return _ataV !== null ? _ataV : (_ataV = _ataCreateValidator(JSON.parse(${text})${rtOpts ? ', { ' + rtOpts + ' }' : ''})); }
790
+ function isValid(data) { return _ataGet().isValid(data); }
791
+ function validate(data) { const v = _ataGet(); if (v.isValid(data)) return VALID; const e = v.errors(data); return e === null ? ABORT : { valid: false, errors: e }; }
792
+ const schemaHash = ${JSON.stringify(hashSrc)};
793
+ const ataVersion = ${JSON.stringify(ATA_VERSION)};
794
+ ${exp}`;
795
+ }
796
+
608
797
  // Bundle multiple validators into a single JS file for fast startup.
609
798
  // Usage:
610
799
  // const bundle = Validator.bundle([schema1, schema2, ...]);
@@ -665,6 +854,7 @@ function bundleStandalone(Validator, schemas, opts) {
665
854
  v._schemaObj,
666
855
  v._schemaMap,
667
856
  v._userFormats,
857
+ { noOrdinal: true },
668
858
  );
669
859
  if (jsFn._usesSafeRe || (jsErrFn && jsErrFn._usesSafeRe)) bundleUsesSafeRe = true;
670
860
  return { v, jsFn, jsErrFn };
@@ -757,6 +947,7 @@ function bundleCompact(Validator, schemas, opts) {
757
947
  v._schemaObj,
758
948
  v._schemaMap,
759
949
  v._userFormats,
950
+ { noOrdinal: true },
760
951
  );
761
952
  if (jsFn._usesSafeRe || (jsErrFn && jsErrFn._usesSafeRe)) bundleUsesSafeRe = true;
762
953
  // Hoisted anyOf/oneOf branch helpers (e.g. `_af1_b0`) must travel with the
@@ -917,6 +1108,23 @@ const htmlSafeResult = (fn) => function () { return htmlSafe(fn.apply(this, argu
917
1108
  module.exports = {
918
1109
  toStandalone: htmlSafeResult(toStandalone),
919
1110
  toStandaloneModule: htmlSafeResult(toStandaloneModule),
1111
+ toCompactModule: htmlSafeResult(toCompactModule),
1112
+ toSchemaModule: htmlSafeResult(toSchemaModule),
1113
+ compactDecline,
1114
+ // `schemas`: the validators (or schemas) whose compact modules will import
1115
+ // this runtime; parts none of them needs are left out. Omitted, the
1116
+ // runtime carries every part.
1117
+ // `schemaMode`: the runtime schema modules import, which also answers the
1118
+ // verdict (createValidator).
1119
+ errorRuntimeSource: htmlSafeResult((format, schemas, schemaMode) => {
1120
+ const er = loadErrorRuntime();
1121
+ if (!Array.isArray(schemas)) return er.errorRuntimeSource(format, ATA_VERSION, undefined, !!schemaMode);
1122
+ const { stripAnnotations } = require('./schema-strip');
1123
+ const embedded = schemas.map((x) => stripAnnotations(x && typeof x === 'object' && x._schemaObj !== undefined ? x._schemaObj : x));
1124
+ const features = er.runtimeFeatures(embedded);
1125
+ for (const x of schemas) if (x && x._jsFn && x._jsFn._usesSafeRe) features['safe-regex'] = true;
1126
+ return er.errorRuntimeSource(format, ATA_VERSION, features, !!schemaMode);
1127
+ }),
920
1128
  bundle: htmlSafeResult(bundle),
921
1129
  bundleStandalone: htmlSafeResult(bundleStandalone),
922
1130
  bundleCompact: htmlSafeResult(bundleCompact),