Repository navigation
lib: add experimental node:yaml module - #67157
marcopiraccini wants to merge 11 commits into
Conversation
|
Review requested:
|
405299b to
0d87e9f
Compare
ad1f666 to
09ed139
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #67157 +/- ##
==========================================
+ Coverage 90.56% 90.58% +0.01%
==========================================
Files 802 804 +2
Lines 286935 287455 +520
Branches 55415 55532 +117
==========================================
+ Hits 259871 260398 +527
+ Misses 17161 17122 -39
- Partials 9903 9935 +32
🚀 New features to boost your workflow:
|
09ed139 to
bbfacd1
Compare
LiviaMedeiros
left a comment
There was a problem hiding this comment.
I'm +0.5 for adding builtin yaml support in general and would be +1 if some concerns were resolved first:
- How do we do versioning once
v1.3or subsequent specs are released? While JSON is both blessed in cursed with lack of versioning, in YAML we need to account this somehow. Hardcodingv1.2.2isn't very future-proof.
1.1. Should we introduce compatibility withv1.1? - What's the plan for this module, aside from
parse()andstringify()? Are we aiming for full-fledged module with all the classes, traversal methods, selectors, transformers, handling multi-document objects, etc.?
Without draft for the desired module API, it's hard to tell if it really should be implemented as separate builtin module.
If we just need this for something similar to #53787, i think an internal/util.parseYAML() (potentially re-exported later for userland as util.parseYAML() or util.YAML.parse()) would be sufficient.
| // parser. test/fixtures/yaml-test-suite.json holds, for every test, the input | ||
| // and either the expected documents as JSON or a flag that the input is an | ||
| // error. |
There was a problem hiding this comment.
Nit: would be more future-proof if either the file structure was fully defined here, or if there was a tool that regenerates it if test suite gets updated.
There was a problem hiding this comment.
Added tools/update-yaml-test-suite.mjs that regenerates test/fixtures/yaml-test-suite.json.
| let TextDecoder; | ||
| function decode(input) { | ||
| TextDecoder ??= require('internal/encoding').TextDecoder; | ||
| return new TextDecoder('utf-8').decode(input); | ||
| } |
There was a problem hiding this comment.
Nit
| let TextDecoder; | |
| function decode(input) { | |
| TextDecoder ??= require('internal/encoding').TextDecoder; | |
| return new TextDecoder('utf-8').decode(input); | |
| } | |
| let textDecoder; | |
| function decode(input) { | |
| textDecoder ??= new (require('internal/encoding').TextDecoder)('utf-8'); | |
| return textDecoder.decode(input); | |
| } |
ShogunPanda
left a comment
There was a problem hiding this comment.
I'm +1 to this. Actually I wanted to implement it but Marco beated me on time.
Only a small nit: make it clear that now it only adds the parser in the commit.
|
Can we verify if a native version would be faster? I'm +1 on adding it to core, but I think we should strive to have near-json performance if possible. |
Why was this path chosen over forking a known tested module and vendoring it? |
|
Should we pick TOML instead? It's much easier to parse (and a simpler parser usually means less maintenance burden), even for humans arguably |
It shouldn't be "instead." There are many reasons to parse yaml, and the standard library is not currently providing a means to do so. |
|
@LiviaMedeiros The parser is YAML 1.2, core schema. A I'd rather not add 1.1 compatibility now. The syntax is almost the same, the difference is in scalar resolution ( |
|
The
notable-change
Please suggest a text for the release notes if you'd like to include a more detailed summary, then proceed to update the PR description with the text or a link to the notable change suggested text comment. Otherwise, the commit will be placed in the Other Notable Changes section. |
There was a problem hiding this comment.
Is it worth the maintenance burden of implementing this ourselves? Is there no trusted library that would be suitable, either native or JS?
There was a problem hiding this comment.
I think using a dependency might be better for our case.
I think near-json performance is not practical, there aren't SIMD yaml parsers yet. Small benchmark I did:
|
@jsumners-nr I did look at vendoring first.
Writing it against the spec gave ~1500 lines of code with 100% coverage and passes the official test suite. YAML 1.2.2 has not changed since 2021, so the maintenance target is a frozen spec with a conformance suite, which I felt manageable. |
@mcollina I tried a rapidyaml C++ addon and yaml-rust2 compiled to Wasm on the same workflow. These are milliseconds per document on Linux x64, including the time to build the JS result and, for Wasm, to encode the input. The sizes are for YAML; I used the equivalent JSON for
On the 332 KiB input, I would keep the first version in JS: on the 17 KiB workflow the addon saved 0.20 ms per parse, which seems small for a new C++ dependency and binding to maintain. |
|
I agree. Leave it in JS. |
|
Calling it
What I meant was "to ship first as an alternative to JSON". Sure parsing YAML would be useful, but if the ecosystem settles on one, TOML is much better choice IMO – for example, SIMD parsers for TOML are available |
|
@marcopiraccini ... in the next hour or so I'm going to have another dependency option for you to try... putting a few finishing touches on it... but to get a sense, these are the current numbers (MB/s) benchmarking the raw parsing (no node.js involvement yet) against libyaml and rapidyaml.
|
|
Ok here, please give this a trial run. https://github.com/jasnell/igname It is still very much a work in progress but has been purpose built with a Node.js binding in mind. Unlike rapidyaml it is event-driven only, avoiding the intermediate tree building with the idea that the events would go straight into JS values. It supports emitting yaml also but I'm running through some ideas for improving the perf there so the emitter APIs may/will change a bit. Btw, If this works out, my plan would be to propose transfering the repo to the node.js org. Update: in testing serialization, the native path via igname beats pure js serialization 1.5x-2x and rapidyaml is slightly slower and uses far more memory. I'm still experimenting tho. |
@jasnell thanks, I gave it a run (parse only). It is the fastest by a clear margin. Time to parse one YAML document into a JS value, in milliseconds per document (on my Linux laptop):
All five return the same value, and runs differ by up to about 10%. igname is about 3.2x faster than this PR and about 1.8x faster than rapidyaml, end to end. Since igname also runs the YAML test suite in its CI, it makes sense to move this PR to it. Should I vendor it from your repo now, or wait until it is transferred to the nodejs org? @mcollina would this address your request for a dependency? |
|
It can be vendored into this PR now, I'd think. Take the latest push and include an update script. If/when it gets transfered that can be updated to point at the org. Request to transfer it in: nodejs/admin#1112 |
igname is a C++ YAML 1.2 parser and emitter, written to be vendored into Node.js. It is vendored at commit ecf1197, with a script to update it to the latest commit of its main branch. Refs: https://github.com/jasnell/igname Refs: nodejs#67157 (comment)
Replace the JavaScript parser of `node:formats/yaml` with a binding to igname. The binding creates the JavaScript values from the events of the parser, without an intermediate tree. The API of `parse()` and its results are unchanged: aliases keep their identity, duplicate keys and mismatched core schema tags throw, and collection keys become their JSON text. The messages of syntax errors now come from igname. igname accepts raw DEL, C1 control characters, U+FFFE and U+FFFF, which are not printable characters in YAML 1.2: the binding rejects them in plain and block scalars, and quoted scalars accept them. The tests cover what the binding adds. The YAML test suite is no longer vendored, since igname runs it. On a 332 KiB document, parsing takes about a third of the time. Refs: nodejs#67157 (comment)
Add a YAML 1.2 parser for the core schema as `node:yaml`, behind `--experimental-yaml`, with `yaml.parse(input)` following the shape of `Bun.YAML.parse()`. The parser is written from scratch, in one pass from text to values, with no new dependency. Anchors and aliases resolve to shared objects, core schema tags are applied, mappings become plain objects and duplicate keys are an error. The official yaml-test-suite is vendored as a JSON fixture and run by test-yaml-test-suite.js: 400 of its 402 cases pass, the two left are documents with duplicate keys. Refs: nodejs#53787 Signed-off-by: marcopiraccini <marco.piraccini@gmail.com>
Add `options.throwIfInvalid` to `yaml.parse()`, following the `fs.statSync()` `throwIfNoEntry` option: with `false` the parser returns `undefined` instead of building an `ERR_INVALID_YAML` error. The parser throws an internal sentinel on the first error, so no error object or message is created in that mode. Add `tools/update-yaml-test-suite.mjs`, which regenerates `test/fixtures/yaml-test-suite.json` from the `data` branch of yaml/yaml-test-suite, and document the fixture layout in the test. The suite runner also checks the non-throwing mode on every case. Reuse a single `TextDecoder` instance when decoding buffer input.
Defining every mapping entry through `ObjectDefineProperty()` was half of the parse time. Build each mapping with a frozen empty prototype instead, assign the entries, and give the mapping `Object.prototype` once it is complete. An assignment can then not reach a setter or a non-writable property inherited from `Object.prototype`, and a `__proto__` key stays an own property. Parsing is about 60% faster on typical documents, and the result objects keep V8 fast properties, which a null-prototype literal would not.
The straw poll in the pull request settled on `node:formats/*` as the home for data format modules, so that future formats such as TOML do not each take a top-level name. Move lib/yaml.js to lib/formats/yaml.js and expose it as `node:formats/yaml`. The API, the `--experimental-yaml` flag and the internal parser location are unchanged. Refs: nodejs#67157 (comment)
Document `node:formats/yaml` in a `formats.md` page that covers the `node:formats/*` modules, with one section per format, so that other formats can be added to it later. Refs: nodejs#67157
"Stream" is the term of the YAML specification for a sequence of documents, but none of the accepted `input` types is a stream. Refer to the input or to its documents instead, in the documentation and in the code.
igname is a C++ YAML 1.2 parser and emitter, written to be vendored into Node.js. It is vendored at commit ecf1197, with a script to update it to the latest commit of its main branch. Refs: https://github.com/jasnell/igname Refs: nodejs#67157 (comment)
Replace the JavaScript parser of `node:formats/yaml` with a binding to igname. The binding creates the JavaScript values from the events of the parser, without an intermediate tree. The API of `parse()` and its results are unchanged: aliases keep their identity, duplicate keys and mismatched core schema tags throw, and collection keys become their JSON text. The messages of syntax errors now come from igname. igname accepts raw DEL, C1 control characters, U+FFFE and U+FFFF, which are not printable characters in YAML 1.2: the binding rejects them in plain and block scalars, and quoted scalars accept them. The tests cover what the binding adds. The YAML test suite is no longer vendored, since igname runs it. On a 332 KiB document, parsing takes about a third of the time. Refs: nodejs#67157 (comment)
160cf03 to
3fa11a8
Compare
|
@jasnell @mcollina the PR now parses with igname, as suggested in #67157 (comment).
|
aduh95
left a comment
There was a problem hiding this comment.
Let's make igname opt-in via a configure flag (e.g. --with-yaml) so we can backport this, and remove the runtime experimental flag. We can make the configure flag opt-out in a semver-major
| // Without throwIfInvalid the result is undefined. | ||
| if (!throw_if_invalid) return; | ||
| std::string message; | ||
| if (result.error == igname::Error::kAborted) { |
There was a problem hiding this comment.
Some error messages point to the wrong column when the line has non-ASCII characters before the error.
There are two kinds of error here:
- Syntax errors. igname finds these, and it counts the column in characters. These are correct.
- Errors this file finds, such as duplicate keys, tags that don't match the value, unknown anchors, and characters that aren't allowed. These get their column from igname::Mark, which counts bytes, not characters (igname.hpp:86).
In UTF-8, é is 2 bytes, so each é before the error pushes the column one place too far right:
parse('{a: 1, a: 2}'); // column 8 (correct)
parse('{é: 1, é: 2}'); // column 9 (should be 8)
parse('{ééé: 1, ééé: 2}'); // column 13 (should be 10)
parse('[ééé, !!int a]'); // column 10 (should be 7)A fix: before building the message, find where the error's line starts and count characters instead of bytes up to the error. The NUL check below already counts this way. It only runs when there's an error, so it costs nothing in the normal case.
Could you also add a test with a non-ASCII character before the error? All the current position tests use ASCII only, which is why this wasn't caught.
Alternatively, we can modify igname's column reporting here.
|
|
||
| // Returns false with a negative budget when the text is too long, and with | ||
| // a pending exception otherwise. | ||
| bool AppendKeyJSON(Local<Value> value, std::string* out, int* budget) { |
There was a problem hiding this comment.
Worth a check here that something like yaml.parse('? [.nan]\n: first\n? [~]\n: second\n'); works correctly.
> yaml.parse('? [.nan]\n: first\n? [~]\n: second\n');
Uncaught [SyntaxError: Duplicate mapping key "[null]" (line 3, column 3)
] {
code: 'ERR_INVALID_YAML'
}
|
Handful of additional review points, but I'd consider them optional for the initial version so long as there is follow-up |
Build mappings with fast properties, count error columns in characters, keep NaN and the infinities distinct in collection keys, pass binary input to the parser without decoding it, reject keys longer than a string can be, and accept at most one document.
@aduh95 I'm fine with gating this at build time and dropping |

This is a proposal for a built-in YAML parser, with a basic implementation to discuss on: an experimental, parse-only
node:yamlmodule behind--experimental-yaml.The parser supports the YAML 1.2 core schema, anchors, aliases, tags, and multi-document streams. It is written from scratch and has no external dependencies.
This gives Node.js a built-in YAML parser for future configuration support, following the discussion about
.nodercin #53787, where the config file ended up JSON-only because core had no parser.Bun parity
Bun ships
Bun.YAMLsince v1.2.21.yaml.parse()followsBun.YAML.parse()so that code written for it runs unchanged:parse(input)takes a string or binary input (ArrayBuffer,TypedArray,DataView) decoded as UTF-8.null.SyntaxError(here with theERR_INVALID_YAMLcode and the line and column).!!strand!!intare applied.Not covered yet:
Bun.YAML.stringify(value, replacer, space),Blobinput, and importing.yamlfiles as modules. See the next steps.Tests
Tests include the official YAML Test Suite, vendored at a fixed revision. Of 402 cases, 400 pass.
The two that fail, 2JQS and X38W, are documents with duplicate keys: two empty keys, and a key that is an alias of the previous key. The suite only checks that they parse, since duplicate keys are not a syntax error, and provides no expected output for them. The YAML 1.2 specification requires mapping keys to be unique, and this parser enforces it and throws
Duplicate mapping key, as theyamlandjs-yamlpackages do by default. They are listed as known failures with that reason. If the reviewers prefer theJSON.parse()behavior, where the last value wins, the check can be removed and both pass.Review guide
doc/api/yaml.md: API behavior.lib/yaml.js: input validation and document return values.lib/internal/yaml/parser.js: parser implementation.test/parallel/test-yaml.js: API tests.test/parallel/test-yaml-test-suite.js: official suite runner.node:vfssetup in vfs: add minimal node:vfs subsystem #63115.Next steps, if accepted
yaml.stringify(value, replacer, space)with Bun's semantics.import data from './config.yaml' with { type: 'yaml' }.--experimental-config-file.yamlsubsystem label and commit subsystem, as was done forvfs.Refs: