You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fx/npm/index.js

721 lines
147 KiB
JavaScript

1 year ago
#!/usr/bin/env node
'use strict'
1 year ago
void async function main() {
const os = await import('node:os')
const fs = await import('node:fs')
1 year ago
const process = await import('node:process')
1 year ago
let flagHelp = false
let flagRaw = false
let flagSlurp = false
let flagYaml = false
1 year ago
const args = []
for (const arg of process.argv.slice(2)) {
if (arg === '--help' || arg === '-h') flagHelp = true
else if (arg === '--raw' || arg === '-r') flagRaw = true
else if (arg === '--slurp' || arg === '-s') flagSlurp = true
else if (arg === '-rs' || arg === '-sr') flagRaw = flagSlurp = true
else if (arg === '--yaml') flagYaml = true
1 year ago
else args.push(arg)
1 year ago
}
if (flagHelp || (args.length === 0 && process.stdin.isTTY)) {
1 year ago
return printUsage()
}
const theme = themes(process.stdout.isTTY ? (process.env.FX_THEME || '1') : '0')
await importFxrc(process.cwd())
await importFxrc(os.homedir())
let fd = 0 // stdin
if (args.length > 0) {
let filename =
isFile(fs, args[0]) ? args.shift() :
isFile(fs, args.at(-1)) ? args.pop() : false
if (filename) {
fd = fs.openSync(filename, 'r')
if (!flagYaml) flagYaml = /\.ya?ml$/i.test(filename)
}
}
const gen = await read(fd)
const input =
flagRaw
? readLine(gen)
: flagYaml
? parseYaml(gen)
: parseJson(gen)
1 year ago
if (flagSlurp) {
const array = []
for (const json of input) {
array.push(json)
}
await transform(array, args, theme)
1 year ago
} else {
for (const json of input) {
await transform(json, args, theme)
}
}
}()
1 year ago
1 year ago
const skip = Symbol('skip')
async function transform(json, args, theme) {
let i, code, jsCode, output = json
1 year ago
for ([i, code] of args.entries()) try {
jsCode = transpile(code)
const fn = `(function () {
const x = this
return ${jsCode}
})`
output = await run(output, fn)
1 year ago
} catch (err) {
await printErr(err)
1 year ago
}
if (typeof output === 'undefined')
console.error('undefined')
else if (typeof output === 'string')
console.log(output)
else if (output === skip)
return
else
console.log(stringify(output, theme))
1 year ago
async function printErr(err) {
const process = await import('node:process')
1 year ago
let pre = args.slice(0, i).join(' ')
let post = args.slice(i + 1).join(' ')
if (pre.length > 20) pre = '...' + pre.substring(pre.length - 20)
if (post.length > 20) post = post.substring(0, 20) + '...'
console.error(
`\n ${pre} ${code} ${post}\n` +
` ${' '.repeat(pre.length + 1)}${'^'.repeat(code.length)}\n` +
(jsCode !== code ? `\n${jsCode}\n` : ``) +
`\n${err.stack || err}`,
1 year ago
)
process.exit(1)
1 year ago
}
}
function transpile(code) {
1 year ago
if ('.' === code)
return 'x'
1 year ago
if (/^(\.\w*)+\[]/.test(code))
return `(${fold(code.split('[]'))})(x)`
1 year ago
function fold(s) {
if (s.length === 1)
return 'x => x' + s[0]
let obj = s.shift()
obj = obj === '.' ? 'x' : 'x' + obj
return `x => ${obj}.flatMap(${fold(s)})`
}
1 year ago
if (/^\.\[/.test(code))
return `x${code.substring(1)}`
1 year ago
if (/^\./.test(code))
return `x${code}`
1 year ago
// deprecated
if (/^map\(.+?\)$/i.test(code)) {
let s = code.substring(4, code.length - 1)
if (s[0] === '.') s = 'x' + s
return `x.map((x, i) => apply(${s}, x, i))`
}
1 year ago
if (/^@/.test(code)) {
const jsCode = transpile(code.substring(1))
return `x.map((x, i) => apply(${jsCode}, x, i))`
}
return code
}
async function run(json, code) {
const fn = eval(code).call(json)
1 year ago
return apply(fn, json)
1 year ago
function apply(fn, ...args) {
if (typeof fn === 'function') return fn(...args)
return fn
}
1 year ago
function len(x) {
if (Array.isArray(x)) return x.length
if (typeof x === 'string') return x.length
if (typeof x === 'object' && x !== null) return Object.keys(x).length
throw new Error(`Cannot get length of ${typeof x}`)
1 year ago
}
function uniq(x) {
if (Array.isArray(x)) return [...new Set(x)]
throw new Error(`Cannot get unique values of ${typeof x}`)
8 months ago
}
function sort(x) {
if (Array.isArray(x)) return x.sort()
throw new Error(`Cannot sort ${typeof x}`)
1 year ago
}
function map(fn) {
return function (x) {
if (Array.isArray(x)) return x.map((v, i) => fn(v, i))
throw new Error(`Cannot map ${typeof x}`)
}
}
function sortBy(fn) {
return function (x) {
if (Array.isArray(x)) return x.sort((a, b) => {
const fa = fn(a)
const fb = fn(b)
return fa < fb ? -1 : fa > fb ? 1 : 0
})
throw new Error(`Cannot sort ${typeof x}`)
}
1 year ago
}
1 year ago
function groupBy(keyFn) {
return function (x) {
1 year ago
const grouped = {}
for (const item of x) {
const key = typeof keyFn === 'function' ? keyFn(item) : item[keyFn]
if (!grouped.hasOwnProperty(key)) grouped[key] = []
1 year ago
grouped[key].push(item)
}
return grouped
1 year ago
}
}
function chunk(size) {
return function (x) {
const res = []
let i = 0
while (i < x.length) {
res.push(x.slice(i, i += size))
}
return res
}
}
function zip(...x) {
const length = Math.min(...x.map(a => a.length))
const res = []
for (let i = 0; i < length; i++) {
res.push(x.map(a => a[i]))
}
return res
}
function flatten(x) {
if (Array.isArray(x)) return x.flat()
throw new Error(`Cannot flatten ${typeof x}`)
}
function reverse(x) {
if (Array.isArray(x)) return x.reverse()
throw new Error(`Cannot reverse ${typeof x}`)
}
function keys(x) {
if (typeof x === 'object' && x !== null) return Object.keys(x)
throw new Error(`Cannot get keys of ${typeof x}`)
}
function values(x) {
if (typeof x === 'object' && x !== null) return Object.values(x)
throw new Error(`Cannot get values of ${typeof x}`)
}
2 months ago
function list(x) {
if (Array.isArray(x)) {
for (const y of x) console.log(y)
return skip
}
throw new Error(`Cannot list ${typeof x}`)
}
1 year ago
}
1 year ago
async function read(fd = 0) {
const fs = await import('node:fs')
const {Buffer} = await import('node:buffer')
const {StringDecoder} = await import('node:string_decoder')
const decoder = new StringDecoder('utf8')
return function* () {
while (true) {
const buffer = Buffer.alloc(4_096)
let bytesRead
try {
bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null)
} catch (e) {
if (e.code === 'EAGAIN' || e.code === 'EWOULDBLOCK') {
sleepSync(10)
continue
}
if (e.code === 'EOF') break
throw e
}
if (bytesRead === 0) break
for (const ch of decoder.write(buffer.subarray(0, bytesRead)))
yield ch
}
for (const ch of decoder.end())
yield ch
}()
}
function isFile(fs, path) {
9 months ago
const stat = fs.statSync(path, {throwIfNoEntry: false})
return stat !== undefined && stat.isFile()
}
function sleepSync(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
}
1 year ago
function* readLine(stdin) {
let buffer = ''
for (const ch of stdin) {
if (ch === '\n') {
yield buffer
buffer = ''
} else {
buffer += ch
}
}
return buffer
}
function* parseYaml(gen) {
let buffer = ''
for (const ch of gen) {
buffer += ch
}
try {
yield YAML.parse(buffer)
} catch (err) {
throw new SyntaxError(err.message)
}
}
function* parseJson(gen) {
let lineNumber = 1, buffer = '', lastChar, done = false
function next() {
({value: lastChar, done} = gen.next())
if (lastChar === '\n') lineNumber++
buffer += (lastChar || '')
if (buffer.length > 100) buffer = buffer.slice(-40)
}
next()
while (!done) {
const value = parseValue()
expectValue(value)
yield value
}
function parseValue() {
skipWhitespace()
const value =
parseString() ??
parseNumber() ??
parseObject() ??
parseArray() ??
parseKeyword('true', true) ??
parseKeyword('false', false) ??
parseKeyword('null', null)
skipWhitespace()
return value
}
function parseString() {
if (lastChar !== '"') return
let str = ''
let escaped = false
while (true) {
next()
if (escaped) {
if (lastChar === 'u') {
let unicode = ''
for (let i = 0; i < 4; i++) {
next()
if (!isHexDigit(lastChar)) {
throw new SyntaxError(errorSnippet(`Invalid Unicode escape sequence '\\u${unicode}${lastChar}'`))
}
unicode += lastChar
}
str += String.fromCharCode(parseInt(unicode, 16))
} else {
const escapedChar = {
'"': '"',
'\\': '\\',
'/': '/',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
}[lastChar]
if (!escapedChar) {
throw new SyntaxError(errorSnippet())
}
str += escapedChar
}
escaped = false
} else if (lastChar === '\\') {
escaped = true
} else if (lastChar === '"') {
break
} else if (lastChar < '\x1F') {
throw new SyntaxError(errorSnippet(`Unescaped control character ${JSON.stringify(lastChar)}`))
} else if (lastChar === undefined) {
throw new SyntaxError(errorSnippet())
} else {
str += lastChar
}
}
next()
return str
}
function parseNumber() {
if (!isDigit(lastChar) && lastChar !== '-') return
let numStr = ''
if (lastChar === '-') {
numStr += lastChar
next()
if (!isDigit(lastChar)) {
throw new SyntaxError(errorSnippet())
}
}
if (lastChar === '0') {
numStr += lastChar
next()
} else {
while (isDigit(lastChar)) {
numStr += lastChar
next()
}
}
if (lastChar === '.') {
numStr += lastChar
next()
if (!isDigit(lastChar)) {
throw new SyntaxError(errorSnippet())
}
while (isDigit(lastChar)) {
numStr += lastChar
next()
}
}
if (lastChar === 'e' || lastChar === 'E') {
numStr += lastChar
next()
if (lastChar === '+' || lastChar === '-') {
numStr += lastChar
next()
}
if (!isDigit(lastChar)) {
throw new SyntaxError(errorSnippet())
}
while (isDigit(lastChar)) {
numStr += lastChar
next()
}
}
return isInteger(numStr) ? toSafeNumber(numStr) : parseFloat(numStr)
}
function parseObject() {
if (lastChar !== '{') return
next()
skipWhitespace()
const obj = {}
if (lastChar === '}') {
next()
return obj
}
while (true) {
if (lastChar !== '"') {
throw new SyntaxError(errorSnippet())
}
const key = parseString()
skipWhitespace()
if (lastChar !== ':') {
throw new SyntaxError(errorSnippet())
}
next()
const value = parseValue()
expectValue(value)
obj[key] = value
skipWhitespace()
if (lastChar === '}') {
next()
return obj
} else if (lastChar === ',') {
next()
skipWhitespace()
if (lastChar === '}') {
next()
return obj
}
} else {
throw new SyntaxError(errorSnippet())
}
}
}
function parseArray() {
if (lastChar !== '[') return
next()
skipWhitespace()
const array = []
if (lastChar === ']') {
next()
return array
}
while (true) {
const value = parseValue()
expectValue(value)
array.push(value)
skipWhitespace()
if (lastChar === ']') {
next()
return array
} else if (lastChar === ',') {
next()
skipWhitespace()
if (lastChar === ']') {
next()
return array
}
} else {
throw new SyntaxError(errorSnippet())
}
}
}
function parseKeyword(name, value) {
if (lastChar !== name[0]) return
for (let i = 1; i < name.length; i++) {
next()
if (lastChar !== name[i]) {
throw new SyntaxError(errorSnippet())
}
}
next()
if (isWhitespace(lastChar) || lastChar === ',' || lastChar === '}' || lastChar === ']' || lastChar === undefined) {
return value
}
throw new SyntaxError(errorSnippet())
}
function skipWhitespace() {
while (isWhitespace(lastChar)) {
next()
}
skipComment()
}
function skipComment() {
if (lastChar === '/') {
next()
if (lastChar === '/') {
while (!done && lastChar !== '\n') {
next()
}
skipWhitespace()
} else if (lastChar === '*') {
while (!done) {
next()
if (lastChar === '*') {
next()
if (lastChar === '/') {
next()
break
}
}
}
skipWhitespace()
} else {
throw new SyntaxError(errorSnippet())
}
}
}
function isWhitespace(ch) {
return ch === ' ' || ch === '\n' || ch === '\t' || ch === '\r'
}
function isHexDigit(ch) {
return (ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')
}
function isDigit(ch) {
return ch >= '0' && ch <= '9'
}
function isInteger(value) {
return /^-?[0-9]+$/.test(value)
}
function toSafeNumber(str) {
const maxSafeInteger = Number.MAX_SAFE_INTEGER
const minSafeInteger = Number.MIN_SAFE_INTEGER
const num = BigInt(str)
return num >= minSafeInteger && num <= maxSafeInteger ? Number(num) : num
}
function expectValue(value) {
if (value === undefined) {
throw new SyntaxError(errorSnippet(`JSON value expected`))
}
}
function errorSnippet(message = `Unexpected character '${lastChar}'`) {
if (!lastChar) {
message = 'Unexpected end of input'
}
const lines = buffer.slice(-40).split('\n')
const lastLine = lines.pop()
const source =
lines.map(line => ` ${line}\n`).join('')
+ ` ${lastLine}${readEOL()}\n`
const p = ` ${'.'.repeat(Math.max(0, lastLine.length - 1))}^\n`
return `${message} on line ${lineNumber}.\n\n${source}${p}`
}
function readEOL() {
let line = ''
for (const ch of gen) {
if (!ch || ch === '\n' || line.length >= 60) break
line += ch
}
return line
}
}
function stringify(value, theme) {
function color(id, str) {
if (theme[id] === '') return str
return `\x1b[${theme[id]}m${str}\x1b[0m`
}
function getIndent(level) {
return ' '.repeat(2 * level)
}
function stringifyValue(value, level = 0) {
if (typeof value === 'string') {
return color(2, JSON.stringify(value))
} else if (typeof value === 'number') {
return color(3, `${value}`)
} else if (typeof value === 'bigint') {
return color(3, `${value}`)
} else if (typeof value === 'boolean') {
return color(4, `${value}`)
} else if (value === null || typeof value === 'undefined') {
return color(5, `null`)
} else if (Array.isArray(value)) {
if (value.length === 0) {
return color(0, `[]`)
}
const items = value
.map((v) => getIndent(level + 1) + stringifyValue(v, level + 1))
.join(color(0, ',') + '\n')
return color(0, '[') + '\n' + items + '\n' + getIndent(level) + color(0, ']')
} else if (typeof value === 'object') {
const keys = Object.keys(value)
if (keys.length === 0) {
return color(0, '{}')
}
const entries = keys
.map((key) =>
getIndent(level + 1) + color(1, `"${key}"`) + color(0, ': ') +
stringifyValue(value[key], level + 1),
)
.join(color(0, ',') + '\n')
return color(0, '{') + '\n' + entries + '\n' + getIndent(level) + color(0, '}')
}
throw new Error(`Unsupported value type: ${typeof value}`)
}
return stringifyValue(value)
}
function themes(id) {
const themes = {
'0': ['', '', '', '', '', ''],
'1': ['', '1;34', '32', '36', '35', '38;5;243'],
'2': ['', '32', '34', '36', '35', '38;5;243'],
'3': ['', '95', '93', '96', '31', '38;5;243'],
'4': ['', '38;5;50', '38;5;39', '38;5;98', '38;5;205', '38;5;243'],
'5': ['', '38;5;230', '38;5;221', '38;5;209', '38;5;209', '38;5;243'],
'6': ['', '38;5;69', '38;5;78', '38;5;221', '38;5;203', '38;5;243'],
'7': ['', '1;38;5;42', '1;38;5;213', '1;38;5;201', '1;38;5;201', '38;5;243'],
'8': ['', '1;38;5;51', '38;5;195', '38;5;123', '38;5;50', '38;5;243'],
'🔵': ['1;38;5;33', '38;5;33', '', '', '', ''],
'🥝': ['38;5;179', '1;38;5;154', '38;5;82', '38;5;226', '38;5;226', '38;5;230'],
}
return themes[id] || themes['1']
}
async function importFxrc(path) {
const {join} = await import('node:path')
const {pathToFileURL} = await import('node:url')
try {
await import(pathToFileURL(join(path, '.fxrc.js')))
} catch (err) {
if (err.code !== 'ERR_MODULE_NOT_FOUND') throw err
}
}
1 year ago
function printUsage() {
const usage = `Usage
fx [flags] [code...]
Flags
-h, --help print help
-r, --raw treat input as a raw string
-s, --slurp read all inputs into an array
--yaml parse input as YAML`
1 year ago
console.log(usage)
}
// yaml v2.4.0
// @formatter:off
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
${indent}${text.slice(0,end2)}`;else{if(mode===FOLD_QUOTED&&escapedFolds[fold])res+=`${text[fold]}\\`;res+=`
${indent}${text.slice(fold+1,end2)}`}}return res}function consumeMoreIndentedLines(text,i){let ch=text[i+1];while(ch===" "||ch===" "){do{ch=text[i+=1]}while(ch&&ch!=="\n");ch=text[i+1]}return i}var getFoldOptions=(ctx,isBlock2)=>({indentAtStart:isBlock2?ctx.indent.length:ctx.indentAtStart,lineWidth:ctx.options.lineWidth,minContentWidth:ctx.options.minContentWidth});var containsDocumentMarker=str=>/^(%|---|\.\.\.)/m.test(str);function lineLengthOverLimit(str,lineWidth,indentLength){if(!lineWidth||lineWidth<0)return false;const limit=lineWidth-indentLength;const strLen=str.length;if(strLen<=limit)return false;for(let i=0,start=0;i<strLen;++i){if(str[i]==="\n"){if(i-start>limit)return true;start=i+1;if(strLen-start<=limit)return false}}return true}function doubleQuotedString(value,ctx){const json=JSON.stringify(value);if(ctx.options.doubleQuotedAsJSON)return json;const{implicitKey}=ctx;const minMultiLineLength=ctx.options.doubleQuotedMinMultiLineLength;const indent=ctx.indent||(containsDocumentMarker(value)?" ":"");let str="";let start=0;for(let i=0,ch=json[i];ch;ch=json[++i]){if(ch===" "&&json[i+1]==="\\"&&json[i+2]==="n"){str+=json.slice(start,i)+"\\ ";i+=1;start=i;ch="\\"}if(ch==="\\")switch(json[i+1]){case"u":{str+=json.slice(start,i);const code=json.substr(i+2,4);switch(code){case"0000":str+="\\0";break;case"0007":str+="\\a";break;case"000b":str+="\\v";break;case"001b":str+="\\e";break;case"0085":str+="\\N";break;case"00a0":str+="\\_";break;case"2028":str+="\\L";break;case"2029":str+="\\P";break;default:if(code.substr(0,2)==="00")str+="\\x"+code.substr(2);else str+=json.substr(i,6)}i+=5;start=i+1}break;case"n":if(implicitKey||json[i+2]==='"'||json.length<minMultiLineLength){i+=1}else{str+=json.slice(start,i)+"\n\n";while(json[i+2]==="\\"&&json[i+3]==="n"&&json[i+4]!=='"'){str+="\n";i+=2}str+=indent;if(json[i+2]===" ")str+="\\";i+=1;start=i+1}break;default:i+=1}}str=start?str+json.slice(start):json;return implicitKey?str:foldFlowLines(str,indent,FOLD_QUOTED,getFoldOptions(ctx,false))}function singleQuotedString(value,ctx){if(ctx.options.singleQuote===false||ctx.implicitKey&&value.includes("\n")||/[ \t]\n|\n[ \t]/.test(value))return doubleQuotedString(value,ctx);const indent=ctx.indent||(containsDocumentMarker(value)?" ":"");const res="'"+value.replace(/'/g,"''").replace(/\n+/g,`$&
${indent}`)+"'";return ctx.implicitKey?res:foldFlowLines(res,indent,FOLD_FLOW,getFoldOptions(ctx,false))}function quotedString(value,ctx){const{singleQuote}=ctx.options;let qs;if(singleQuote===false)qs=doubleQuotedString;else{const hasDouble=value.includes('"');const hasSingle=value.includes("'");if(hasDouble&&!hasSingle)qs=singleQuotedString;else if(hasSingle&&!hasDouble)qs=doubleQuotedString;else qs=singleQuote?singleQuotedString:doubleQuotedString}return qs(value,ctx)}var blockEndNewlines;try{blockEndNewlines=new RegExp("(^|(?<!\n))\n+(?!\n|$)","g")}catch{blockEndNewlines=/\n+(?!\n|$)/g}function blockString({comment,type,value},ctx,onComment,onChompKeep){const{blockQuote,commentString,lineWidth}=ctx.options;if(!blockQuote||/\n[\t ]+$/.test(value)||/^\s*$/.test(value)){return quotedString(value,ctx)}const indent=ctx.indent||(ctx.forceBlockIndent||containsDocumentMarker(value)?" ":"");const literal=blockQuote==="literal"?true:blockQuote==="folded"||type===Scalar.BLOCK_FOLDED?false:type===Scalar.BLOCK_LITERAL?true:!lineLengthOverLimit(value,lineWidth,indent.length);if(!value)return literal?"|\n":">\n";let chomp;let endStart;for(endStart=value.length;endStart>0;--endStart){const ch=value[endStart-1];if(ch!=="\n"&&ch!==" "&&ch!==" ")break}let end=value.substring(endStart);const endNlPos=end.indexOf("\n");if(endNlPos===-1){chomp="-"}else if(value===end||endNlPos!==end.length-1){chomp="+";if(onChompKeep)onChompKeep()}else{chomp=""}if(end){value=value.slice(0,-end.length);if(end[end.length-1]==="\n")end=end.slice(0,-1);end=end.replace(blockEndNewlines,`$&${indent}`)}let startWithSpace=false;let startEnd;let startNlPos=-1;for(startEnd=0;startEnd<value.length;++startEnd){const ch=value[startEnd];if(ch===" ")startWithSpace=true;else if(ch==="\n")startNlPos=startEnd;else break}let start=value.substring(0,startNlPos<startEnd?startNlPos+1:startEnd);if(start){value=value.substring(start.length);start=start.replace(/\n+/g,`$&${indent}`)}const indentSize=indent?"2":"1";let header=(literal?"|":">")+(startWithSpace?indentSize:"")+chomp;if(comment){header+=" "+commentString(comment.replace(/ ?[\r\n]+/g," "));if(onComment)onComment()}if(literal){value=value.replace(/\n+/g,`$&${indent}`);return`${header}
${indent}${start}${value}${end}`}value=value.replace(/\n+/g,"\n$&").replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${indent}`);const body=foldFlowLines(`${start}${value}${end}`,indent,FOLD_BLOCK,getFoldOptions(ctx,true));return`${header}
${indent}${body}`}function plainString(item,ctx,onComment,onChompKeep){const{type,value}=item;const{actualString,implicitKey,indent,indentStep,inFlow}=ctx;if(implicitKey&&value.includes("\n")||inFlow&&/[[\]{},]/.test(value)){return quotedString(value,ctx)}if(!value||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)){return implicitKey||inFlow||!value.includes("\n")?quotedString(value,ctx):blockString(item,ctx,onComment,onChompKeep)}if(!implicitKey&&!inFlow&&type!==Scalar.PLAIN&&value.includes("\n")){return blockString(item,ctx,onComment,onChompKeep)}if(containsDocumentMarker(value)){if(indent===""){ctx.forceBlockIndent=true;return blockString(item,ctx,onComment,onChompKeep)}else if(implicitKey&&indent===indentStep){return quotedString(value,ctx)}}const str=value.replace(/\n+/g,`$&
${indent}`);if(actualString){const test=tag=>tag.default&&tag.tag!=="tag:yaml.org,2002:str"&&tag.test?.test(str);const{compat,tags}=ctx.doc.schema;if(tags.some(test)||compat?.some(test))return quotedString(value,ctx)}return implicitKey?str:foldFlowLines(str,indent,FOLD_FLOW,getFoldOptions(ctx,false))}function stringifyString(item,ctx,onComment,onChompKeep){const{implicitKey,inFlow}=ctx;const ss=typeof item.value==="string"?item:Object.assign({},item,{value:String(item.value)});let{type}=item;if(type!==Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))type=Scalar.QUOTE_DOUBLE}const _stringify=_type=>{switch(_type){case Scalar.BLOCK_FOLDED:case Scalar.BLOCK_LITERAL:return implicitKey||inFlow?quotedString(ss.value,ctx):blockString(ss,ctx,onComment,onChompKeep);case Scalar.QUOTE_DOUBLE:return doubleQuotedString(ss.value,ctx);case Scalar.QUOTE_SINGLE:return singleQuotedString(ss.value,ctx);case Scalar.PLAIN:return plainString(ss,ctx,onComment,onChompKeep);default:return null}};let res=_stringify(type);if(res===null){const{defaultKeyType,defaultStringType}=ctx.options;const t=implicitKey&&defaultKeyType||defaultStringType;res=_stringify(t);if(res===null)throw new Error(`Unsupported default string type ${t}`)}return res}function createStringifyContext(doc,options){const opt=Object.assign({blockQuote:true,commentString:stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:false,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:true,indentSeq:true,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:false,singleQuote:null,trueStr:"true",verifyAliasOrder:true},doc.schema.toStringOptions,options);let inFlow;switch(opt.collectionStyle){case"block":inFlow=false;break;case"flow":inFlow=true;break;default:inFlow=null}return{anchors:new Set,doc,flowCollectionPadding:opt.flowCollectionPadding?" ":"",indent:"",indentStep:typeof opt.indent==="number"?" ".repeat(opt.indent):" ",inFlow,options:opt}}function getTagObject(tags,item){if(item.tag){const match=tags.filter(t=>t.tag===item.tag);if(match.length>0)return match.find(t=>t.format===item.format)??match[0]}let tagObj=void 0;let obj;if(isScalar(item)){obj=item.value;const match=tags.filter(t=>t.identify?.(obj));tagObj=match.find(t=>t.format===item.format)??match.find(t=>!t.format)}else{obj=item;tagObj=tags.find(t=>t.nodeClass&&obj instanceof t.nodeClass)}if(!tagObj){const name=obj?.constructor?.name??typeof obj;throw new Error(`Tag not resolved for ${name} value`)}return tagObj}function stringifyProps(node,tagObj,{anchors,doc}){if(!doc.directives)return"";const props=[];const anchor=(isScalar(node)||isCollection(node))&&node.anchor;if(anchor&&anchorIsValid(anchor)){anchors.add(anchor);props.push(`&${anchor}`)}const tag=node.tag?node.tag:tagObj.default?null:tagObj.tag;if(tag)props.push(doc.directives.tagString(tag));return props.join(" ")}function stringify(item,ctx,onComment,onChompKeep){if(isPair(item))return item.toString(ctx,onComment,onChompKeep);if(isAlias(item)){if(ctx.doc.directives)return item.toString(ctx);if(ctx.resolvedAliases?.has(item)){throw new TypeError(`Cannot stringify circular structure without alias nodes`)}else{if(ctx.resolvedAliases)ctx.resolvedAliases.add(item);else ctx.resolvedAliases=new Set([item]);item=item.resolve(ctx.doc)}}let tagObj=void 0;const node=isNode(item)?item:ctx.doc.createNode(item,{onTagObj:o=>tagObj=o});if(!tagObj)tagObj=getTagObject(ctx.doc.schema.tags,node);const props=stringifyProps(node,tagObj,ctx);if(props.length>0)ctx.indentAtStart=(ctx.indentAtStart??0)+props.length+1;const str=typeof tagObj.stringify==="function"?tagObj.stringify(node,ctx,onComment,onChompKeep):isScalar(node)?stringifyString(node,ctx,onComment,onChompKeep):node.toString(ctx,onComment,onChompKeep);if(!props)return str;return isScalar(node)||str[0]==="{"||str[0]==="["?`${props} ${str}`:`${props}
${ctx.indent}${str}`}function stringifyPair({key,value},ctx,onComment,onChompKeep){const{allNullValues,doc,indent,indentStep,options:{commentString,indentSeq,simpleKeys}}=ctx;let keyComment=isNode(key)&&key.comment||null;if(simpleKeys){if(keyComment){throw new Error("With simple keys, key nodes cannot have comments")}if(isCollection(key)){const msg="With simple keys, collection cannot be used as a key value";throw new Error(msg)}}let explicitKey=!simpleKeys&&(!key||keyComment&&value==null&&!ctx.inFlow||isCollection(key)||(isScalar(key)?key.type===Scalar.BLOCK_FOLDED||key.type===Scalar.BLOCK_LITERAL:typeof key==="object"));ctx=Object.assign({},ctx,{allNullValues:false,implicitKey:!explicitKey&&(simpleKeys||!allNullValues),indent:indent+indentStep});let keyCommentDone=false;let chompKeep=false;let str=stringify(key,ctx,()=>keyCommentDone=true,()=>chompKeep=true);if(!explicitKey&&!ctx.inFlow&&str.length>1024){if(simpleKeys)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");explicitKey=true}if(ctx.inFlow){if(allNullValues||value==null){if(keyCommentDone&&onComment)onComment();return str===""?"?":explicitKey?`? ${str}`:str}}else if(allNullValues&&!simpleKeys||value==null&&explicitKey){str=`? ${str}`;if(keyComment&&!keyCommentDone){str+=lineComment(str,ctx.indent,commentString(keyComment))}else if(chompKeep&&onChompKeep)onChompKeep();return str}if(keyCommentDone)keyComment=null;if(explicitKey){if(keyComment)str+=lineComment(str,ctx.indent,commentString(keyComment));str=`? ${str}
${indent}:`}else{str=`${str}:`;if(keyComment)str+=lineComment(str,ctx.indent,commentString(keyComment))}let vsb,vcb,valueComment;if(isNode(value)){vsb=!!value.spaceBefore;vcb=value.commentBefore;valueComment=value.comment}else{vsb=false;vcb=null;valueComment=null;if(value&&typeof value==="object")value=doc.createNode(value)}ctx.implicitKey=false;if(!explicitKey&&!keyComment&&isScalar(value))ctx.indentAtStart=str.length+1;chompKeep=false;if(!indentSeq&&indentStep.length>=2&&!ctx.inFlow&&!explicitKey&&isSeq(value)&&!value.flow&&!value.tag&&!value.anchor){ctx.indent=ctx.indent.substring(2)}let valueCommentDone=false;const valueStr=stringify(value,ctx,()=>valueCommentDone=true,()=>chompKeep=true);let ws=" ";if(keyComment||vsb||vcb){ws=vsb?"\n":"";if(vcb){const cs=commentString(vcb);ws+=`
${indentComment(cs,ctx.indent)}`}if(valueStr===""&&!ctx.inFlow){if(ws==="\n")ws="\n\n"}else{ws+=`
${ctx.indent}`}}else if(!explicitKey&&isCollection(value)){const vs0=valueStr[0];const nl0=valueStr.indexOf("\n");const hasNewline=nl0!==-1;const flow=ctx.inFlow??value.flow??value.items.length===0;if(hasNewline||!flow){let hasPropsLine=false;if(hasNewline&&(vs0==="&"||vs0==="!")){let sp0=valueStr.indexOf(" ");if(vs0==="&"&&sp0!==-1&&sp0<nl0&&valueStr[sp0+1]==="!"){sp0=valueStr.indexOf(" ",sp0+1)}if(sp0===-1||nl0<sp0)hasPropsLine=true}if(!hasPropsLine)ws=`
${ctx.indent}`}}else if(valueStr===""||valueStr[0]==="\n"){ws=""}str+=ws+valueStr;if(ctx.inFlow){if(valueCommentDone&&onComment)onComment()}else if(valueComment&&!valueCommentDone){str+=lineComment(str,ctx.indent,commentString(valueComment))}else if(chompKeep&&onChompKeep){onChompKeep()}return str}function warn(logLevel,warning){if(logLevel==="debug"||logLevel==="warn"){if(typeof process!=="undefined"&&process.emitWarning)process.emitWarning(warning);else console.warn(warning)}}var MERGE_KEY="<<";function addPairToJSMap(ctx,map2,{key,value}){if(ctx?.doc.schema.merge&&isMergeKey(key)){value=isAlias(value)?value.resolve(ctx.doc):value;if(isSeq(value))for(const it of value.items)mergeToJSMap(ctx,map2,it);else if(Array.isArray(value))for(const it of value)mergeToJSMap(ctx,map2,it);else mergeToJSMap(ctx,map2,value)}else{const jsKey=toJS(key,"",ctx);if(map2 instanceof Map){map2.set(jsKey,toJS(value,jsKey,ctx))}else if(map2 instanceof Set){map2.add(jsKey)}else{const stringKey=stringifyKey(key,jsKey,ctx);const jsValue=toJS(value,stringKey,ctx);if(stringKey in map2)Object.defineProperty(map2,stringKey,{value:jsValue,writable:true,enumerable:true,configurable:true});else map2[stringKey]=jsValue}}return map2}var isMergeKey=key=>key===MERGE_KEY||isScalar(key)&&key.value===MERGE_KEY&&(!key.type||key.type===Scalar.PLAIN);function mergeToJSMap(ctx,map2,value){const source=ctx&&isAlias(value)?value.resolve(ctx.doc):value;if(!isMap(source))throw new Error("Merge sources must be maps or map aliases");const srcMap=source.toJSON(null,ctx,Map);for(const[key,value2]of srcMap){if(map2 instanceof Map){if(!map2.has(key))map2.set(key,value2)}else if(map2 instanceof Set){map2.add(key)}else if(!Object.prototype.hasOwnProperty.call(map2,key)){Object.defineProperty(map2,key,{value:value2,writable:true,enumerable:true,configurable:true})}}return map2}function stringifyKey(key,jsKey,ctx){if(jsKey===null)return"";if(typeof jsKey!=="object")return String(jsKey);if(isNode(key)&&ctx?.doc){const strCtx=createStringifyContext(ctx.doc,{});strCtx.anchors=new Set;for(const node of ctx.anchors.keys())strCtx.anchors.add(node.anchor);strCtx.inFlow=true;strCtx.inStringifyKey=true;const strKey=key.toString(strCtx);if(!ctx.mapKeyWarned){let jsonStr=JSON.stringify(strKey);if(jsonStr.length>40)jsonStr=jsonStr.substring(0,36)+'..."';warn(ctx.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);ctx.mapKeyWarned=true}return strKey}return JSON.stringify(jsKey)}function createPair(key,value,ctx){const k=createNode(key,void 0,ctx);const v=createNode(value,void 0,ctx);return new Pair(k,v)}var Pair=class _Pair{constructor(key,value=null){Object.defineProperty(this,NODE_TYPE,{value:PAIR});this.key=key;this.value=value}clone(schema4){let{key,value}=this;if(isNode(key))key=key.clone(schema4);if(isNode(value))value=value.clone(schema4);return new _Pair(key,value)}toJSON(_,ctx){const pair=ctx?.mapAsMap?new Map:{};return addPairToJSMap(ctx,pair,this)}toString(ctx,onComment,onChompKeep){return ctx?.doc?stringifyPair(this,ctx,onComment,onChompKeep):JSON.stringify(this)}};function stringifyCollection(collection,ctx,options){const flow=ctx.inFlow??collection.flow;const stringify4=flow?stringifyFlowCollection:stringifyBlockCollection;return stringify4(collection,ctx,options)}function stringifyBlockCollection({comment,items},ctx,{blockItemPrefix,flowChars,itemIndent,onChompKeep,onComment}){const{indent,options:{commentString}}=ctx;const itemCtx=Object.assign({},ctx,{indent:itemIndent,type:null});let chompKeep=false;const lines=[];for(let i=0;i<items.length;++i){const item=items[i];let comment2=null;if(isNode(item)){if(!chompKeep&&item.spaceBefore)lines.push("");addCommentBefore(ctx,lines,item.commentBefore,chompKeep);if(item.comment)comment2=item.comment}else if(isPair(item)){const ik=isNode(item.key)?item.key:null;if(ik){if(!chompKeep&&ik.spaceBefore)lines.push("");addCommentBefore(ctx,lines,ik.commentBefore,chompKeep)}}chompKeep=false;let str2=stringify(item,itemCtx,()=>comment2=null,()
${indent}${line}`:"\n"}}if(comment){str+="\n"+indentComment(commentString(comment),indent);if(onComment)onComment()}else if(chompKeep&&onChompKeep)onChompKeep();return str}function stringifyFlowCollection({comment,items},ctx,{flowChars,itemIndent,onComment}){const{indent,indentStep,flowCollectionPadding:fcPadding,options:{commentString}}=ctx;itemIndent+=indentStep;const itemCtx=Object.assign({},ctx,{indent:itemIndent,inFlow:true,type:null});let reqNewline=false;let linesAtValue=0;const lines=[];for(let i=0;i<items.length;++i){const item=items[i];let comment2=null;if(isNode(item)){if(item.spaceBefore)lines.push("");addCommentBefore(ctx,lines,item.commentBefore,false);if(item.comment)comment2=item.comment}else if(isPair(item)){const ik=isNode(item.key)?item.key:null;if(ik){if(ik.spaceBefore)lines.push("");addCommentBefore(ctx,lines,ik.commentBefore,false);if(ik.comment)reqNewline=true}const iv=isNode(item.value)?item.value:null;if(iv){if(iv.comment)comment2=iv.comment;if(iv.commentBefore)reqNewline=true}else if(item.value==null&&ik?.comment){comment2=ik.comment}}if(comment2)reqNewline=true;let str2=stringify(item,itemCtx,()=>comment2=null);if(i<items.length-1)str2+=",";if(comment2)str2+=lineComment(str2,itemIndent,commentString(comment2));if(!reqNewline&&(lines.length>linesAtValue||str2.includes("\n")))reqNewline=true;lines.push(str2);linesAtValue=lines.length}let str;const{start,end}=flowChars;if(lines.length===0){str=start+end}else{if(!reqNewline){const len=lines.reduce((sum,line)=>sum+line.length+2,2);reqNewline=ctx.options.lineWidth>0&&len>ctx.options.lineWidth}if(reqNewline){str=start;for(const line of lines)str+=line?`
${indentStep}${indent}${line}`:"\n";str+=`
${indent}${end}`}else{str=`${start}${fcPadding}${lines.join(" ")}${fcPadding}${end}`}}if(comment){str+=lineComment(str,indent,commentString(comment));if(onComment)onComment()}return str}function addCommentBefore({indent,options:{commentString}},lines,comment,chompKeep){if(comment&&chompKeep)comment=comment.replace(/^\n+/,"");if(comment){const ic=indentComment(commentString(comment),indent);lines.push(ic.trimStart())}}function findPair(items,key){const k=isScalar(key)?key.value:key;for(const it of items){if(isPair(it)){if(it.key===key||it.key===k)return it;if(isScalar(it.key)&&it.key.value===k)return it}}return void 0}var YAMLMap=class extends Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(schema4){super(MAP,schema4);this.items=[]}static from(schema4,obj,ctx){const{keepUndefined,replacer}=ctx;const map2=new this(schema4);const add=(key,value)=>{if(typeof replacer==="function")value=replacer.call(obj,key,value);else if(Array.isArray(replacer)&&!replacer.includes(key))return;if(value!==void 0||keepUndefined)map2.items.push(createPair(key,value,ctx))};if(obj instanceof Map){for(const[key,value]of obj)add(key,value)}else if(obj&&typeof obj==="object"){for(const key of Object.keys(obj))add(key,obj[key])}if(typeof schema4.sortMapEntries==="function"){map2.items.sort(schema4.sortMapEntries)}return map2}add(pair,overwrite){let _pair;if(isPair(pair))_pair=pair;else if(!pair||typeof pair!=="object"||!("key"in pair)){_pair=new Pair(pair,pair?.value)}else _pair=new Pair(pair.key,pair.value);const prev=findPair(this.items,_pair.key);const sortEntries=this.schema?.sortMapEntries;if(prev){if(!overwrite)throw new Error(`Key ${_pair.key} already set`);if(isScalar(prev.value)&&isScalarValue(_pair.value))prev.value.value=_pair.value;else prev.value=_pair.value}else if(sortEntries){const i=this.items.findIndex(item=>sortEntries(_pair,item)<0);if(i===-1)this.items.push(_pair);else this.items.splice(i,0,_pair)}else{this.items.push(_pair)}}delete(key){const it=findPair(this.items,key);if(!it)return false;const del=this.items.splice(this.items.indexOf(it),1);return del.length>0}get(key,keepScalar){const it=findPair(this.items,key);const node=it?.value;return(!keepScalar&&isScalar(node)?node.value:node)??void 0}has(key){return!!findPair(this.items,key)}set(key,value){this.add(new Pair(key,value),true)}toJSON(_,ctx,Type){const map2=Type?new Type:ctx?.mapAsMap?new Map:{};if(ctx?.onCreate)ctx.onCreate(map2);for(const item of this.items)addPairToJSMap(ctx,map2,item);return map2}toString(ctx,onComment,onChompKeep){if(!ctx)return JSON.stringify(this);for(const item of this.items){if(!isPair(item))throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`)}if(!ctx.allNullValues&&this.hasAllNullValues(false))ctx=Object.assign({},ctx,{allNullValues:true});return stringifyCollection(this,ctx,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:ctx.indent||"",onChompKeep,onComment})}};var map={collection:"map",default:true,nodeClass:YAMLMap,tag:"tag:yaml.org,2002:map",resolve(map2,onError){if(!isMap(map2))onError("Expected a mapping for this tag");return map2},createNode:(schema4,obj,ctx)=>YAMLMap.from(schema4,obj,ctx)};var YAMLSeq=class extends Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(schema4){super(SEQ,schema4);this.items=[]}add(value){this.items.push(value)}delete(key){const idx=asItemIndex(key);if(typeof idx!=="number")return false;const del=this.items.splice(idx,1);return del.length>0}get(key,keepScalar){const idx=asItemIndex(key);if(typeof idx!=="number")return void 0;const it=this.items[idx];return!keepScalar&&isScalar(it)?it.value:it}has(key){const idx=asItemIndex(key);return typeof idx==="number"&&idx<this.items.length}set(key,value){const idx=asItemIndex(key);if(typeof idx!=="number")throw new Error(`Expected a valid index, not ${key}.`);const prev=this.items[idx];if(isScalar(prev)&&isScalarValue(value))prev.value=value;else this.items[idx]=value}toJSON(_,ctx){const seq2=[];if(ctx?.onCreate)ctx.onCreate(seq2);let i=0;for(const item of this.items)seq2.pus
${pair.key.commentBefore}`:item.commentBefore;if(item.comment){const cn=pair.value??pair.key;cn.comment=cn.comment?`${item.comment}
${cn.comment}`:item.comment}item=pair}seq2.items[i]=isPair(item)?item:new Pair(item)}}else onError("Expected a sequence for this tag");return seq2}function createPairs(schema4,iterable,ctx){const{replacer}=ctx;const pairs2=new YAMLSeq(schema4);pairs2.tag="tag:yaml.org,2002:pairs";let i=0;if(iterable&&Symbol.iterator in Object(iterable))for(let it of iterable){if(typeof replacer==="function")it=replacer.call(iterable,String(i++),it);let key,value;if(Array.isArray(it)){if(it.length===2){key=it[0];value=it[1]}else throw new TypeError(`Expected [key, value] tuple: ${it}`)}else if(it&&it instanceof Object){const keys=Object.keys(it);if(keys.length===1){key=keys[0];value=it[key]}else{throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`)}}else{key=it}pairs2.items.push(createPair(key,value,ctx))}return pairs2}var pairs={collection:"seq",default:false,tag:"tag:yaml.org,2002:pairs",resolve:resolvePairs,createNode:createPairs};var YAMLOMap=class _YAMLOMap extends YAMLSeq{constructor(){super();this.add=YAMLMap.prototype.add.bind(this);this.delete=YAMLMap.prototype.delete.bind(this);this.get=YAMLMap.prototype.get.bind(this);this.has=YAMLMap.prototype.has.bind(this);this.set=YAMLMap.prototype.set.bind(this);this.tag=_YAMLOMap.tag}toJSON(_,ctx){if(!ctx)return super.toJSON(_);const map2=new Map;if(ctx?.onCreate)ctx.onCreate(map2);for(const pair of this.items){let key,value;if(isPair(pair)){key=toJS(pair.key,"",ctx);value=toJS(pair.value,key,ctx)}else{key=toJS(pair,"",ctx)}if(map2.has(key))throw new Error("Ordered maps must not include duplicate keys");map2.set(key,value)}return map2}static from(schema4,iterable,ctx){const pairs2=createPairs(schema4,iterable,ctx);const omap2=new this;omap2.items=pairs2.items;return omap2}};YAMLOMap.tag="tag:yaml.org,2002:omap";var omap={collection:"seq",identify:value=>value instanceof Map,nodeClass:YAMLOMap,default:false,tag:"tag:yaml.org,2002:omap",resolve(seq2,onError){const pairs2=resolvePairs(seq2,onError);const seenKeys=[];for(const{key}of pairs2.items){if(isScalar(key)){if(seenKeys.includes(key.value)){onError(`Ordered maps must not include duplicate keys: ${key.value}`)}else{seenKeys.push(key.value)}}}return Object.assign(new YAMLOMap,pairs2)},createNode:(schema4,iterable,ctx)=>YAMLOMap.from(schema4,iterable,ctx)};function boolStringify({value,source},ctx){const boolObj=value?trueTag:falseTag;if(source&&boolObj.test.test(source))return source;return value?ctx.options.trueStr:ctx.options.falseStr}var trueTag={identify:value=>value===true,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new Scalar(true),stringify:boolStringify};var falseTag={identify:value=>value===false,default:true,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>new Scalar(false),stringify:boolStringify};var floatNaN2={identify:value=>typeof value==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?\.(?:inf|Inf|INF|nan|NaN|NAN)$/,resolve:str=>str.slice(-3).toLowerCase()==="nan"?NaN:str[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:stringifyNumber};var floatExp2={identify:value=>typeof value==="number",default:true,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:str=>parseFloat(str.replace(/_/g,"")),stringify(node){const num=Number(node.value);return isFinite(num)?num.toExponential():stringifyNumber(node)}};var float2={identify:value=>typeof value==="number",default:true,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(str){const node=new Scalar(parseFloat(str.replace(/_/g,"")));const dot=str.indexOf(".");if(dot!==-1){const f=str.substring(dot+1).replace(/_/g,"");if(f[f.length-1]==="0")node.minFractionDigits=f.length}return node},stringify:stringifyNumber};var intIdentify3=value=>typeof value==="bigint"||Number.isInteger(value);function intResolve2(str,offset,radix,{intAsBigInt}){const sign=str[0];if(sign==="-"||sign==="+")offset+=1;str=str.substring(offset).replace(/_/g,"");if(in
${lineStr}
${pointer}
`}};function resolveProps(tokens,{flow,indicator,next,offset,onError,startOnNewline}){let spaceBefore=false;let atNewline=startOnNewline;let hasSpace=startOnNewline;let comment="";let commentSep="";let hasNewline=false;let hasNewlineAfterProp=false;let reqSpace=false;let anchor=null;let tag=null;let comma=null;let found=null;let start=null;for(const token of tokens){if(reqSpace){if(token.type!=="space"&&token.type!=="newline"&&token.type!=="comma")onError(token.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");reqSpace=false}switch(token.type){case"space":if(!flow&&atNewline&&indicator!=="doc-start"&&token.source[0]===" ")onError(token,"TAB_AS_INDENT","Tabs are not allowed as indentation");hasSpace=true;break;case"comment":{if(!hasSpace)onError(token,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const cb=token.source.substring(1)||" ";if(!comment)comment=cb;else comment+=commentSep+cb;commentSep="";atNewline=false;break}case"newline":if(atNewline){if(comment)comment+=token.source;else spaceBefore=true}else commentSep+=token.source;atNewline=true;hasNewline=true;if(anchor||tag)hasNewlineAfterProp=true;hasSpace=true;break;case"anchor":if(anchor)onError(token,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(token.source.endsWith(":"))onError(token.offset+token.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",true);anchor=token;if(start===null)start=token.offset;atNewline=false;hasSpace=false;reqSpace=true;break;case"tag":{if(tag)onError(token,"MULTIPLE_TAGS","A node can have at most one tag");tag=token;if(start===null)start=token.offset;atNewline=false;hasSpace=false;reqSpace=true;break}case indicator:if(anchor||tag)onError(token,"BAD_PROP_ORDER",`Anchors and tags must be after the ${token.source} indicator`);if(found)onError(token,"UNEXPECTED_TOKEN",`Unexpected ${token.source} in ${flow??"collection"}`);found=token;atNewline=false;hasSpace=false;break;case"comma":if(flow){if(comma)onError(token,"UNEXPECTED_TOKEN",`Unexpected , in ${flow}`);comma=token;atNewline=false;hasSpace=false;break}default:onError(token,"UNEXPECTED_TOKEN",`Unexpected ${token.type} token`);atNewline=false;hasSpace=false}}const last=tokens[tokens.length-1];const end=last?last.offset+last.source.length:offset;if(reqSpace&&next&&next.type!=="space"&&next.type!=="newline"&&next.type!=="comma"&&(next.type!=="scalar"||next.source!==""))onError(next.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");return{comma,found,spaceBefore,comment,hasNewline,hasNewlineAfterProp,anchor,tag,end,start:start??end}}function containsNewline(key){if(!key)return null;switch(key.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(key.source.includes("\n"))return true;if(key.end){for(const st of key.end)if(st.type==="newline")return true}return false;case"flow-collection":for(const it of key.items){for(const st of it.start)if(st.type==="newline")return true;if(it.sep){for(const st of it.sep)if(st.type==="newline")return true}if(containsNewline(it.key)||containsNewline(it.value))return true}return false;default:return true}}function flowIndentCheck(indent,fc,onError){if(fc?.type==="flow-collection"){const end=fc.end[0];if(end.indent===indent&&(end.source==="]"||end.source==="}")&&containsNewline(fc)){const msg="Flow end indicator should be more indented than parent";onError(end,"BAD_INDENT",msg,true)}}}function mapIncludes(ctx,items,search){const{uniqueKeys}=ctx.options;if(uniqueKeys===false)return false;const isEqual=typeof uniqueKeys==="function"?uniqueKeys:(a,b)=>a===b||isScalar(a)&&isScalar(b)&&a.value===b.value&&!(a.value==="<<"&&ctx.schema.merge);return items.some(pair=>isEqual(pair.key,search))}var startColMsg="All mapping items must start at the same column";function resolveBlockMap({composeNode:composeNode2,composeEmptyNode:composeEmptyNode2},ctx,bm,onError,tag){const NodeClass=tag?.nodeClass??YAMLMap;const map2=new NodeClass(ctx.schema);if(ctx.atRoot)ctx.atRoot=false;let offset=b
${comment}`:comment}else if(afterEmptyLine||doc.directives.docStart||!dc){doc.commentBefore=comment}else if(isCollection(dc)&&!dc.flow&&dc.items.length>0){let it=dc.items[0];if(isPair(it))it=it.key;const cb=it.commentBefore;it.commentBefore=cb?`${comment}
${cb}`:comment}else{const cb=dc.commentBefore;dc.commentBefore=cb?`${comment}
${cb}`:comment}}if(afterDoc){Array.prototype.push.apply(doc.errors,this.errors);Array.prototype.push.apply(doc.warnings,this.warnings)}else{doc.errors=this.errors;doc.warnings=this.warnings}this.prelude=[];this.errors=[];this.warnings=[]}streamInfo(){return{comment:parsePrelude(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(tokens,forceDoc=false,endOffset=-1){for(const token of tokens)yield*this.next(token);yield*this.end(forceDoc,endOffset)}*next(token){switch(token.type){case"directive":this.directives.add(token.source,(offset,message,warning)=>{const pos=getErrorPos(token);pos[0]+=offset;this.onError(pos,"BAD_DIRECTIVE",message,warning)});this.prelude.push(token.source);this.atDirectives=true;break;case"document":{const doc=composeDoc(this.options,this.directives,token,this.onError);if(this.atDirectives&&!doc.directives.docStart)this.onError(token,"MISSING_CHAR","Missing directives-end/doc-start indicator line");this.decorate(doc,false);if(this.doc)yield this.doc;this.doc=doc;this.atDirectives=false;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(token.source);break;case"error":{const msg=token.source?`${token.message}: ${JSON.stringify(token.source)}`:token.message;const error=new YAMLParseError(getErrorPos(token),"UNEXPECTED_TOKEN",msg);if(this.atDirectives||!this.doc)this.errors.push(error);else this.doc.errors.push(error);break}case"doc-end":{if(!this.doc){const msg="Unexpected doc-end without preceding document";this.errors.push(new YAMLParseError(getErrorPos(token),"UNEXPECTED_TOKEN",msg));break}this.doc.directives.docEnd=true;const end=resolveEnd(token.end,token.offset+token.source.length,this.doc.options.strict,this.onError);this.decorate(this.doc,true);if(end.comment){const dc=this.doc.comment;this.doc.comment=dc?`${dc}
${end.comment}`:end.comment}this.doc.range[2]=end.offset;break}default:this.errors.push(new YAMLParseError(getErrorPos(token),"UNEXPECTED_TOKEN",`Unsupported token ${token.type}`))}}*end(forceDoc=false,endOffset=-1){if(this.doc){this.decorate(this.doc,true);yield this.doc;this.doc=null}else if(forceDoc){const opts=Object.assign({_directives:this.directives},this.options);const doc=new Document(void 0,opts);if(this.atDirectives)this.onError(endOffset,"MISSING_CHAR","Missing directives-end indicator line");doc.range=[0,endOffset,endOffset];this.decorate(doc,false);yield doc}}};var BREAK2=Symbol("break visit");var SKIP2=Symbol("skip children");var REMOVE2=Symbol("remove item");function visit2(cst,visitor){if("type"in cst&&cst.type==="document")cst={start:cst.start,value:cst.value};_visit(Object.freeze([]),cst,visitor)}visit2.BREAK=BREAK2;visit2.SKIP=SKIP2;visit2.REMOVE=REMOVE2;visit2.itemAtPath=(cst,path)=>{let item=cst;for(const[field,index]of path){const tok=item?.[field];if(tok&&"items"in tok){item=tok.items[index]}else return void 0}return item};visit2.parentCollection=(cst,path)=>{const parent=visit2.itemAtPath(cst,path.slice(0,-1));const field=path[path.length-1][0];const coll=parent?.[field];if(coll&&"items"in coll)return coll;throw new Error("Parent collection not found")};function _visit(path,item,visitor){let ctrl=visitor(item,path);if(typeof ctrl==="symbol")return ctrl;for(const field of["key","value"]){const token=item[field];if(token&&"items"in token){for(let i=0;i<token.items.length;++i){const ci=_visit(Object.freeze(path.concat([[field,i]])),token.items[i],visitor);if(typeof ci==="number")i=ci-1;else if(ci===BREAK2)return BREAK2;else if(ci===REMOVE2){token.items.splice(i,1);i-=1}}if(typeof ctrl==="function"&&field==="key")ctrl=ctrl(item,path)}}return typeof ctrl==="function"?ctrl(item,path):ctrl}var BOM="\uFEFF";var DOCUMENT="";var FLOW_END="";var SCALAR2="";function tokenType(source){switch(source){case BOM:return"byte-order-mark";case DOCUMENT:return"doc-mode";case FLOW_END:return"flow-error-end";case SCALAR2:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case"\n":case"\r\n":return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(source[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function isEmpty(ch){switch(ch){case void 0:case" ":case"\n":case"\r":case" ":return true;default:return false}}var hexDigits="0123456789ABCDEFabcdef".split("");var tagChars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()".split("");var invalidFlowScalarChars=",[]{}".split("");var invalidAnchorChars=" ,[]{}\n\r ".split("");var isNotAnchorChar=ch=>!ch||invalidAnchorChars.includes(ch);var Lexer=class{constructor(){this.atEnd=false;this.blockScalarIndent=-1;this.blockScalarKeep=false;this.buffer="";this.flowKey=false;this.flowLevel=0;this.indentNext=0;this.indentValue=0;this.lineEndPos=null;this.next=null;this.pos=0}*lex(source,incomplete=false){if(source){this.buffer=this.buffer?this.buffer+source:source;this.lineEndPos=null}this.atEnd=!incomplete;let next=this.next??"stream";while(next&&(incomplete||this.hasChars(1)))next=yield*this.parseNext(next)}atLineEnd(){let i=this.pos;let ch=this.buffer[i];while(ch===" "||ch===" ")ch=this.buffer[++i];if(!ch||ch==="#"||ch==="\n")return true;if(ch==="\r")return this.buffer[i+1]==="\n";return false}charAt(n){return this.buffer[this.pos+n]}continueScalar(offset){let ch=this.buffer[offset];if(this.indentNext>0){let indent=0;while(ch===" ")ch=this.buffer[++indent+offset];if(ch==="\r"){const next=this.buffer[indent+offset+1];if(next==="\n"||!next&&!this.atEnd)return offset+indent+1}return ch==="\n"||
}()