sd-wildcards-utils
Version: 
Parse Stable Diffusion wildcards source to a YAML object.
1 lines • 81.1 kB
Source Map (JSON)
{"version":3,"file":"index.umd.development.cjs","sources":["../src/options.ts","../src/format.ts","../src/is.ts","../src/util.ts","../src/valid.ts","../src/items.ts","../src/merge.ts","../src/find.ts","../src/check.ts","../src/index.ts"],"sourcesContent":["import { Document } from 'yaml';\nimport { IOptionsParseDocument, IOptionsSharedWildcardsYaml, IOptionsStringify } from './types';\n\nexport function getOptionsShared<T extends IOptionsSharedWildcardsYaml>(opts?: T): Pick<T, keyof IOptionsSharedWildcardsYaml >\n{\n\topts ??= {} as T;\n\treturn {\n\t\tallowMultiRoot: opts.allowMultiRoot,\n\t\tdisableUniqueItemValues: opts.disableUniqueItemValues,\n\t\tminifyPrompts: opts.minifyPrompts,\n\t\tdisableUnsafeQuote: opts.disableUnsafeQuote,\n\t}\n}\n\nexport function defaultOptionsStringifyMinify()\n{\n\treturn {\n\t\tlineWidth: 0,\n\t\tminifyPrompts: true,\n\t} as const satisfies IOptionsStringify\n}\n\nexport function defaultOptionsStringify(opts?: IOptionsStringify): IOptionsStringify\n{\n\treturn {\n\t\tblockQuote: true,\n\t\tdefaultKeyType: 'PLAIN',\n\t\tdefaultStringType: 'PLAIN',\n\t\t//lineWidth: 0,\n\t\t//minContentWidth: 100,\n\t\t//indentSeq: false,\n\t\t//doubleQuotedMinMultiLineLength: 10,\n\t\tcollectionStyle: 'block',\n\t\tuniqueKeys: true,\n\t\t...opts,\n\t} satisfies IOptionsStringify\n}\n\nexport function defaultOptionsParseDocument(opts?: IOptionsParseDocument): IOptionsParseDocument\n{\n\topts ??= {};\n\n\topts = {\n\t\t//keepSourceTokens: true,\n\t\tprettyErrors: true,\n\t\t...opts,\n\t\ttoStringDefaults: defaultOptionsStringify({\n\t\t\t...getOptionsShared(opts),\n\t\t\t...opts.toStringDefaults,\n\t\t}),\n\t}\n\n\treturn opts\n}\n\nexport function getOptionsFromDocument<T extends Document>(doc: T, opts?: IOptionsParseDocument)\n{\n\treturn {\n\t\t...doc.options,\n\t\t...opts,\n\t} as IOptionsParseDocument\n}\n\n","import { IOptionsSharedWildcardsYaml } from './types';\nimport { Extractor } from '@bluelovers/extract-brackets';\n\nlet ExtractParents: Extractor;\n\nexport function stripZeroStr(value: string)\n{\n\treturn value\n\t\t.replace(/[\\x00\\u200b]+/g, '')\n}\n\nexport function trimPrompts(value: string)\n{\n\treturn value\n\t\t.replace(/\\xa0/g, ' ')\n\t\t.replace(/^\\s+|\\s+$/g, '')\n\t\t.replace(/^\\s+|\\s+$/gm, '')\n\t\t.replace(/\\n\\s*\\n/g, '\\n')\n\t\t.replace(/\\s{2,}/gm, ' ')\n\t\t// .replace(/[ ,.]+(?=,|$)/gm, '')\n\t\t// .replace(/,\\s*(?=,|$)/g, '')\n\t\t.replace(/,\\s{2,}/gm, ', ')\n\t\t.replace(/\\s+,/gm, ',')\n\t\t.replace(/,+\\s*$/g, '')\n\t\t;\n}\n\nexport function normalizeWildcardsYamlString(value: string)\n{\n\tvalue = stripZeroStr(value)\n\t\t.replace(/\\xa0/g, ' ')\n\t\t.replace(/[,.]+(?=,)/gm, '')\n\t\t.replace(/[ .]+$/gm, '')\n\t\t.replace(/(\\w) +(?=,)/gm, '$1')\n\t\t.replace(/(,) {2,}(?=\\S)/gm, '$1 ')\n\t\t.replace(/\\{\\s+(\\d+(?:\\.\\d+)?(?:-(?:\\d+(?:\\.\\d+)?)?\\$\\$|::))/gm, '{$1')\n\t\t.replace(/\\|\\s(\\d+(?:\\.\\d+)?::)/gm, '|$1')\n\t\t.replace(/^[ \\t]+-[ \\t]*$/gm, '')\n\t\t.replace(/^([ \\t]+-)[ \\t]{1,}(?:[ ,.]+|(?=[^ \\t]))/gm, '$1 ')\n\t\t// .replace(/^([ \\t]+-[^\\n]+),+$/gm, '$1')\n\t;\n\treturn value\n}\n\n/**\n * trim Dynamic Prompts Variables\n */\nexport function trimPromptsDynamic(value: string)\n{\n\tif (value.includes('='))\n\t{\n\t\tExtractParents ??= new Extractor('{', '}');\n\n\t\tconst ebs = ExtractParents.extract(value);\n\t\tlet i = 0;\n\t\tlet _do: boolean;\n\n\t\t// console.dir(ebs);\n\n\t\tlet arr = ebs\n\t\t\t.reduce((a, eb) => {\n\n\t\t\t\tlet s: string = typeof eb.nest[0] === 'string' && eb.nest[0] as any;\n\t\t\t\tlet input = eb.str;\n\n\t\t\t\tlet pre = value.slice(i, eb.index[0]);\n\n\t\t\t\tif (_do) \n\t\t\t\t{\n\t\t\t\t\tpre = pre.replace(/^[\\s\\r\\n]+/g, '');\n\t\t\t\t}\n\n\t\t\t\t// console.log(_do, pre);\n\n\t\t\t\t_do = s?.includes('=');\n\n\t\t\t\tif (_do)\n\t\t\t\t{\n\t\t\t\t\tinput = input.replace(/^\\s*([\\w_]+)\\s*=\\s*/, '$1=');\n\t\t\t\t}\n\n\t\t\t\ta.push(pre);\n\n\t\t\t\ta.push('{' + input.trim() + '}');\n\n\t\t\t\ti = eb.index[0] + eb.str.length + 2;\n\n\t\t\t\treturn a\n\t\t\t}, [] as string[])\n\t\t\t;\n\n\t\t\tlet pre = value.slice(i)\n\n\t\t\tif (_do)\n\t\t\t{\n\t\t\t\tpre = pre.replace(/[\\s\\r\\n]+$|^[\\s\\r\\n]+/g, '');\n\t\t\t}\n\n\t\tarr.push(pre);\n\n\t\t// console.dir(arr);\n\n\t\tvalue = arr.join('');\n\n\t\t// value = value\n\t\t// \t.replace(/\\s*(\\$\\{[\\w_]+=[^{}]*\\})\\s*/g, '$1')\n\t\t// \t;\n\t}\n\treturn value\n}\n\nexport function formatPrompts(value: string, opts?: IOptionsSharedWildcardsYaml)\n{\n\topts ??= {};\n\n\tvalue = stripZeroStr(value);\n\tvalue = trimPrompts(value);\n\tvalue = normalizeWildcardsYamlString(value);\n\n\tif (opts.minifyPrompts)\n\t{\n\t\tvalue = value\n\t\t\t.replace(/(,)\\s+/gm, '$1')\n\t\t\t.replace(/\\s+(,)/gm, '$1')\n\t\t\t.replace(/(?<=,\\|})\\s+/gm, '')\n\t\t\t.replace(/\\s+(?=\\{(?:\\s*\\d+(?:\\.\\d+)?::)?,)/gm, '')\n\t\t;\n\t\tvalue = trimPromptsDynamic(value);\n\t}\n\n\treturn value\n}\n\nexport function stripBlankLines(value: string, appendEOF?: boolean)\n{\n\tvalue = value\n\t\t.replace(/(\\r?\\n)[\\s\\r\\n\\t\\xa0]+(\\r?\\n)/g, '$1$2')\n\t\t.replace(/(\\r?\\n)(?:\\r?\\n)(?=[\\s\\t\\xa0])/g, '$1')\n\t\t.replace(/[ \\xa0\\t]+$/gm, '')\n\t;\n\n\tif (appendEOF)\n\t{\n\t\tvalue = value.replace(/\\s+$/, '');\n\t\tvalue += '\\n\\n';\n\t}\n\n\treturn value\n}\n","import { isDocument, YAMLMap, Document, isMap } from 'yaml';\nimport { IWildcardsYAMLDocument, IWildcardsYAMLMapRoot, IWildcardsYAMLPairValue, IWildcardsYAMLScalar } from './types';\n\nexport function isWildcardsYAMLDocument<T extends IWildcardsYAMLMapRoot>(node: IWildcardsYAMLDocument<T, true> | Document<T, true>): node is IWildcardsYAMLDocument<T, true>\nexport function isWildcardsYAMLDocument<T extends IWildcardsYAMLDocument | Document>(doc: any): doc is IWildcardsYAMLDocument\nexport function isWildcardsYAMLDocument<T extends YAMLMap = IWildcardsYAMLMapRoot>(node: any): node is IWildcardsYAMLDocument<T, true>\nexport function isWildcardsYAMLDocument(doc: any)\n{\n\treturn isDocument(doc)\n}\n\nexport function isWildcardsYAMLDocumentAndContentsIsMap(doc: any): doc is IWildcardsYAMLDocument\n{\n\treturn isDocument(doc) && isMap(doc.contents)\n}\n\nexport function isWildcardsYAMLMap<K extends IWildcardsYAMLScalar, V extends IWildcardsYAMLPairValue>(doc: IWildcardsYAMLMapRoot<K, V> | YAMLMap.Parsed<K, V> | YAMLMap<K, V>): doc is IWildcardsYAMLMapRoot<K, V>\nexport function isWildcardsYAMLMap<K extends IWildcardsYAMLScalar = IWildcardsYAMLScalar, V extends IWildcardsYAMLPairValue = IWildcardsYAMLPairValue>(doc: any): doc is IWildcardsYAMLMapRoot<K, V>\nexport function isWildcardsYAMLMap(doc: any)\n{\n\treturn isMap(doc)\n}\n","import { array_unique_overwrite } from 'array-hyper-unique';\nimport {\n\tIMatchDynamicPromptsWildcardsEntry,\n\tIVisitPathsNode,\n\tIYamlNodeTypeSymbol,\n\tIOptionsMatchDynamicPromptsWildcards,\n} from './types';\n\nexport const SYMBOL_YAML_NODE_TYPE_ALIAS = Symbol.for('yaml.alias');\nexport const SYMBOL_YAML_NODE_TYPE_DOC = Symbol.for('yaml.document');\nexport const SYMBOL_YAML_NODE_TYPE_MAP = Symbol.for('yaml.map');\nexport const SYMBOL_YAML_NODE_TYPE_PAIR = Symbol.for('yaml.pair');\nexport const SYMBOL_YAML_NODE_TYPE_SCALAR = Symbol.for('yaml.scalar');\nexport const SYMBOL_YAML_NODE_TYPE_SEQ = Symbol.for('yaml.seq');\nexport const SYMBOL_YAML_NODE_TYPE = Symbol.for('yaml.node.type');\n\n// export const RE_DYNAMIC_PROMPTS_WILDCARDS = /(?<!#[^\\n]*)__([&~!@])?([*\\w\\/_\\-]+)(\\([^\\n#]+\\))?__/;\nexport const RE_DYNAMIC_PROMPTS_WILDCARDS = /(?<!#[^\\n]*)__([&~!@])?([\\w*](?:[*\\w\\/_\\-]+?))(\\([^\\n#]+\\))?__/;\nexport const RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE = /(?<!#[^\\n]*)__([&~!@])?([\\w*](?:[*\\w\\/_\\-\\s]+?))(\\([^\\n#]+\\))?__/;\n\n/**\n * for `matchAll`\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll\n */\nexport const RE_DYNAMIC_PROMPTS_WILDCARDS_GLOBAL = new RegExp(RE_DYNAMIC_PROMPTS_WILDCARDS, RE_DYNAMIC_PROMPTS_WILDCARDS.flags + 'g');\nexport const RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE_GLOBAL = new RegExp(RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE, RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE.flags + 'g');\n\nexport const RE_WILDCARDS_NAME = /^[\\w\\-_\\/]+$/\nexport const RE_WILDCARDS_NAME_STAR = /^[\\w\\-_\\/*]+$/\n\n/**\n * Checks if the input string matches the dynamic prompts wildcards pattern.\n *\n * @param input - The input string to check.\n * @returns A boolean indicating whether the input string matches the pattern.\n *\n * @remarks\n * This function uses the `matchDynamicPromptsWildcards` function to perform the check.\n * It returns `true` if the input string is a full match, and `false` otherwise.\n *\n * @example\n * ```typescript\n * const input1 = \"__season_clothes(season=winter)__\";\n * console.log(isDynamicPromptsWildcards(input1)); // Output: true\n *\n * const input2 = \"__season_clothes(season=__season_clothes__)__\";\n * console.log(isDynamicPromptsWildcards(input2)); // Output: true\n *\n * const input3 = \"This is not a wildcards pattern\";\n * console.log(isDynamicPromptsWildcards(input3)); // Output: false\n * ```\n */\nexport function isDynamicPromptsWildcards(input: string): boolean\n{\n\treturn matchDynamicPromptsWildcards(input).isFullMatch;\n}\n\n/**\n * Matches the input string against the dynamic prompts wildcards pattern.\n *\n * @see https://github.com/adieyal/sd-dynamic-prompts/blob/main/docs/SYNTAX.md\n *\n * @param input - The input string to match.\n * @returns An object containing the matched groups or `null` if no match is found.\n *\n * @remarks\n * This function uses the `RE_DYNAMIC_PROMPTS_WILDCARDS` regular expression to perform the match.\n * The returned object contains the following properties:\n * - `name`: The name extracted from the input string.\n * - `variables`: The variables extracted from the input string.\n * - `keyword`: The keyword extracted from the input string.\n * - `source`: The original matched source string.\n * - `isFullMatch`: A boolean indicating whether the input string is a full match.\n *\n * @example\n * ```typescript\n * const input = \"\\_\\_season_clothes(season=winter)\\_\\_\";\n * const result = matchDynamicPromptsWildcards(input);\n * console.log(result);\n * // Output: { name: 'season_clothes', variables: '(season=winter)', keyword: undefined, source: '\\__season_clothes(season=winter)\\__', isFullMatch: true }\n * ```\n *\n * @example\n * __season_clothes(season=winter)__\n * __season_clothes(season=__season_clothes__)__\n * __season_clothes(season=!__season_clothes__)__\n *\n * __season_clothes(season=__@season_clothes__)__\n * __season_clothes(season=__~season_clothes__)__\n *\n * __@season_clothes(season=__season_clothes__)__\n * __~season_clothes(season=__season_clothes__)__\n *\n * __season_clothes(season={summer|autumn|winter|spring})__\n * __season_clothes(season=!{summer|autumn|winter|spring})__\n *\n * __season_clothes(season={@summer|autumn|winter|spring})__\n * __season_clothes(season={!summer|autumn|winter|spring})__\n *\n * __season_clothes(season=)__\n */\nexport function matchDynamicPromptsWildcards(input: string, opts?: IOptionsMatchDynamicPromptsWildcards)\n{\n\tconst m = input.match(opts?.unsafe ? RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE : RE_DYNAMIC_PROMPTS_WILDCARDS);\n\treturn _matchDynamicPromptsWildcardsCore(m, input);\n}\n\nexport function _matchDynamicPromptsWildcardsCore(m: RegExpMatchArray,\n\tinput?: string,\n): IMatchDynamicPromptsWildcardsEntry\n{\n\tif (!m) return null;\n\n\tlet [source, keyword, name, variables] = m;\n\n\treturn {\n\t\tname,\n\t\tvariables,\n\t\tkeyword,\n\t\tsource,\n\t\tisFullMatch: source === (input ?? m.input),\n\t\tisStarWildcards: name.includes('*'),\n\t}\n}\n\n/**\n * Generator function that matches all occurrences of the dynamic prompts wildcards pattern in the input string.\n */\nexport function* matchDynamicPromptsWildcardsAllGenerator(input: string, opts?: IOptionsMatchDynamicPromptsWildcards)\n{\n\tconst ls = input.matchAll(opts?.unsafe ? RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE_GLOBAL : RE_DYNAMIC_PROMPTS_WILDCARDS_GLOBAL);\n\n\tfor (let m of ls)\n\t{\n\t\tyield _matchDynamicPromptsWildcardsCore(m, input);\n\t}\n}\n\n/**\n * Converts the generator function `matchDynamicPromptsWildcardsAllGenerator` into an array.\n */\nexport function matchDynamicPromptsWildcardsAll(input: string, opts?: IOptionsMatchDynamicPromptsWildcards)\n{\n\tconst arr = [...matchDynamicPromptsWildcardsAllGenerator(input, opts)] as IMatchDynamicPromptsWildcardsEntry[];\n\n\treturn opts?.unique ? array_unique_overwrite(arr) : arr\n}\n\n/**\n * Checks if the given name is a valid Wildcards name.\n *\n * @param name - The name to check.\n * @returns A boolean indicating whether the name is valid.\n *\n * @remarks\n * A valid Wildcards name should:\n * - Only contain alphanumeric characters, hyphens, or underscores.\n * - Not start or end with an underscore.\n * - Not contain consecutive underscores.\n *\n * @example\n * ```typescript\n * const name1 = \"season_clothes\";\n * console.log(isWildcardsName(name1)); // Output: true\n *\n * const name2 = \"_season_clothes\";\n * console.log(isWildcardsName(name2)); // Output: false\n *\n * const name3 = \"season_clothes_\";\n * console.log(isWildcardsName(name3)); // Output: false\n *\n * const name4 = \"season__clothes\";\n * console.log(isWildcardsName(name4)); // Output: false\n *\n * const name5 = \"season-clothes\";\n * console.log(isWildcardsName(name5)); // Output: true\n * ```\n */\nexport function isWildcardsName(name: string): boolean\n{\n\treturn RE_WILDCARDS_NAME.test(name) && !_isBadWildcardsNameCore(name)\n}\n\nexport function isBadWildcardsName(name: string): boolean\n{\n\treturn !RE_WILDCARDS_NAME.test(name) || _isBadWildcardsNameCore(name)\n}\n\nexport function isBadWildcardsPath(name: string): boolean\n{\n\treturn !RE_WILDCARDS_NAME_STAR.test(name) || _isBadWildcardsNameCore(name)\n}\n\nexport function _isBadWildcardsNameCore(name: string)\n{\n\treturn /^[\\s_\\/\\\\-]|[\\s_\\/\\\\-]$|[\\s_\\/\\\\-]\\/|\\/[\\s_\\/\\\\-]|\\/\\/|[\\s_\\/\\\\-]{2,}/.test(name)\n}\n\nexport function assertWildcardsName(name: string)\n{\n\tif (isBadWildcardsName(name))\n\t{\n\t\tthrow new SyntaxError(`Invalid Wildcards Name Syntax: ${name}`)\n\t}\n}\n\nexport function assertWildcardsPath(name: string)\n{\n\tif (isBadWildcardsPath(name))\n\t{\n\t\tthrow new SyntaxError(`Invalid Paths Syntax [UNSAFE_SYNTAX] \"${name}\"`)\n\t}\n}\n\nexport function convertWildcardsNameToPaths(name: string)\n{\n\treturn name.split('/');\n}\n\nexport function isWildcardsPathSyntx(path: string): path is `__${string}__`\n{\n\treturn RE_DYNAMIC_PROMPTS_WILDCARDS.test(path)\n}\n\nexport function wildcardsPathToPaths(path: string)\n{\n\tif (isWildcardsPathSyntx(path))\n\t{\n\t\tpath = matchDynamicPromptsWildcards(path).name\n\t}\n\n\treturn convertWildcardsNameToPaths(path);\n}\n\nexport function getNodeTypeSymbol(node: IVisitPathsNode): IYamlNodeTypeSymbol\n{\n\t// @ts-ignore\n\treturn node?.[SYMBOL_YAML_NODE_TYPE]\n}\n\nexport function _getNodeTypeCore(sym: IYamlNodeTypeSymbol)\n{\n\ttry\n\t{\n\t\treturn Symbol.keyFor(sym)\n\t}\n\tcatch (e)\n\t{\n\n\t}\n}\n\nexport function getNodeType(node: IVisitPathsNode)\n{\n\treturn _getNodeTypeCore(getNodeTypeSymbol(node))\n}\n\nexport function isSameNodeType(a: IVisitPathsNode, b: IVisitPathsNode)\n{\n\tconst s = getNodeTypeSymbol(a);\n\n\treturn s && getNodeTypeSymbol(b) === s;\n}\n","import { Document, isDocument, isMap, isNode, isScalar, YAMLMap, YAMLSeq, Scalar, isPair, Pair } from 'yaml';\nimport { handleVisitPathsFull, uniqueSeqItems, visitWildcardsYAML } from './items';\nimport {\n\tICheckErrorResult,\n\tIOptionsParseDocument,\n\tIOptionsSharedWildcardsYaml,\n\tIOptionsVisitorMap,\n\tIRecordWildcards, IVisitorFnKey,\n\tIVisitPathsNode,\n\tIWildcardsYAMLDocument, IWildcardsYAMLPair,\n\tIWildcardsYAMLScalar,\n} from './types';\nimport { getNodeType } from './util';\nimport { Extractor, IExtractionResult, infoNearExtractionError } from '@bluelovers/extract-brackets';\n\nlet _extractor: Extractor;\n\nexport function _checkBrackets(value: string)\n{\n\t_extractor ??= new Extractor('{', '}');\n\n\treturn _extractor.extractSync(value, (e) => {\n\t\tif (e)\n\t\t{\n\t\t\tlet result: IExtractionResult = e.self?.result;\n\n\t\t\tif (!result)\n\t\t\t{\n\t\t\t\treturn {\n\t\t\t\t\tvalue,\n\t\t\t\t\terror: `Invalid Error [UNKNOWN]: ${e}`\n\t\t\t\t} satisfies ICheckErrorResult\n\t\t\t}\n\n\t\t\tlet near = infoNearExtractionError(value, e.self)\n\n\t\t\treturn {\n\t\t\t\tvalue,\n\t\t\t\tindex: result.index?.[0],\n\t\t\t\tnear,\n\t\t\t\terror: `Invalid Syntax [BRACKET] ${e.message} near \"${near}\"`\n\t\t\t} satisfies ICheckErrorResult\n\t\t}\n\t}) as ICheckErrorResult\n}\n\n// @ts-ignore\nexport function _validMap(key: IVisitorFnKey | null, node: YAMLMap, ...args: any[])\n{\n\tconst idx = node.items.findIndex(pair => (!isPair(pair) || pair?.value == null));\n\tif (idx !== -1)\n\t{\n\t\t// @ts-ignore\n\t\tconst paths = handleVisitPathsFull(key, node, ...args);\n\n\t\tconst elem = node.items[idx];\n\t\tthrow new SyntaxError(`Invalid SYNTAX. paths: [${paths}], key: ${key}, node: ${node}, elem: ${elem}`)\n\t}\n}\n\n// @ts-ignore\nexport function _validSeq(key: IVisitorFnKey | null, nodeSeq: YAMLSeq, ...args: any[]): asserts nodeSeq is YAMLSeq<Scalar | IWildcardsYAMLScalar>\n{\n\tfor (const index in nodeSeq.items)\n\t{\n\t\tconst entry = nodeSeq.items[index] as IVisitPathsNode;\n\n\t\tif (!isScalar(entry))\n\t\t{\n\t\t\t// @ts-ignore\n\t\t\tconst paths = handleVisitPathsFull(key, nodeSeq, ...args);\n\n\t\t\tthrow new SyntaxError(`Invalid SYNTAX. entry type should be 'Scalar', but got '${getNodeType(entry)}'. paths: [${paths}], entryIndex: ${index}, entry: ${entry}, nodeKey: ${key}, node: ${nodeSeq}`)\n\t\t}\n\t}\n}\n\nexport function _validPair(key: IVisitorFnKey, pair: IWildcardsYAMLPair | Pair, ...args: any[])\n{\n\tconst keyNode = (pair as IWildcardsYAMLPair).key as IWildcardsYAMLScalar | string;\n\n\tconst notOk = !isSafeKey(typeof keyNode === 'string' ? keyNode : keyNode.value)\n\n\tif (notOk)\n\t{\n\t\t// @ts-ignore\n\t\tconst paths = handleVisitPathsFull(key, pair, ...args);\n\n\t\tthrow new SyntaxError(`Invalid Key. paths: [${paths}], key: ${key}, keyNodeValue: \"${(keyNode as any)?.value}\", keyNode: ${keyNode}`)\n\t}\n}\n\nexport function createDefaultVisitWildcardsYAMLOptions(opts?: IOptionsParseDocument): IOptionsVisitorMap\n{\n\tlet defaults = {\n\t\tMap: _validMap,\n\t\tSeq: _validSeq,\n\t} as IOptionsVisitorMap\n\n\topts ??= {};\n\n\tif (!opts.allowUnsafeKey)\n\t{\n\t\tdefaults.Pair = _validPair\n\t}\n\n\tif (!opts.disableUniqueItemValues)\n\t{\n\t\tconst fn = defaults.Seq;\n\t\tdefaults.Seq = (key, node, ...args) =>\n\t\t{\n\t\t\t// @ts-ignore\n\t\t\tfn(key, node, ...args);\n\t\t\tuniqueSeqItems(node.items);\n\t\t}\n\t}\n\n\treturn defaults;\n}\n\nexport function validWildcardsYamlData<T extends IRecordWildcards | IWildcardsYAMLDocument | Document>(data: T | unknown,\n\topts?: IOptionsSharedWildcardsYaml,\n): asserts data is T\n{\n\topts ??= {};\n\n\tif (isDocument(data))\n\t{\n\t\tif (isNode(data.contents) && !isMap(data.contents))\n\t\t{\n\t\t\tthrow TypeError(`The 'contents' property of the provided YAML document must be a YAMLMap. Received: ${data.contents}`)\n\t\t}\n\n\t\tvisitWildcardsYAML(data, createDefaultVisitWildcardsYAMLOptions(opts));\n\n\t\tdata = data.toJSON()\n\t}\n\n\tif (typeof data === 'undefined' || data === null)\n\t{\n\t\tif (opts.allowEmptyDocument)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tthrow new TypeError(`The provided JSON contents should not be empty. ${data}`)\n\t}\n\n\tlet rootKeys = Object.keys(data);\n\n\tif (!rootKeys.length)\n\t{\n\t\tthrow TypeError(`The provided JSON contents must contain at least one key.`)\n\t}\n\telse if (rootKeys.length !== 1 && !opts.allowMultiRoot)\n\t{\n\t\tthrow TypeError(`The provided JSON object cannot have more than one root key. Only one root key is allowed unless explicitly allowed by the 'allowMultiRoot' option.`)\n\t}\n}\n\nexport function isSafeKey<T extends string>(key: T | unknown): key is T\n{\n\treturn typeof key === 'string' && /^[._\\w-]+$/.test(key) && !/^[\\._-]|[\\._-]$/.test(key)\n}\n\nexport function _validKey<T extends string>(key: T | unknown): asserts key is T\n{\n\tif (!isSafeKey(key))\n\t{\n\t\tthrow new SyntaxError(`Invalid Key. key: ${key}`)\n\t}\n}\n\nexport function _checkValue(value: string): ICheckErrorResult\n{\n\tlet m = /(?:^|[\\s{},])_(?=[^_]|$)|(?<!_)_(?:[\\s{},]|$)|\\/_+|_+\\/(?!\\()|\\([\\w_]+\\s*=(?:!|\\s*[{}$])/.exec(value)\n\n\tif (m)\n\t{\n\t\tlet near = _nearString(value, m!.index, m![0]);\n\t\tlet match = m![0];\n\n\t\treturn {\n\t\t\tvalue,\n\t\t\tmatch,\n\t\t\tindex: m!.index,\n\t\t\tnear,\n\t\t\terror: `Invalid Syntax [UNSAFE_SYNTAX] \"${match}\" in value near \"${near}\"`\n\t\t}\n\t}\n\telse if (/[{}]/.test(value))\n\t{\n\t\treturn _checkBrackets(value)\n\t}\n}\n\nexport function _nearString(value: string, index: number, match: string, offset: number = 15) \n{\n\tlet s = Math.max(0, index - offset);\n\tlet e = index + (match?.length || 0) + offset;\n\n\treturn value.slice(s, e)\n}\n","import { array_unique_overwrite, defaultChecker } from 'array-hyper-unique';\nimport { Document, isDocument, isMap, isPair, isScalar, isSeq, Node, ParsedNode, visit, visitor, YAMLMap } from 'yaml';\nimport {\n\tIOptionsParseDocument,\n\tIOptionsVisitor,\n\tIResultDeepFindSingleRootAt,\n\tIVisitorFnKey,\n\tIVisitPathsList,\n\tIVisitPathsNodeList,\n\tIWildcardsYAMLDocument,\n\tIWildcardsYAMLMapRoot,\n\tIWildcardsYAMLPair,\n\tIWildcardsYAMLScalar,\n} from './types';\nimport { formatPrompts } from './format';\nimport { isWildcardsYAMLDocument, isWildcardsYAMLMap } from './is';\nimport { _checkValue } from './valid';\n\nexport function visitWildcardsYAML(node: Node | Document | null, visitorOptions: IOptionsVisitor)\n{\n\treturn visit(node, visitorOptions as visitor)\n}\n\nexport function defaultCheckerIgnoreCase(a: unknown, b: unknown)\n{\n\tif (typeof a === 'string' && typeof b === 'string')\n\t{\n\t\ta = a.toLowerCase();\n\t\tb = b.toLowerCase();\n\t}\n\n\treturn defaultChecker(a, b)\n}\n\nexport function uniqueSeqItemsChecker(a: Node, b: Node)\n{\n\tif (isScalar(a) && isScalar(b))\n\t{\n\t\treturn defaultCheckerIgnoreCase(a.value, b.value)\n\t}\n\treturn defaultCheckerIgnoreCase(a, b)\n}\n\nexport function uniqueSeqItems<T extends Node>(items: (T | unknown)[])\n{\n\treturn array_unique_overwrite(items, {\n\t\t// @ts-ignore\n\t\tchecker: uniqueSeqItemsChecker,\n\t}) as T[];\n}\n\n/**\n * This function is used to find a single root node in a YAML structure.\n * It traverses the YAML structure and returns the first node that has only one child.\n * If the node is a Document, it will start from its contents.\n *\n * @param node - The YAML node to start the search from.\n * @param result - An optional object to store the result.\n * @returns - An object containing the paths, key, value, and parent of the found single root node.\n *            If no single root node is found, it returns the input `result` object.\n * @throws - Throws a TypeError if the Document Node is passed as a child node.\n */\nexport function deepFindSingleRootAt(node: ParsedNode | Document.Parsed | IWildcardsYAMLMapRoot | IWildcardsYAMLDocument,\n\tresult?: IResultDeepFindSingleRootAt,\n)\n{\n\tif (isMap(node) && node.items.length === 1)\n\t{\n\t\tlet child = node.items[0] as IWildcardsYAMLPair;\n\n\t\tlet key = child.key.value;\n\n\t\tlet paths = result?.paths?.slice() ?? [];\n\t\t(paths as any as string[]).push(key);\n\n\t\tlet value = child.value;\n\n\t\tif (isSeq(value))\n\t\t{\n\t\t\treturn result\n\t\t}\n\n\t\treturn deepFindSingleRootAt(value, {\n\t\t\tpaths,\n\t\t\tkey,\n\t\t\tvalue,\n\t\t\tparent: node as IWildcardsYAMLMapRoot,\n\t\t} as const satisfies IResultDeepFindSingleRootAt)\n\n\t}\n\telse if (isDocument(node))\n\t{\n\t\tif (result)\n\t\t{\n\t\t\tthrow new TypeError(`The Document Node should not as Child Node`)\n\t\t}\n\n\t\tlet value = node.contents as IWildcardsYAMLMapRoot;\n\n\t\treturn deepFindSingleRootAt(value, {\n\t\t\tpaths: [] as const,\n\t\t\tkey: void 0,\n\t\t\tvalue,\n\t\t\tparent: node as IWildcardsYAMLDocument,\n\t\t} as const satisfies IResultDeepFindSingleRootAt)\n\t}\n\n\treturn result;\n}\n\nexport function _handleVisitPathsCore(nodePaths: IVisitPathsNodeList): IWildcardsYAMLPair[]\n{\n\treturn nodePaths.filter(p => isPair(p)) as any\n}\n\nexport function convertPairsToPathsList(nodePaths: IWildcardsYAMLPair[])\n{\n\treturn nodePaths.map(p => p.key.value) as IVisitPathsList\n}\n\n/**\n * [ 'root', 'root2', 'sub2', 'sub2-2' ]\n */\nexport function handleVisitPaths(nodePaths: IVisitPathsNodeList)\n{\n\treturn convertPairsToPathsList(_handleVisitPathsCore(nodePaths))\n}\n\n/**\n * full paths\n *\n * [ 'root', 'root2', 'sub2', 'sub2-2', 1 ]\n */\nexport function handleVisitPathsFull<T>(key: IVisitorFnKey | null,\n\t_node: T,\n\tnodePaths: IVisitPathsNodeList,\n)\n{\n\tconst paths = handleVisitPaths(nodePaths);\n\n\tif (typeof key === 'number')\n\t{\n\t\tpaths.push(key)\n\t}\n\n\treturn paths\n}\n\n/**\n * This function is used to find all paths of sequences in a given YAML structure.\n * It traverses the YAML structure and collects the paths of all sequences (Seq nodes).\n *\n * @param node - The YAML node to start the search from. It can be a Node, Document.\n * @returns - An array of arrays, where each inner array represents a path of sequence nodes.\n *            Each path is represented as an array of paths, where each path is a key or index.\n */\nexport function findWildcardsYAMLPathsAll(node: Node | Document)\n{\n\tconst ls: IVisitPathsList[] = [];\n\tvisitWildcardsYAML(node, {\n\t\tSeq(...args)\n\t\t{\n\t\t\tconst paths = handleVisitPathsFull(...args);\n\n\t\t\tls.push(paths)\n\t\t}\n\t});\n\treturn ls;\n}\n\nconst RE_UNSAFE_QUOTE = /['\"]/;\nconst RE_UNSAFE_VALUE = /^\\s*-|[{$~!@}\\n|:?#'\"%]/;\nconst RE_UNSAFE_PLAIN = /-/\n\nexport function _visitNormalizeScalar(key: IVisitorFnKey, node: IWildcardsYAMLScalar, runtime: {\n\tcheckUnsafeQuote: boolean,\n\toptions: IOptionsParseDocument,\n})\n{\n\tlet value = node.value as string;\n\n\tif (typeof value === 'string')\n\t{\n\t\tif (runtime.checkUnsafeQuote && RE_UNSAFE_QUOTE.test(value))\n\t\t{\n\t\t\tthrow new SyntaxError(`Invalid SYNTAX [UNSAFE_QUOTE]. key: ${key}, node: ${node}`)\n\t\t}\n\t\telse if (node.type === 'QUOTE_DOUBLE' || node.type === 'QUOTE_SINGLE' && !value.includes('\\\\'))\n\t\t{\n\t\t\tnode.type = 'PLAIN';\n\t\t}\n\n\t\tvalue = formatPrompts(value, runtime.options);\n\n\t\tif (!value.length)\n\t\t{\n\t\t\tthrow new SyntaxError(`Invalid SYNTAX [EMPTY_VALUE]. key: ${key}, node: ${node}`)\n\t\t}\n\t\telse if (RE_UNSAFE_VALUE.test(value))\n\t\t{\n\t\t\tif (node.type === 'PLAIN')\n\t\t\t{\n\t\t\t\tnode.type = 'BLOCK_LITERAL'\n\t\t\t}\n\t\t\telse if (node.type === 'BLOCK_FOLDED' && /#/.test(value))\n\t\t\t{\n\t\t\t\tnode.type = 'BLOCK_LITERAL'\n\t\t\t}\n\t\t}\n\t\telse if (node.type === 'PLAIN' && RE_UNSAFE_PLAIN.test(value)) \n\t\t{\n\t\t\tnode.type = 'QUOTE_DOUBLE'\n\t\t}\n\n\t\tlet res = _checkValue(value);\n\t\tif (res?.error)\n\t\t{\n\t\t\tthrow new SyntaxError(`${res.error}. key: ${key}, node: ${node}`)\n\t\t}\n\n\t\tnode.value = value;\n\t}\n}\n\nexport function getTopRootContents<T extends IWildcardsYAMLDocument | Document | IWildcardsYAMLMapRoot | YAMLMap>(doc: T)\n{\n\tif (isWildcardsYAMLDocument(doc))\n\t{\n\t\t// @ts-ignore\n\t\tdoc = doc.contents as IWildcardsYAMLMapRoot\n\t}\n\n\tif (isWildcardsYAMLMap(doc))\n\t{\n\t\treturn doc\n\t}\n\n\tthrow new TypeError(`Input document is not a YAML Document or a YAML Map. Please provide a valid YAML structure.`)\n}\n\nexport function getTopRootNodes<T extends IWildcardsYAMLDocument | Document | IWildcardsYAMLMapRoot | YAMLMap>(doc: T)\n{\n\treturn getTopRootContents(doc).items\n}\n","import { Document, isDocument, isMap, isSeq, YAMLMap, YAMLSeq } from 'yaml';\n\nimport {\n\tIOptionsMergeWilcardsYAMLDocumentJsonBy,\n\tIRecordWildcards,\n\tIWildcardsYAMLDocument,\n\tIWildcardsYAMLMapRoot,\n\tIWildcardsYAMLPair,\n\tIWildcardsYAMLPairValue,\n\tIWildcardsYAMLSeq,\n} from './types';\nimport { deepFindSingleRootAt } from './items';\nimport { AggregateErrorExtra } from 'lazy-aggregate-error';\nimport { getNodeType, isSameNodeType } from './util';\n\nexport function mergeWildcardsYAMLDocumentRoots<T extends Pick<Document<YAMLMap>, 'contents'>>(ls: [T, ...any[]])\n{\n\treturn ls.reduce(_mergeWildcardsYAMLDocumentRootsCore) as T\n}\n\nexport function _mergeWildcardsYAMLDocumentRootsCore<T extends Pick<Document<YAMLMap>, 'contents'>>(a: T, b: any)\n{\n\t// @ts-ignore\n\ta.contents.items.push(...b.contents.items);\n\n\treturn a\n}\n\n/**\n * @example\n * import { deepmergeAll } from 'deepmerge-plus';\n *\n * mergeWildcardsYAMLDocumentJsonBy(ls, {\n * \tdeepmerge: deepmergeAll,\n * })\n */\nexport function mergeWildcardsYAMLDocumentJsonBy<T extends Document | unknown, R = IRecordWildcards>(ls: T[], opts: IOptionsMergeWilcardsYAMLDocumentJsonBy): R\n{\n\treturn opts.deepmerge(ls.map(_toJSON)) as any\n}\n\nexport function _toJSON<T extends Document | unknown, R = IRecordWildcards>(v: T): R\n{\n\t// @ts-ignore\n\treturn isDocument(v) ? v.toJSON() : v\n}\n\nexport function _mergeSeqCore<T extends YAMLSeq | IWildcardsYAMLSeq>(a: T, b: NoInfer<T>)\n{\n\ta.items.push(...(b as IWildcardsYAMLSeq).items);\n\treturn a\n}\n\nexport function mergeSeq<T extends YAMLSeq | IWildcardsYAMLSeq>(a: T, b: NoInfer<T>)\n{\n\tif (isSeq(a) && isSeq(b))\n\t{\n\t\treturn _mergeSeqCore(a, b)\n\t}\n\n\tthrow new TypeError(`Only allow merge YAMLSeq`)\n}\n\n/**\n * Merges a single root YAMLMap or Document with a list of YAMLMap or Document.\n * The function only merges the root nodes of the provided YAML structures.\n *\n * @throws {TypeError} - If the merge target is not a YAMLMap or Document.\n * @throws {TypeError} - If the current node is not a YAMLMap.\n * @throws {TypeError} - If the current node does not support deep merge.\n */\nexport function mergeFindSingleRoots<T extends IWildcardsYAMLMapRoot | IWildcardsYAMLDocument>(doc: T, list: NoInfer<T>[] | NoInfer<T>): T\n{\n\tif (!isDocument(doc) && !isMap(doc))\n\t{\n\t\tthrow TypeError(`The merge target should be a YAMLMap or Document. doc: ${doc}`)\n\t}\n\n\tlist = [list].flat() as NoInfer<T>[];\n\n\tfor (let node of list)\n\t{\n\t\tlet result = deepFindSingleRootAt(node);\n\t\tlet paths = result?.paths;\n\n\t\tif (result)\n\t\t{\n\t\t\tlet current = doc.getIn(paths) as IWildcardsYAMLMapRoot;\n\n\t\t\tif (current)\n\t\t\t{\n\t\t\t\tif (!isMap(current))\n\t\t\t\t{\n\t\t\t\t\tthrow new TypeError(`Only YAMLMap can be merged [1]. path: ${paths}, type: ${getNodeType(current)} node: ${current}`)\n\t\t\t\t}\n\n\t\t\t\tresult.value.items\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t.forEach((p: IWildcardsYAMLPair) => {\n\t\t\t\t\t\tconst key = p.key.value;\n\t\t\t\t\t\tconst sub: IWildcardsYAMLPairValue = current.get(key);\n\n\t\t\t\t\t\tif (sub)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif (isSeq(sub) && isSeq(p.value))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t_mergeSeqCore(sub, p.value)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (isMap(sub) && isMap(p.value))\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tconst errKeys: string[] = [];\n\t\t\t\t\t\t\t\tconst errors: Error[] = []\n\t\t\t\t\t\t\t\tfor (const pair of p.value.items)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tif (isSeq(pair.value))\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tlet sub2 = sub.get(pair.key);\n\n\t\t\t\t\t\t\t\t\t\t\tif (isSeq(sub2))\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t_mergeSeqCore(sub2, pair.value);\n\t\t\t\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t\tsub.add(pair, false);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcatch (e: any)\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\terrKeys.push(pair.key.value);\n\t\t\t\t\t\t\t\t\t\terrors.push(e);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif (errors.length)\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthrow new AggregateErrorExtra(errors, `Failure when merging sub YAMLMap. Paths: ${JSON.stringify(paths.concat(key))}. Conflicting keys: ${JSON.stringify(errKeys)}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tif (!isSameNodeType(sub, p.value))\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthrow new TypeError(`Only allow merge same node type at paths: ${JSON.stringify(paths.concat(key))}, a: ${getNodeType(sub)}, b: ${getNodeType(p.value)}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tthrow new TypeError(`Current does not support deep merge at paths: ${JSON.stringify(paths.concat(key))}, a: ${sub}, b: ${p.value}`)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcurrent.items.push(p)\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdoc.setIn(paths, result.value)\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow new TypeError(`Only YAMLMap can be merged [2]. path: ${paths}, node: ${node}`)\n\t\t}\n\t}\n\n\treturn doc\n}\n","\nimport { isMatch } from 'picomatch';\nimport {\n\tICachesFindPath,\n\tIFindPathEntry,\n\tIOptionsFind,\n\tIRecordWildcards,\n\tIVisitPathsListReadonly,\n\tIWildcardsYAMLDocument,\n} from './types';\nimport { Document, isDocument } from 'yaml';\nimport { PicomatchOptions } from 'picomatch';\n\nexport function pathsToWildcardsPath(paths: IVisitPathsListReadonly, full?: boolean)\n{\n\tlet s = paths.join('/');\n\tif (full)\n\t{\n\t\ts = `__${s}__`\n\t}\n\treturn s\n}\n\nexport function pathsToDotPath(paths: IVisitPathsListReadonly)\n{\n\treturn paths.join('.');\n}\n\n/**\n * Recursively searches for a path in a nested object or array structure.\n */\nexport function findPath(data: IRecordWildcards | Document | IWildcardsYAMLDocument,\n\tpaths: string[],\n\tfindOpts?: IOptionsFind,\n\tprefix: string[] = [],\n\tlist: IFindPathEntry[] = []\n)\n{\n\tfindOpts ??= {};\n\tprefix ??= [];\n\tlist ??= [];\n\n\tlet _cache: ICachesFindPath = {\n\t\tpaths: paths.slice(),\n\t\tfindOpts,\n\t\tprefix,\n\t\tglobOpts: findPathOptionsToGlobOptions(findOpts),\n\t}\n\n\tif (isDocument(data))\n\t{\n\t\t// @ts-ignore\n\t\t_cache.data = data;\n\n\t\tdata = data.toJSON() as IRecordWildcards;\n\t}\n\n\treturn _findPathCore(data, paths.slice(), findOpts, prefix, list, _cache)\n}\n\nexport function findPathOptionsToGlobOptions(findOpts?: IOptionsFind): PicomatchOptions\n{\n\treturn {\n\t\t...findOpts?.globOpts,\n\t\tignore: findOpts?.ignore,\n\t} satisfies PicomatchOptions\n}\n\nexport function _findPathCore(data: IRecordWildcards, paths: string[], findOpts: IOptionsFind, prefix: string[], list: IFindPathEntry[], _cache: ICachesFindPath)\n{\n\tpaths = paths.slice(); // Create a copy of the paths array to avoid modifying the original array.\n\tconst current = paths.shift(); // Remove the first element from the paths array.\n\tconst deep = paths.length > 0; // Check if there are remaining paths to search.\n\n\tfor (const key in data)\n\t{\n\t\tif (findOpts.onlyFirstMatchAll && list.length)\n\t\t{\n\t\t\tbreak;\n\t\t}\n\n\t\t// Create the current path.\n\t\tconst target = prefix.slice().concat(key);\n\t\tconst search = prefix.slice().concat(current);\n\n\t\t// Check if the current key matches the current path element.\n\t\t//const bool = isMatch(key, current);\n\t\tconst bool = isMatch(pathsToWildcardsPath(target), pathsToWildcardsPath(search), _cache.globOpts);\n\n\t\tif (bool)\n\t\t{\n\n\t\t\tconst value = data[key]; // Get the value at the current path.\n\n\t\t\tconst notArray = !Array.isArray(value); // Check if the value is not an array.\n\n\t\t\tif (deep)\n\t\t\t{\n\t\t\t\tif (notArray && typeof value !== 'string')\n\t\t\t\t{\n\t\t\t\t\t_findPathCore(value, paths, findOpts, target, list, _cache); // Recursively search for the remaining paths in the nested object or array.\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (!notArray)\n\t\t\t{\n\t\t\t\tlist.push({\n\t\t\t\t\tkey: target,\n\t\t\t\t\tvalue,\n\t\t\t\t}); // Add the found path and its corresponding value to the list.\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (!deep && _cache.findOpts.allowWildcardsAtEndMatchRecord && current.includes('*') && typeof value === 'object' && value)\n\t\t\t{\n\t\t\t\tlist.push({\n\t\t\t\t\tkey: target,\n\t\t\t\t\tvalue,\n\t\t\t\t}); // Add the found path and its corresponding value to the list.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!current.includes('*') || notArray && !deep)\n\t\t\t{\n\t\t\t\tthrow new TypeError(`Invalid Type. paths: [${target}], isMatch: ${bool}, deep: ${deep}, deep paths: [${paths}], notArray: ${notArray}, match: [${search}], value: ${value}, _cache : ${JSON.stringify(_cache)}`); // Throw an error if the value is not a string and there are remaining paths to search.\n\t\t\t}\n\t\t}\n\t}\n\n\tif (prefix.length === 0 && findOpts.throwWhenNotFound && !list.length)\n\t{\n\t\tthrow new RangeError(`Invalid Paths. paths: [${[current, ...paths]}], _cache : ${JSON.stringify(_cache)}`);\n\t}\n\n\treturn list; // Return the list of found paths and their corresponding values.\n}\n","import { Document, isDocument, isNode, Node } from 'yaml';\nimport {\n\tIFindPathEntry,\n\tIRecordWildcards,\n\tIOptionsCheckAllSelfLinkWildcardsExists,\n} from './types';\nimport {\n\tassertWildcardsPath,\n\tparseWildcardsYaml,\n} from './index';\nimport {\n\tconvertWildcardsNameToPaths,\n\tmatchDynamicPromptsWildcardsAll,\n} from './util';\nimport {\n\tfindPath\n} from './find';\nimport picomatch, { Matcher } from 'picomatch';\n\n/**\n * Checks if all self-link wildcards exist in a given object.\n *\n * @param obj - The object to check, can be a YAML string, Uint8Array, or a YAML Document/Node.\n * @param chkOpts - Optional options for the check.\n * @returns An object containing the results of the check.\n *\n * @throws Will throw an error if the provided object is not a YAML Document/Node and cannot be parsed as a YAML string.\n *\n * @remarks\n * This function will parse the provided object into a YAML Document/Node if it is not already one.\n * It will then extract all self-link wildcards from the YAML string representation of the object.\n * For each wildcard, it will check if it exists in the JSON representation of the object using the `findPath` function.\n * The function will return an object containing arrays of wildcard names that exist, do not exist, or were ignored due to the ignore option.\n * It will also include an array of any errors that occurred during the check.\n */\nexport function checkAllSelfLinkWildcardsExists(obj: IRecordWildcards | Node | Document | string | Uint8Array, chkOpts?: IOptionsCheckAllSelfLinkWildcardsExists)\n{\n\tchkOpts ??= {};\n\n\tconst maxErrors = chkOpts.maxErrors > 0 ? chkOpts.maxErrors : 10;\n\n\tif (!(isDocument(obj) || isNode(obj)))\n\t{\n\t\tobj = parseWildcardsYaml(obj as string)\n\t}\n\n\tconst str = obj.toString();\n\tconst json = obj.toJSON();\n\n let entries = matchDynamicPromptsWildcardsAll(str, {\n\t unsafe: true,\n\t ...chkOpts.optsMatch,\n\t unique: true,\n });\n\n\tlet isMatchIgnore: Matcher = () => false;\n\n\tif (chkOpts.ignore?.length)\n\t{\n\t\tisMatchIgnore = picomatch(chkOpts.ignore);\n\t}\n\n\tconst listHasExists: string[] = [];\n\tconst listHasExistsWildcards: string[] = [];\n\tconst ignoreList: string[] = [];\n\n\tconst errors: Error[] = [];\n\n\tfor (const entry of entries)\n\t{\n\t\tif (isMatchIgnore(entry.name))\n\t\t{\n\t\t\tignoreList.push(entry.name);\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst paths = convertWildcardsNameToPaths(entry.name);\n\n\t\t// @ts-ignore\n\t\tlet list: IFindPathEntry[] = [];\n\n\t\ttry\n\t\t{\n\t\t\tassertWildcardsPath(entry.name);\n\n\t\t\tlist = findPath(json, paths, {\n\t\t\t\tonlyFirstMatchAll: true,\n\t\t\t\tthrowWhenNotFound: true,\n\t\t\t\tallowWildcardsAtEndMatchRecord: chkOpts.allowWildcardsAtEndMatchRecord,\n\t\t\t});\n\n\t\t\tif (chkOpts.report)\n\t\t\t{\n\t\t\t\tlistHasExists.push(...list.map(v => v.key.join('/')));\n\n\t\t\t\tif (entry.name.includes('*'))\n\t\t\t\t{\n\t\t\t\t\tlistHasExistsWildcards.push(entry.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (e)\n\t\t{\n\t\t\terrors.push(e as any)\n\n\t\t\tif (errors.length >= maxErrors)\n\t\t\t{\n\t\t\t\tlet e2 = new RangeError(`Max Errors. errors.length ${errors.length} >= ${maxErrors}`);\n\t\t\t\terrors.unshift(e2)\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcontinue;\n\t\t}\n\t}\n\n\treturn {\n\t\tobj,\n\t\tlistHasExists,\n\t\tlistHasExistsWildcards,\n\t\tignoreList,\n\t\terrors,\n\t}\n}\n\n","/**\n * Created by user on 2024/5/21.\n */\nimport { Document, isDocument, ParsedNode, parseDocument, stringify, YAMLMap } from 'yaml';\nimport {\n\tdefaultOptionsParseDocument,\n\tdefaultOptionsStringify,\n\tgetOptionsFromDocument,\n\n} from './options';\nimport { _visitNormalizeScalar, visitWildcardsYAML } from './items';\nimport { createDefaultVisitWildcardsYAMLOptions, validWildcardsYamlData } from './valid';\nimport {\n\tIOptionsParseDocument,\n\tIOptionsStringify,\n\tIOptionsVisitor,\n\tIParseWildcardsYamlInputSource,\n\tIRecordWildcards,\n\tIWildcardsYAMLDocument,\n\tIWildcardsYAMLDocumentParsed,\n\tIWildcardsYAMLMapRoot,\n} from './types';\n\nexport * from './util';\nexport * from './options';\nexport * from './items';\nexport * from './valid';\nexport * from './merge';\nexport * from './find';\nexport * from './format';\nexport * from './check';\nexport * from './is';\nexport type * from './types';\n\n/**\n * Normalizes a YAML document by applying specific rules to its nodes.\n **/\nexport function normalizeDocument<T extends Document>(doc: T, opts?: IOptionsParseDocument)\n{\n\tlet options = getOptionsFromDocument(doc, opts);\n\n\tconst defaults = createDefaultVisitWildcardsYAMLOptions(options);\n\n\tlet checkUnsafeQuote = !options.disableUnsafeQuote;\n\n\tlet visitorOptions: IOptionsVisitor = {\n\t\t...defaults,\n\n\t\tScalar(key, node)\n\t\t{\n\t\t\treturn _visitNormalizeScalar(key, node, {\n\t\t\t\tcheckUnsafeQuote,\n\t\t\t\toptions,\n\t\t\t})\n\t\t},\n\t};\n\n\tvisitWildcardsYAML(doc, visitorOptions)\n}\n\n/**\n * Converts the given YAML data to a string, applying normalization and formatting.\n *\n * @returns - A string representation of the input YAML data, with normalization and formatting applied.\n *\n * @throws - Throws a `SyntaxError` if the input data is invalid according to the `validWildcardsYamlData` function.\n *\n * @remarks\n * This function takes the input YAML data and applies normalization and formatting using the provided options.\n * If the input data is a `Document` object, it first normalizes the document using the `normalizeDocument` function.\n * Then, it converts the normalized document to a string using the `toString` method with the specified options.\n * If the input data is not a `Document` object, it directly converts the data to a string using the `stringify` function with the specified options.\n *\n * @example\n * ```typescript\n * const yamlData: IRecordWildcards = {\n *   key1: ['value1', 'value2'],\n *   key2: {\n *     subkey1: ['value3', 'value4'],\n *   },\n * };\n *\n * const yamlString = stringifyWildcardsYamlData(yamlData);\n * console.log(yamlString);\n * // Output:\n * // key1:\n * //   - value1\n * //   - value2\n * // key2:\n * //   subkey1:\n * //     - value3\n * //     - value4\n * ```\n */\nexport function stringifyWildcardsYamlData<T extends IRecordWildcards | IWildcardsYAMLDocument | Document>(data: T | unknown,\n\topts?: IOptionsStringify,\n)\n{\n\tconst isDoc = isDocument(data);\n\n\tif (isDoc)\n\t{\n\t\topts = getOptionsFromDocument(data, opts);\n\t}\n\n\topts = defaultOptionsStringify(opts);\n\n\tif (isDoc)\n\t{\n\t\tnormalizeDocument(data, opts);\n\n\t\treturn data.toString(opts)\n\t}\n\n\treturn stringify(data, opts)\n}\n\n/**\n * Parses Stable Diffusion wildcards source to a YAML object.\n *\n * @returns - If `Contents` extends `ParsedNode`, returns a parsed `Document.Parsed` with the specified `Contents` and `Strict`.\n *            Otherwise, returns a parsed `Document` with the specified `Contents` and `Strict`.\n *\n * @throws - Throws a `SyntaxError` if the YAML data is invalid according to the `validWildcardsYamlData` function.\n *\n * @remarks\n * This function parses the given `source` string or Uint8Array to a YAML object.\n * It uses the `parseDocument` function from the `yaml` library with `keepSourceTokens: true` option.\n * Then, it validates the parsed data using the `validWildcardsYamlData` function.\n * Finally, it returns the parsed data.\n */\nexport function parseWildcardsYaml<Contents extends YAMLMap = IWildcardsYAMLMapRoot, Strict extends boolean = true>(source: IParseWildcardsYamlInputSource,\n\topts?: IOptionsParseDocument,\n): Contents extends ParsedNode\n\t? IWildcardsYAMLDocumentParsed<Contents, Strict>\n\t: IWildcardsYAMLDocument<Contents, Strict>\n{\n\topts = defaultOptionsParseDocument(opts);\n\n\tif (opts.allowEmptyDocument)\n\t{\n\t\tsource ??= '';\n\t}\n\n\tlet data = parseDocument<Contents, Strict>(source.toString(), opts);\n\n\tvalidWildcardsYamlData(data, opts)\n\n\t// @ts-ignore\n\treturn data\n}\n\nexport default parseWildcardsYaml\n"],"names":["getOptionsShared","opts","_opts","allowMultiRoot","disableUniqueItemValues","minifyPrompts","disableUnsafeQuote","defaultOptionsStringifyMinify","lineWidth","defaultOptionsStringify","blockQuote","defaultKeyType","defaultStringType","collectionStyle","uniqueKeys","defaultOptionsParseDocument","_opts2","prettyErrors","toStringDefaults","getOptionsFromDocument","doc","options","ExtractParents","stripZeroStr","value","replace","trimPrompts","normalizeWildcardsYamlString","trimPromptsDynamic","includes","_ExtractParents","Extractor","ebs","extract","i","_do","arr","reduce","a","eb","s","nest","input","str","pre","slice","index","push","trim","length","join","formatPrompts","stripBlankLines","appendEOF","isWildcardsYAMLDocument","isDocument","isWildcardsYAMLDocumentAndContentsIsMap","isMap","contents","isWildcardsYAMLMap","SYMBOL_YAML_NODE_TYPE_ALIAS","Symbol","for","SYMBOL_YAML_NODE_TYPE_DOC","SYMBOL_YAML_NODE_TYPE_MAP","SYMBOL_YAML_NODE_TYPE_PAIR","SYMBOL_YAML_NODE_TYPE_SCALAR","SYMBOL_YAML_NODE_TYPE_SEQ","SYMBOL_YAML_NODE_TYPE","RE_DYNAMIC_PROMPTS_WILDCARDS","RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE","RE_DYNAMIC_PROMPTS_WILDCARDS_GLOBAL","RegExp","flags","RE_DYNAMIC_PROMPTS_WILDCARDS_UNSAFE_GLOBAL","RE_WILDCARDS_NAME","RE_WILDCARDS_NAME_STAR","isDynamicPromptsWildcards","matchDynamicPromptsWildcards","isFullMatch","m","match","unsafe","_matchDynamicPromptsWildcardsCore","source","keyword","name","variables","isStarWildcards","matchDynamicPromptsWildcardsAllGenerator","ls","matchAll","matchDynamicPromptsWildcardsAll","unique","array_unique_overwrite","isWildcardsName","test","_isBadWildcardsNameCore","isBadWildcardsName","isBadWildcardsPath","assertWildcardsName","SyntaxError","assertWildcardsPath","convertWildcardsNameToPaths","split","isWildcardsPathSyntx","path","wildcardsPathToPaths","getNodeTypeSymbol","node","_getNodeTypeCore","sym","keyFor","e","getNodeType","isSameNodeType","b","_extractor","_checkBrackets","_extractor2","extractSync","_e$self","_result$index","result","self","error","near","infoNearExtractionError","message","_validMap","key","args","idx","items","findIndex","pair","isPair","paths","handleVisitPathsFull","elem","_validSeq","nodeSeq","entry","isScalar","_validPair","keyNode","notOk","isSafeKey","createDefaultVisitWildcardsYAMLOptions","defaults","Map","Seq","allowUnsafeKey","Pair","fn","uniqueSeqItems","validWildcardsYamlData","data","isNode","TypeError","visitWildcardsYAML","toJSON","allowEmptyDocument","rootKeys","Object","keys","_validKey","_checkValue","exec","_nearString","offset","Math","max","visitorOptions","visit","defaultCheckerIgnoreCase","toLowerCase","defaultChecker","uniqueSeqItemsChecker","checker","deepFindSingleRootAt","_result$paths$slice","_result$paths","child","isSeq","parent","_handleVisitPathsCore","nodePaths","filter","p","convertPairsToPathsList","map","handleVisitPaths","_node","findWildcardsYAMLPathsAll","RE_UNSAFE_QUOTE","RE_UNSAFE_VALUE","RE_UNSAFE_PLAIN","_visitNormalizeScalar","runtime","checkUnsafeQuote","type","res","getTopRootContents","getTopRootNodes","mergeWildcardsYAMLDocumentRoots","_mergeWildcardsYAMLDocumentRootsCore","mergeWildcardsYAMLDocumentJsonBy","deepmerge","_toJSON","v","_mergeSeqCore","mergeSeq","mergeFindSingleRoots","list","flat","current","getIn","forEach","sub","get","errKeys","errors","sub2","add","AggregateErrorExtra","JSON","stringify","concat","setIn","pathsToWildcardsPath","full","pathsToDotPath","findPath","findOpts","prefix","_findOpts","_prefix","_list","_cache","globOpts","findPathOptionsToGlobOptions","_findPathCore","ignore","shift","deep","onlyFirstMatchAll","target","search","bool","isMatch","notArray","Array","isArray","allowWildcardsAtEndMatchRecord","throwWhenNotFound","RangeError","checkAllSelfLinkWildcardsExists","obj","chkOpts","_chkOpts","_chkOpts$ignore","maxErrors","parseWildcardsYaml","toString","json","entries","optsMatch","isMatchIgnore","picomatch","listHasExists","listHasExistsWildcards","ignoreList","report","e2","unshift","normalizeDocument","Scalar","stringifyWildcardsYamlData","isDoc","_source","parseDocument"],"mappings":";;;;;;CAGM,SAAUA,gBAAgBA,CAAwCC,IAAQ,EAAA;CAAA,EAAA,IAAAC,KAAA,CAAA;GAE/E,CAAAA,KAAA,GAAAD,IAAI,MAAAC,IAAAA,IAAAA,KAAA,KAAAA,KAAAA,CAAAA,GAAAA,KAAA,GAAJD,IAAI,GAAK,EAAO,CAAA;GAChB,OAAO;KACNE,cAAc,EAAEF,IAAI,CAACE,cAAc;KACnCC,uBAAuB,EAAEH,IAAI,CAACG,uBAAuB;KACrDC,aAAa,EAAEJ,IAAI,CAACI,aAAa;KACjCC,kBAAkB,EAAEL,IAAI,CAACK,kBAAAA;IACzB,CAAA;CACF,CAAA;UAEgBC,6BAA6BA,GAAA;GAE5C,OAAO;CACNC,IAAAA,SAAS,EAAE,CAAC;CACZH,IAAAA,aAAa,EAAE,IAAA;IACsB,CAAA;CACvC,CAAA;CAEM,SAAUI,uBAAuBA,CAACR,IAAwB,EAAA;GAE/D,OAAO;CACNS,IAAAA,UAAU,EAAE,IAAI;CAChBC,IAAAA,cAAc,EAAE,OAAO;CACvBC,IAAAA,iBAAiB,EAAE,OAAO;CAK1BC,IAAAA,eAAe,EAAE,OAAO;CACxBC,IAAAA,UAAU,EAAE,IAAI;KAChB,GAAGb,IAAAA;IACyB,C