schema.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. var Scalar = require('../../nodes/Scalar.js');
  3. var map = require('../common/map.js');
  4. var seq = require('../common/seq.js');
  5. function intIdentify(value) {
  6. return typeof value === 'bigint' || Number.isInteger(value);
  7. }
  8. const stringifyJSON = ({ value }) => JSON.stringify(value);
  9. const jsonScalars = [
  10. {
  11. identify: value => typeof value === 'string',
  12. default: true,
  13. tag: 'tag:yaml.org,2002:str',
  14. resolve: str => str,
  15. stringify: stringifyJSON
  16. },
  17. {
  18. identify: value => value == null,
  19. createNode: () => new Scalar.Scalar(null),
  20. default: true,
  21. tag: 'tag:yaml.org,2002:null',
  22. test: /^null$/,
  23. resolve: () => null,
  24. stringify: stringifyJSON
  25. },
  26. {
  27. identify: value => typeof value === 'boolean',
  28. default: true,
  29. tag: 'tag:yaml.org,2002:bool',
  30. test: /^true|false$/,
  31. resolve: str => str === 'true',
  32. stringify: stringifyJSON
  33. },
  34. {
  35. identify: intIdentify,
  36. default: true,
  37. tag: 'tag:yaml.org,2002:int',
  38. test: /^-?(?:0|[1-9][0-9]*)$/,
  39. resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
  40. stringify: ({ value }) => intIdentify(value) ? value.toString() : JSON.stringify(value)
  41. },
  42. {
  43. identify: value => typeof value === 'number',
  44. default: true,
  45. tag: 'tag:yaml.org,2002:float',
  46. test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
  47. resolve: str => parseFloat(str),
  48. stringify: stringifyJSON
  49. }
  50. ];
  51. const jsonError = {
  52. default: true,
  53. tag: '',
  54. test: /^/,
  55. resolve(str, onError) {
  56. onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
  57. return str;
  58. }
  59. };
  60. const schema = [map.map, seq.seq].concat(jsonScalars, jsonError);
  61. exports.schema = schema;