fx 39.1.0 → 40.0.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/README.md +4 -4
- package/index.js +90 -25
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -97,15 +97,15 @@ The edited data will be saved to the same `file.json` file.
|
|
|
97
97
|
|
|
98
98
|
### Syntactic Sugar
|
|
99
99
|
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
Prefix an expression with `@` to apply it to each item of an array. For example,
|
|
101
|
+
`.map(x => x.commit.message)` can be written as `@.commit.message`.
|
|
102
102
|
|
|
103
103
|
```sh
|
|
104
|
-
curl https://api.github.com/repos/antonmedv/fx/commits | fx '
|
|
104
|
+
curl https://api.github.com/repos/antonmedv/fx/commits | fx '@.commit.message'
|
|
105
105
|
```
|
|
106
106
|
|
|
107
107
|
```sh
|
|
108
|
-
echo '[{"name": "world"}]' | fx '
|
|
108
|
+
echo '[{"name": "world"}]' | fx '@`Hello, ${x.name}!`'
|
|
109
109
|
```
|
|
110
110
|
|
|
111
111
|
Fx has a special syntax for the flatMap function. Fox example,
|
package/index.js
CHANGED
|
@@ -11,6 +11,7 @@ void async function main() {
|
|
|
11
11
|
let flagRaw = false
|
|
12
12
|
let flagSlurp = false
|
|
13
13
|
let flagYaml = false
|
|
14
|
+
let flagMaml = false
|
|
14
15
|
const args = []
|
|
15
16
|
for (const arg of process.argv.slice(2)) {
|
|
16
17
|
if (arg === '--help' || arg === '-h') flagHelp = true
|
|
@@ -18,6 +19,7 @@ void async function main() {
|
|
|
18
19
|
else if (arg === '--slurp' || arg === '-s') flagSlurp = true
|
|
19
20
|
else if (arg === '-rs' || arg === '-sr') flagRaw = flagSlurp = true
|
|
20
21
|
else if (arg === '--yaml') flagYaml = true
|
|
22
|
+
else if (arg === '--maml') flagMaml = true
|
|
21
23
|
else args.push(arg)
|
|
22
24
|
}
|
|
23
25
|
|
|
@@ -37,7 +39,10 @@ void async function main() {
|
|
|
37
39
|
if (filename) {
|
|
38
40
|
globalThis.__file__ = filename
|
|
39
41
|
fd = fs.openSync(filename, 'r')
|
|
40
|
-
if (!flagYaml
|
|
42
|
+
if (!flagYaml && !flagMaml) {
|
|
43
|
+
flagYaml = /\.ya?ml$/i.test(filename)
|
|
44
|
+
flagMaml = /\.maml$/i.test(filename)
|
|
45
|
+
}
|
|
41
46
|
}
|
|
42
47
|
}
|
|
43
48
|
|
|
@@ -47,7 +52,9 @@ void async function main() {
|
|
|
47
52
|
? readLine(gen)
|
|
48
53
|
: flagYaml
|
|
49
54
|
? parseYaml(gen)
|
|
50
|
-
:
|
|
55
|
+
: flagMaml
|
|
56
|
+
? parseMaml(gen)
|
|
57
|
+
: parseJson(gen)
|
|
51
58
|
|
|
52
59
|
if (flagSlurp) {
|
|
53
60
|
const array = []
|
|
@@ -73,6 +80,7 @@ async function transform(json, args, theme) {
|
|
|
73
80
|
return ${jsCode}
|
|
74
81
|
})`
|
|
75
82
|
output = await run(output, fn)
|
|
83
|
+
if (output === skip) break
|
|
76
84
|
} catch (err) {
|
|
77
85
|
await printErr(err)
|
|
78
86
|
}
|
|
@@ -125,12 +133,12 @@ function transpile(code) {
|
|
|
125
133
|
|
|
126
134
|
if (/^@/.test(code)) {
|
|
127
135
|
const jsCode = transpile(code.substring(1))
|
|
128
|
-
return `
|
|
136
|
+
return `map((x, i) => apply(${jsCode}, x, i))`
|
|
129
137
|
}
|
|
130
138
|
|
|
131
139
|
if (/^\?/.test(code)) {
|
|
132
140
|
const jsCode = transpile(code.substring(1))
|
|
133
|
-
return `
|
|
141
|
+
return `filter((x, i) => apply(${jsCode}, x, i))`
|
|
134
142
|
}
|
|
135
143
|
|
|
136
144
|
return code
|
|
@@ -164,21 +172,16 @@ async function run(json, code) {
|
|
|
164
172
|
throw new Error(`Cannot sort ${typeof x}`)
|
|
165
173
|
}
|
|
166
174
|
|
|
175
|
+
function isFalsely(x) {
|
|
176
|
+
return x === false || x === null || x === undefined
|
|
177
|
+
}
|
|
178
|
+
|
|
167
179
|
function filter(fn) {
|
|
168
180
|
return function (x) {
|
|
169
181
|
if (Array.isArray(x)) {
|
|
170
|
-
return x.filter((v, i) => fn(v, i))
|
|
171
|
-
} else if (x !== null && typeof x === 'object') {
|
|
172
|
-
const result = {}
|
|
173
|
-
for (const [k, v] of Object.entries(x)) {
|
|
174
|
-
if (fn(v, k)) {
|
|
175
|
-
result[k] = v
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
return result
|
|
179
|
-
} else {
|
|
180
|
-
throw new Error(`Cannot filter ${typeof x}`)
|
|
182
|
+
return x.filter((v, i) => !isFalsely(fn(v, i)))
|
|
181
183
|
}
|
|
184
|
+
return isFalsely(fn(x))? skip : x
|
|
182
185
|
}
|
|
183
186
|
}
|
|
184
187
|
|
|
@@ -186,15 +189,8 @@ async function run(json, code) {
|
|
|
186
189
|
return function (x) {
|
|
187
190
|
if (Array.isArray(x)) {
|
|
188
191
|
return x.map((v, i) => fn(v, i))
|
|
189
|
-
} else if (x !== null && typeof x === 'object') {
|
|
190
|
-
const result = {}
|
|
191
|
-
for (const [k, v] of Object.entries(x)) {
|
|
192
|
-
result[k] = fn(v, k)
|
|
193
|
-
}
|
|
194
|
-
return result
|
|
195
|
-
} else {
|
|
196
|
-
throw new Error(`Cannot map over ${typeof x}`)
|
|
197
192
|
}
|
|
193
|
+
return fn(x)
|
|
198
194
|
}
|
|
199
195
|
}
|
|
200
196
|
|
|
@@ -226,12 +222,26 @@ async function run(json, code) {
|
|
|
226
222
|
}
|
|
227
223
|
}
|
|
228
224
|
|
|
225
|
+
function sortKeys(x) {
|
|
226
|
+
if (Array.isArray(x)) {
|
|
227
|
+
return x.map(sortKeys)
|
|
228
|
+
}
|
|
229
|
+
if (typeof x === 'object' && x !== null) {
|
|
230
|
+
const sorted = {}
|
|
231
|
+
for (const key of Object.keys(x).sort()) {
|
|
232
|
+
sorted[key] = sortKeys(x[key])
|
|
233
|
+
}
|
|
234
|
+
return sorted
|
|
235
|
+
}
|
|
236
|
+
return x
|
|
237
|
+
}
|
|
238
|
+
|
|
229
239
|
function groupBy(keyFn) {
|
|
230
240
|
return function (x) {
|
|
231
241
|
const grouped = {}
|
|
232
242
|
for (const item of x) {
|
|
233
243
|
const key = typeof keyFn === 'function' ? keyFn(item) : item[keyFn]
|
|
234
|
-
if (!
|
|
244
|
+
if (!Object.prototype.hasOwnProperty.call(grouped, key)) grouped[key] = []
|
|
235
245
|
grouped[key].push(item)
|
|
236
246
|
}
|
|
237
247
|
return grouped
|
|
@@ -286,6 +296,26 @@ async function run(json, code) {
|
|
|
286
296
|
throw new Error(`Cannot list ${typeof x}`)
|
|
287
297
|
}
|
|
288
298
|
|
|
299
|
+
function del(key) {
|
|
300
|
+
return function (x) {
|
|
301
|
+
if (Array.isArray(x)) {
|
|
302
|
+
const copy = [...x]
|
|
303
|
+
copy.splice(key, 1)
|
|
304
|
+
return copy
|
|
305
|
+
}
|
|
306
|
+
if (typeof x === 'object' && x !== null) {
|
|
307
|
+
const copy = {...x}
|
|
308
|
+
delete copy[key]
|
|
309
|
+
return copy
|
|
310
|
+
}
|
|
311
|
+
throw new Error(`Cannot delete key from ${typeof x}`)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function exit(code) {
|
|
316
|
+
process.exit(code)
|
|
317
|
+
}
|
|
318
|
+
|
|
289
319
|
function save(x) {
|
|
290
320
|
if (!globalThis.__file__) throw new Error('Specify a file as the first argument to be able to save: fx file.json ...')
|
|
291
321
|
fs.writeFileSync(globalThis.__file__, JSON.stringify(x, null, 2))
|
|
@@ -368,6 +398,14 @@ function* parseYaml(gen) {
|
|
|
368
398
|
}
|
|
369
399
|
}
|
|
370
400
|
|
|
401
|
+
function* parseMaml(gen) {
|
|
402
|
+
let buffer = ''
|
|
403
|
+
for (const ch of gen) {
|
|
404
|
+
buffer += ch
|
|
405
|
+
}
|
|
406
|
+
yield MAML.parse(buffer)
|
|
407
|
+
}
|
|
408
|
+
|
|
371
409
|
function* parseJson(gen) {
|
|
372
410
|
let lineNumber = 1, buffer = '', lastChar, done = false
|
|
373
411
|
|
|
@@ -783,10 +821,37 @@ Flags
|
|
|
783
821
|
-h, --help print help
|
|
784
822
|
-r, --raw treat input as a raw string
|
|
785
823
|
-s, --slurp read all inputs into an array
|
|
786
|
-
--yaml parse input as YAML
|
|
824
|
+
--yaml parse input as YAML
|
|
825
|
+
--maml parse input as MAML`
|
|
787
826
|
console.log(usage)
|
|
788
827
|
}
|
|
789
828
|
|
|
829
|
+
// maml v1.0.1
|
|
830
|
+
// @formatter:off
|
|
831
|
+
void function () {function I(e){if(typeof e!="string")throw TypeError("Source must be a string");let o=0,a=1,n,l=!1;t();let d=w();if(g(),!l)throw new SyntaxError(f());return m(d),d;function t(){o<e.length?(n=e[o],o++):(n="",l=!0),n===`
|
|
832
|
+
`&&a++}function c(r){return e.substring(o,o+r)}function w(){var r,s,i,u,p,S,M;return g(),(M=(S=(p=(u=(i=(s=(r=_())!=null?r:x())!=null?s:O())!=null?i:C())!=null?u:R())!=null?p:E("true",!0))!=null?S:E("false",!1))!=null?M:E("null",null)}function x(){if(n!=='"')return;let r="",s=!1;for(;;)if(t(),s){if(n==="u"){if(t(),n!=="{")throw new SyntaxError(f(h.u+" "+JSON.stringify(n)+' (expected "{")'));let i="";for(;t(),n!=="}";){if(!j(n))throw new SyntaxError(f(h.u+" "+JSON.stringify(n)));if(i+=n,i.length>6)throw new SyntaxError(f(h.u+" (too many hex digits)"))}if(i.length===0)throw new SyntaxError(f(h.u));let u=parseInt(i,16);if(u>1114111||u>=55296&&u<=57343)throw new SyntaxError(f(h.u+" (out of range)"));r+=String.fromCodePoint(u)}else{let i=L[n];if(!i)throw new SyntaxError(f(h.u+" "+JSON.stringify(n)));r+=i}s=!1}else if(n==="\\")s=!0;else{if(n==='"')break;if(n===`
|
|
833
|
+
`)throw new SyntaxError(f());if(n<" "&&n!==" "||n==="\x7F")throw new SyntaxError(f());r+=n}return t(),r}function _(){if(n!=='"'||c(2)!=='""')return;t(),t(),t();let r=!1;n==="\r"&&c(1)===`
|
|
834
|
+
`&&t(),n===`
|
|
835
|
+
`&&(r=!0,t());let s="";for(;!l;){if(n==='"'&&c(2)==='""'){if(t(),t(),t(),s===""&&!r)throw new SyntaxError(f("Raw strings cannot be empty"));return s}s+=n,t()}throw new SyntaxError(f())}function O(){if(!y(n)&&n!=="-")return;let r="",s=!1;if(n==="-"&&(r+=n,t(),!y(n)))throw new SyntaxError(f());if(n==="0")r+=n,t();else for(;y(n);)r+=n,t();if(n==="."){if(s=!0,r+=n,t(),!y(n))throw new SyntaxError(f());for(;y(n);)r+=n,t()}if(n==="e"||n==="E"){if(s=!0,r+=n,t(),(n==="+"||n==="-")&&(r+=n,t()),!y(n))throw new SyntaxError(f());for(;y(n);)r+=n,t()}return s?parseFloat(r):K(r)}function C(){if(n!=="{")return;t(),g();let r={};if(n==="}")return t(),r;for(;;){let s=o,i;if(n==='"'?i=x():i=F(),Object.prototype.hasOwnProperty.call(r,i))throw o=s,new SyntaxError(f(`Duplicate key ${JSON.stringify(i)}`));if(g(),n!==":")throw new SyntaxError(f());t();let u=w();m(u),r[i]=u;let p=g();if(n==="}")return t(),r;if(n===","){if(t(),g(),n==="}")return t(),r}else{if(p)continue;throw new SyntaxError(f("Expected comma or newline between key-value pairs"))}}}function F(){let r="";for(;J(n);)r+=n,t();if(r==="")throw new SyntaxError(f());return r}function R(){if(n!=="[")return;t(),g();let r=[];if(n==="]")return t(),r;for(;;){let s=w();m(s),r.push(s);let i=g();if(n==="]")return t(),r;if(n===","){if(t(),g(),n==="]")return t(),r}else{if(i)continue;throw new SyntaxError(f("Expected comma or newline between values"))}}}function E(r,s){if(n===r[0]){for(let i=1;i<r.length;i++)if(t(),n!==r[i])throw new SyntaxError(f());if(t(),A(n)||n===","||n==="}"||n==="]"||l)return s;throw new SyntaxError(f())}}function g(){let r=!1;for(;A(n);)r||(r=n===`
|
|
836
|
+
`),t();let s=T();return r||s}function T(){if(n==="#"){for(;!l&&n!==`
|
|
837
|
+
`;)t();return g()}return!1}function A(r){return r===" "||r===`
|
|
838
|
+
`||r===" "||r==="\r"}function j(r){return r>="0"&&r<="9"||r>="A"&&r<="F"}function y(r){return r>="0"&&r<="9"}function J(r){return r>="A"&&r<="Z"||r>="a"&&r<="z"||r>="0"&&r<="9"||r==="_"||r==="-"}function K(r){if(r=="-0")return-0;let s=Number(r);if(s>=Number.MIN_SAFE_INTEGER&&s<=Number.MAX_SAFE_INTEGER)return s;let i=BigInt(r),u=-(2n**63n),p=2n**63n-1n;if(i<u||i>p)throw new SyntaxError(`Integer ${r} is outside the 64-bit signed integer range on line ${a}.`);return i}function m(r){if(r===void 0)throw new SyntaxError(f())}function f(r=`Unexpected character ${JSON.stringify(n)}`){n||(r="Unexpected end of input");let s=e.substring(o-40,o).split(`
|
|
839
|
+
`),i=s.at(-1)||"",u=e.substring(o,o+40).split(`
|
|
840
|
+
`,1).at(0)||"";i===""&&(i=s.at(-2)||"",i+=" ",a--,u="");let p=` ${i}${u}
|
|
841
|
+
`,S=` ${".".repeat(Math.max(0,i.length-1))}^
|
|
842
|
+
`;return`${r} on line ${a}.
|
|
843
|
+
|
|
844
|
+
${p}${S}`}}var L={'"':'"',"\\":"\\",n:`
|
|
845
|
+
`,r:"\r",t:" "},h={u:"Invalid escape sequence"};function $(e){return N(e,0)}function N(e,o){let a=e===null?"null":Array.isArray(e)?"array":typeof e;switch(a){case"string":return k(e);case"boolean":return`${e}`;case"bigint":{let n=-(2n**63n),l=2n**63n-1n;if(e<n||e>l)throw new Error(`Integer ${e} is outside the 64-bit signed integer range`);return`${e}`}case"number":{if(!Number.isFinite(e))throw new Error(`Cannot encode ${e} as a MAML value`);let n=`${e}`;if(!n.includes(".")&&!n.includes("e")&&!Number.isSafeInteger(e))throw new Error(`Integer ${e} cannot be represented losslessly as a number, use BigInt instead`);return n}case"null":case"undefined":return"null";case"array":{let n=e.length;if(n===0)return"[]";let l=b(o+1),d=b(o),t=`[
|
|
846
|
+
`;for(let c=0;c<n;c++)c>0&&(t+=`
|
|
847
|
+
`),t+=l+N(e[c],o+1);return t+`
|
|
848
|
+
`+d+"]"}case"object":{let n=Object.keys(e),l=n.length;if(l===0)return"{}";let d=b(o+1),t=b(o),c=`{
|
|
849
|
+
`;for(let w=0;w<l;w++){w>0&&(c+=`
|
|
850
|
+
`);let x=n[w];c+=d+U(x)+": "+N(e[x],o+1)}return c+`
|
|
851
|
+
`+t+"}"}default:throw new Error(`Unsupported value type: ${a}`)}}function k(e){let o='"';for(let a of e){let n=a.codePointAt(0);a==='"'?o+='\\"':a==="\\"?o+="\\\\":a===`
|
|
852
|
+
`?o+="\\n":a==="\r"?o+="\\r":a===" "?o+="\\t":n<32||n===127?o+=`\\u{${n.toString(16).toUpperCase()}}`:o+=a}return o+'"'}var P=/^[A-Za-z0-9_-]+$/;function U(e){return P.test(e)?e:k(e)}function b(e){return" ".repeat(2*e)}(function(){return typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:Function("return this")()})().MAML={parse:I,stringify:$};
|
|
853
|
+
}()
|
|
854
|
+
|
|
790
855
|
// yaml v2.4.0
|
|
791
856
|
// @formatter:off
|
|
792
857
|
void function () {var ALIAS=Symbol.for("yaml.alias");var DOC=Symbol.for("yaml.document");var MAP=Symbol.for("yaml.map");var PAIR=Symbol.for("yaml.pair");var SCALAR=Symbol.for("yaml.scalar");var SEQ=Symbol.for("yaml.seq");var NODE_TYPE=Symbol.for("yaml.node.type");var isAlias=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===ALIAS;var isDocument=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===DOC;var isMap=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===MAP;var isPair=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===PAIR;var isScalar=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SCALAR;var isSeq=node=>!!node&&typeof node==="object"&&node[NODE_TYPE]===SEQ;function isCollection(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case MAP:case SEQ:return true}return false}function isNode(node){if(node&&typeof node==="object")switch(node[NODE_TYPE]){case ALIAS:case MAP:case SCALAR:case SEQ:return true}return false}var hasAnchor=node=>(isScalar(node)||isCollection(node))&&!!node.anchor;var BREAK=Symbol("break visit");var SKIP=Symbol("skip children");var REMOVE=Symbol("remove node");function visit(node,visitor){const visitor_=initVisitor(visitor);if(isDocument(node)){const cd=visit_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else visit_(null,node,visitor_,Object.freeze([]))}visit.BREAK=BREAK;visit.SKIP=SKIP;visit.REMOVE=REMOVE;function visit_(key,node,visitor,path){const ctrl=callVisitor(key,node,visitor,path);if(isNode(ctrl)||isPair(ctrl)){replaceNode(key,path,ctrl);return visit_(key,ctrl,visitor,path)}if(typeof ctrl!=="symbol"){if(isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){const ci=visit_(i,node.items[i],visitor,path);if(typeof ci==="number")i=ci-1;else if(ci===BREAK)return BREAK;else if(ci===REMOVE){node.items.splice(i,1);i-=1}}}else if(isPair(node)){path=Object.freeze(path.concat(node));const ck=visit_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=visit_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}async function visitAsync(node,visitor){const visitor_=initVisitor(visitor);if(isDocument(node)){const cd=await visitAsync_(null,node.contents,visitor_,Object.freeze([node]));if(cd===REMOVE)node.contents=null}else await visitAsync_(null,node,visitor_,Object.freeze([]))}visitAsync.BREAK=BREAK;visitAsync.SKIP=SKIP;visitAsync.REMOVE=REMOVE;async function visitAsync_(key,node,visitor,path){const ctrl=await callVisitor(key,node,visitor,path);if(isNode(ctrl)||isPair(ctrl)){replaceNode(key,path,ctrl);return visitAsync_(key,ctrl,visitor,path)}if(typeof ctrl!=="symbol"){if(isCollection(node)){path=Object.freeze(path.concat(node));for(let i=0;i<node.items.length;++i){const ci=await visitAsync_(i,node.items[i],visitor,path);if(typeof ci==="number")i=ci-1;else if(ci===BREAK)return BREAK;else if(ci===REMOVE){node.items.splice(i,1);i-=1}}}else if(isPair(node)){path=Object.freeze(path.concat(node));const ck=await visitAsync_("key",node.key,visitor,path);if(ck===BREAK)return BREAK;else if(ck===REMOVE)node.key=null;const cv=await visitAsync_("value",node.value,visitor,path);if(cv===BREAK)return BREAK;else if(cv===REMOVE)node.value=null}}return ctrl}function initVisitor(visitor){if(typeof visitor==="object"&&(visitor.Collection||visitor.Node||visitor.Value)){return Object.assign({Alias:visitor.Node,Map:visitor.Node,Scalar:visitor.Node,Seq:visitor.Node},visitor.Value&&{Map:visitor.Value,Scalar:visitor.Value,Seq:visitor.Value},visitor.Collection&&{Map:visitor.Collection,Seq:visitor.Collection},visitor)}return visitor}function callVisitor(key,node,visitor,path){if(typeof visitor==="function")return visitor(key,node,path);if(isMap(node))return visitor.Map?.(key,node,path);if(isSeq(node))return visitor.Seq?.(key,node,path);if(isPair(node))return visitor.Pair?.(key,node,path);if(isScalar(node))return visitor.Scalar?.(key,node,path);if(isAlias(node))return visitor.Alias?.(key,node,path);return void 0}function replaceNode(key,path,node){const parent=path[path.length-1];if(isCollection(parent)){parent.items[key]=node}else if(isPair(parent)){if(key==="key")parent.key=node;else parent.value=node}else if(isDocument(parent)){parent.contents=node}else{const pt=isAlias(parent)?"alias":"scalar";throw new Error(`Cannot replace node with ${pt} parent`)}}var escapeChars={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"};var escapeTagName=tn=>tn.replace(/[!,[\]{}]/g,ch=>escapeChars[ch]);var Directives=class _Directives{constructor(yaml,tags){this.docStart=null;this.docEnd=false;this.yaml=Object.assign({},_Directives.defaultYaml,yaml);this.tags=Object.assign({},_Directives.defaultTags,tags)}clone(){const copy=new _Directives(this.yaml,this.tags);copy.docStart=this.docStart;return copy}atDocument(){const res=new _Directives(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=true;break;case"1.2":this.atNextDocument=false;this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.2"};this.tags=Object.assign({},_Directives.defaultTags);break}return res}add(line,onError){if(this.atNextDocument){this.yaml={explicit:_Directives.defaultYaml.explicit,version:"1.1"};this.tags=Object.assign({},_Directives.defaultTags);this.atNextDocument=false}const parts=line.trim().split(/[ \t]+/);const name=parts.shift();switch(name){case"%TAG":{if(parts.length!==2){onError(0,"%TAG directive should contain exactly two parts");if(parts.length<2)return false}const[handle,prefix]=parts;this.tags[handle]=prefix;return true}case"%YAML":{this.yaml.explicit=true;if(parts.length!==1){onError(0,"%YAML directive should contain exactly one part");return false}const[version]=parts;if(version==="1.1"||version==="1.2"){this.yaml.version=version;return true}else{const isValid=/^\d+\.\d+$/.test(version);onError(6,`Unsupported YAML version ${version}`,isValid);return false}}default:onError(0,`Unknown directive ${name}`,true);return false}}tagName(source,onError){if(source==="!")return"!";if(source[0]!=="!"){onError(`Not a valid tag: ${source}`);return null}if(source[1]==="<"){const verbatim=source.slice(2,-1);if(verbatim==="!"||verbatim==="!!"){onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);return null}if(source[source.length-1]!==">")onError("Verbatim tags must end with a >");return verbatim}const[,handle,suffix]=source.match(/^(.*!)([^!]*)$/s);if(!suffix)onError(`The ${source} tag has no suffix`);const prefix=this.tags[handle];if(prefix){try{return prefix+decodeURIComponent(suffix)}catch(error){onError(String(error));return null}}if(handle==="!")return source;onError(`Could not resolve tag: ${source}`);return null}tagString(tag){for(const[handle,prefix]of Object.entries(this.tags)){if(tag.startsWith(prefix))return handle+escapeTagName(tag.substring(prefix.length))}return tag[0]==="!"?tag:`!<${tag}>`}toString(doc){const lines=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[];const tagEntries=Object.entries(this.tags);let tagNames;if(doc&&tagEntries.length>0&&isNode(doc.contents)){const tags={};visit(doc.contents,(_key,node)=>{if(isNode(node)&&node.tag)tags[node.tag]=true});tagNames=Object.keys(tags)}else tagNames=[];for(const[handle,prefix]of tagEntries){if(handle==="!!"&&prefix==="tag:yaml.org,2002:")continue;if(!doc||tagNames.some(tn=>tn.startsWith(prefix)))lines.push(`%TAG ${handle} ${prefix}`)}return lines.join("\n")}};Directives.defaultYaml={explicit:false,version:"1.2"};Directives.defaultTags={"!!":"tag:yaml.org,2002:"};function anchorIsValid(anchor){if(/[\x00-\x19\s,[\]{}]/.test(anchor)){const sa=JSON.stringify(anchor);const msg=`Anchor must not contain whitespace or control characters: ${sa}`;throw new Error(msg)}return true}function anchorNames(root){const anchors=new Set;visit(root,{Value(_key,node){if(node.anchor)anchors.add(node.anchor)}});return anchors}function findNewAnchor(prefix,exclude){for(let i=1;true;++i){const name=`${prefix}${i}`;if(!exclude.has(name))return name}}function createNodeAnchors(doc,prefix){const aliasObjects=[];const sourceObjects=new Map;let prevAnchors=null;return{onAnchor:source=>{aliasObjects.push(source);if(!prevAnchors)prevAnchors=anchorNames(doc);const anchor=findNewAnchor(prefix,prevAnchors);prevAnchors.add(anchor);return anchor},setAnchors:()=>{for(const source of aliasObjects){const ref=sourceObjects.get(source);if(typeof ref==="object"&&ref.anchor&&(isScalar(ref.node)||isCollection(ref.node))){ref.node.anchor=ref.anchor}else{const error=new Error("Failed to resolve repeated object (this should not happen)");error.source=source;throw error}}},sourceObjects}}function applyReviver(reviver,obj,key,val){if(val&&typeof val==="object"){if(Array.isArray(val)){for(let i=0,len=val.length;i<len;++i){const v0=val[i];const v1=applyReviver(reviver,val,String(i),v0);if(v1===void 0)delete val[i];else if(v1!==v0)val[i]=v1}}else if(val instanceof Map){for(const k of Array.from(val.keys())){const v0=val.get(k);const v1=applyReviver(reviver,val,k,v0);if(v1===void 0)val.delete(k);else if(v1!==v0)val.set(k,v1)}}else if(val instanceof Set){for(const v0 of Array.from(val)){const v1=applyReviver(reviver,val,v0,v0);if(v1===void 0)val.delete(v0);else if(v1!==v0){val.delete(v0);val.add(v1)}}}else{for(const[k,v0]of Object.entries(val)){const v1=applyReviver(reviver,val,k,v0);if(v1===void 0)delete val[k];else if(v1!==v0)val[k]=v1}}}return reviver.call(obj,key,val)}function toJS(value,arg,ctx){if(Array.isArray(value))return value.map((v,i)=>toJS(v,String(i),ctx));if(value&&typeof value.toJSON==="function"){if(!ctx||!hasAnchor(value))return value.toJSON(arg,ctx);const data={aliasCount:0,count:1,res:void 0};ctx.anchors.set(value,data);ctx.onCreate=res2=>{data.res=res2;delete ctx.onCreate};const res=value.toJSON(arg,ctx);if(ctx.onCreate)ctx.onCreate(res);return res}if(typeof value==="bigint"&&!ctx?.keep)return Number(value);return value}var NodeBase=class{constructor(type){Object.defineProperty(this,NODE_TYPE,{value:type})}clone(){const copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)copy.range=this.range.slice();return copy}toJS(doc,{mapAsMap,maxAliasCount,onAnchor,reviver}={}){if(!isDocument(doc))throw new TypeError("A document argument is required");const ctx={anchors:new Map,doc,keep:true,mapAsMap:mapAsMap===true,mapKeyWarned:false,maxAliasCount:typeof maxAliasCount==="number"?maxAliasCount:100};const res=toJS(this,"",ctx);if(typeof onAnchor==="function")for(const{count,res:res2}of ctx.anchors.values())onAnchor(res2,count);return typeof reviver==="function"?applyReviver(reviver,{"":res},"",res):res}};var Alias=class extends NodeBase{constructor(source){super(ALIAS);this.source=source;Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(doc){let found=void 0;visit(doc,{Node:(_key,node)=>{if(node===this)return visit.BREAK;if(node.anchor===this.source)found=node}});return found}toJSON(_arg,ctx){if(!ctx)return{source:this.source};const{anchors,doc,maxAliasCount}=ctx;const source=this.resolve(doc);if(!source){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(msg)}let data=anchors.get(source);if(!data){toJS(source,null,ctx);data=anchors.get(source)}if(!data||data.res===void 0){const msg="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(msg)}if(maxAliasCount>=0){data.count+=1;if(data.aliasCount===0)data.aliasCount=getAliasCount(doc,source,anchors);if(data.count*data.aliasCount>maxAliasCount){const msg="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(msg)}}return data.res}toString(ctx,_onComment,_onChompKeep){const src=`*${this.source}`;if(ctx){anchorIsValid(this.source);if(ctx.options.verifyAliasOrder&&!ctx.anchors.has(this.source)){const msg=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(msg)}if(ctx.implicitKey)return`${src} `}return src}};function getAliasCount(doc,node,anchors){if(isAlias(node)){const source=node.resolve(doc);const anchor=anchors&&source&&anchors.get(source);return anchor?anchor.count*anchor.aliasCount:0}else if(isCollection(node)){let count=0;for(const item of node.items){const c=getAliasCount(doc,item,anchors);if(c>count)count=c}return count}else if(isPair(node)){const kc=getAliasCount(doc,node.key,anchors);const vc=getAliasCount(doc,node.value,anchors);return Math.max(kc,vc)}return 1}var isScalarValue=value=>!value||typeof value!=="function"&&typeof value!=="object";var Scalar=class extends NodeBase{constructor(value){super(SCALAR);this.value=value}toJSON(arg,ctx){return ctx?.keep?this.value:toJS(this.value,arg,ctx)}toString(){return String(this.value)}};Scalar.BLOCK_FOLDED="BLOCK_FOLDED";Scalar.BLOCK_LITERAL="BLOCK_LITERAL";Scalar.PLAIN="PLAIN";Scalar.QUOTE_DOUBLE="QUOTE_DOUBLE";Scalar.QUOTE_SINGLE="QUOTE_SINGLE";var defaultTagPrefix="tag:yaml.org,2002:";function findTagObject(value,tagName,tags){if(tagName){const match=tags.filter(t=>t.tag===tagName);const tagObj=match.find(t=>!t.format)??match[0];if(!tagObj)throw new Error(`Tag ${tagName} not found`);return tagObj}return tags.find(t=>t.identify?.(value)&&!t.format)}function createNode(value,tagName,ctx){if(isDocument(value))value=value.contents;if(isNode(value))return value;if(isPair(value)){const map2=ctx.schema[MAP].createNode?.(ctx.schema,null,ctx);map2.items.push(value);return map2}if(value instanceof String||value instanceof Number||value instanceof Boolean||typeof BigInt!=="undefined"&&value instanceof BigInt){value=value.valueOf()}const{aliasDuplicateObjects,onAnchor,onTagObj,schema:schema4,sourceObjects}=ctx;let ref=void 0;if(aliasDuplicateObjects&&value&&typeof value==="object"){ref=sourceObjects.get(value);if(ref){if(!ref.anchor)ref.anchor=onAnchor(value);return new Alias(ref.anchor)}else{ref={anchor:null,node:null};sourceObjects.set(value,ref)}}if(tagName?.startsWith("!!"))tagName=defaultTagPrefix+tagName.slice(2);let tagObj=findTagObject(value,tagName,schema4.tags);if(!tagObj){if(value&&typeof value.toJSON==="function"){value=value.toJSON()}if(!value||typeof value!=="object"){const node2=new Scalar(value);if(ref)ref.node=node2;return node2}tagObj=value instanceof Map?schema4[MAP]:Symbol.iterator in Object(value)?schema4[SEQ]:schema4[MAP]}if(onTagObj){onTagObj(tagObj);delete ctx.onTagObj}const node=tagObj?.createNode?tagObj.createNode(ctx.schema,value,ctx):typeof tagObj?.nodeClass?.from==="function"?tagObj.nodeClass.from(ctx.schema,value,ctx):new Scalar(value);if(tagName)node.tag=tagName;else if(!tagObj.default)node.tag=tagObj.tag;if(ref)ref.node=node;return node}function collectionFromPath(schema4,path,value){let v=value;for(let i=path.length-1;i>=0;--i){const k=path[i];if(typeof k==="number"&&Number.isInteger(k)&&k>=0){const a=[];a[k]=v;v=a}else{v=new Map([[k,v]])}}return createNode(v,void 0,{aliasDuplicateObjects:false,keepUndefined:false,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:schema4,sourceObjects:new Map})}var isEmptyPath=path=>path==null||typeof path==="object"&&!!path[Symbol.iterator]().next().done;var Collection=class extends NodeBase{constructor(type,schema4){super(type);Object.defineProperty(this,"schema",{value:schema4,configurable:true,enumerable:false,writable:true})}clone(schema4){const copy=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(schema4)copy.schema=schema4;copy.items=copy.items.map(it=>isNode(it)||isPair(it)?it.clone(schema4):it);if(this.range)copy.range=this.range.slice();return copy}addIn(path,value){if(isEmptyPath(path))this.add(value);else{const[key,...rest]=path;const node=this.get(key,true);if(isCollection(node))node.addIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}deleteIn(path){const[key,...rest]=path;if(rest.length===0)return this.delete(key);const node=this.get(key,true);if(isCollection(node))return node.deleteIn(rest);else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}getIn(path,keepScalar){const[key,...rest]=path;const node=this.get(key,true);if(rest.length===0)return!keepScalar&&isScalar(node)?node.value:node;else return isCollection(node)?node.getIn(rest,keepScalar):void 0}hasAllNullValues(allowScalar){return this.items.every(node=>{if(!isPair(node))return false;const n=node.value;return n==null||allowScalar&&isScalar(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(path){const[key,...rest]=path;if(rest.length===0)return this.has(key);const node=this.get(key,true);return isCollection(node)?node.hasIn(rest):false}setIn(path,value){const[key,...rest]=path;if(rest.length===0){this.set(key,value)}else{const node=this.get(key,true);if(isCollection(node))node.setIn(rest,value);else if(node===void 0&&this.schema)this.set(key,collectionFromPath(this.schema,rest,value));else throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`)}}};Collection.maxFlowStringSingleLineLength=60;var stringifyComment=str=>str.replace(/^(?!$)(?: $)?/gm,"#");function indentComment(comment,indent){if(/^\n+$/.test(comment))return comment.substring(1);return indent?comment.replace(/^(?! *$)/gm,indent):comment}var lineComment=(str,indent,comment)=>str.endsWith("\n")?indentComment(comment,indent):comment.includes("\n")?"\n"+indentComment(comment,indent):(str.endsWith(" ")?"":" ")+comment;var FOLD_FLOW="flow";var FOLD_BLOCK="block";var FOLD_QUOTED="quoted";function foldFlowLines(text,indent,mode="flow",{indentAtStart,lineWidth=80,minContentWidth=20,onFold,onOverflow}={}){if(!lineWidth||lineWidth<0)return text;const endStep=Math.max(1+minContentWidth,1+lineWidth-indent.length);if(text.length<=endStep)return text;const folds=[];const escapedFolds={};let end=lineWidth-indent.length;if(typeof indentAtStart==="number"){if(indentAtStart>lineWidth-Math.max(2,minContentWidth))folds.push(0);else end=lineWidth-indentAtStart}let split=void 0;let prev=void 0;let overflow=false;let i=-1;let escStart=-1;let escEnd=-1;if(mode===FOLD_BLOCK){i=consumeMoreIndentedLines(text,i);if(i!==-1)end=i+endStep}for(let ch;ch=text[i+=1];){if(mode===FOLD_QUOTED&&ch==="\\"){escStart=i;switch(text[i+1]){case"x":i+=3;break;case"u":i+=5;break;case"U":i+=9;break;default:i+=1}escEnd=i}if(ch==="\n"){if(mode===FOLD_BLOCK)i=consumeMoreIndentedLines(text,i);end=i+endStep;split=void 0}else{if(ch===" "&&prev&&prev!==" "&&prev!=="\n"&&prev!==" "){const next=text[i+1];if(next&&next!==" "&&next!=="\n"&&next!==" ")split=i}if(i>=end){if(split){folds.push(split);end=split+endStep;split=void 0}else if(mode===FOLD_QUOTED){while(prev===" "||prev===" "){prev=ch;ch=text[i+=1];overflow=true}const j=i>escEnd+1?i-2:escStart-1;if(escapedFolds[j])return text;folds.push(j);escapedFolds[j]=true;end=j+endStep;split=void 0}else{overflow=true}}}prev=ch}if(overflow&&onOverflow)onOverflow();if(folds.length===0)return text;if(onFold)onFold();let res=text.slice(0,folds[0]);for(let i2=0;i2<folds.length;++i2){const fold=folds[i2];const end2=folds[i2+1]||text.length;if(fold===0)res=`
|