@isdk/json-repair 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import t from"@apidevtools/json-schema-ref-parser";import{cloneDeep as s}from"lodash-es";var i=class i{dereferencedSchema;options;constructor(t,s={}){this.dereferencedSchema=t,this.options=s}static async create(e,r={}){if(!e)return new i({},r);const h=new t,n=await h.dereference(s(e));return new i(n,r)}getSchemaForPath(t){let s=this.dereferencedSchema;for(const i of t){if(!s)return;if("object"===s.type||s.properties)s=s.properties?.[i]||s.additionalProperties;else{if("array"!==s.type&&!s.items)return 0===Object.keys(s).length?{}:void 0;s=Array.isArray(s.items)?s.items[i]||s.additionalItems:s.items}}return s}isValidProperty(t,s){const i=this.getSchemaForPath(t);return!i||(0===Object.keys(i).length||(!i.type||"object"===i.type)&&(i.properties&&null!==this.matchProperty(t,s)||!1!==i.additionalProperties))}matchProperty(t,s){const e=this.declaredPropertyNames(t);if(e.includes(s))return s;const r=this.options.keyMatching;if(!r||0===e.length)return null;if("function"==typeof r){const t=r(s,e);return"string"==typeof t&&""!==t?t:null}const h=i.normalizeName(s);return e.find(t=>i.normalizeName(t)===h)??null}declaredPropertyNames(t){const s=this.getSchemaForPath(t)?.properties;return s?Object.keys(s):[]}static normalizeName(t){return t.replace(/[\s_\-.]/g,"").toLowerCase()}isDeclaredProperty(t,s){const i=this.getSchemaForPath(t);return!!i?.properties&&Object.prototype.hasOwnProperty.call(i.properties,s)}hasDeclaredProperties(t){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.keys(s.properties).length>0}getExpectedTypes(t,s){const i=this.getSchemaForPath(t),e=i?.properties?.[s];return e?Array.isArray(e.type)?e.type:e.type?[e.type]:[]:[]}},e=class t{input="";pos=0;pathStack=[];walker;options;constructor(t,s={}){this.walker=t,this.options={coerceTypes:!0,...s}}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.cachedPath=null,this.cachedDeclaredKeys=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const s=this.peek(),i=this.walker.getSchemaForPath(this.pathStack);if("{"===s||t.declaresObject(i)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();if("["===s)return this.consumeArray();const e=this.pos,r=this.tryConsumeStrictValue(s);if(r.ok)return this.options.coerceTypes&&i?this.coerceValue(r.value,i,r.raw):r.value;this.pos=e;const h=this.consumeGreedyString();return this.options.coerceTypes&&i?this.coerceValue(h,i):h}tryConsumeStrictValue(t){const s=this.pos;let i=null;if('"'===t||"'"===t?i=()=>this.consumeString():this.isDigit(t)||"-"===t||"+"===t?i=()=>this.consumeNumber():"t"!==t&&"f"!==t&&"n"!==t||(i=()=>"n"===t?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const t=i(),e=this.input.slice(s,this.pos);if(this.skipWhitespace(),this.isAtDelimiter("structural")||this.pos>=this.input.length)return{ok:!0,value:t,raw:e}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties)}consumeObject(){const s={},i="{"===this.peek();for(i&&this.consumeChar("{"),this.skipWhitespace();this.pos<this.input.length&&"}"!==this.peek();){const e=this.pos;if(!i&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const r=this.consumeKey(this.pathStack);if(null===r)break;const h=[...this.pathStack],n=this.walker.matchProperty(h,r)??r;if(!i&&Object.prototype.hasOwnProperty.call(s,n)){this.pos=e;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(n);try{const i=this.consumeValue();(this.pos!==e||void 0!==i&&""!==i)&&this.isKeptProperty(h,n)&&t.setOwn(s,n,i)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()){if(this.isLookingAtKey(this.pathStack,this.pos+1)||i&&/^\s*[}]/.test(this.input.slice(this.pos+1)))this.consumeChar(","),this.skipWhitespace();else{if(!i)break;this.consumeChar(","),this.skipWhitespace()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===e)break}return i&&"}"===this.peek()&&this.consumeChar("}"),s}isKeptProperty(t,s){return"remove"!==this.options.additionalProperties||(!this.walker.hasDeclaredProperties(t)||this.walker.isDeclaredProperty(t,s))}static setOwn(t,s,i){Object.defineProperty(t,s,{value:i,enumerable:!0,writable:!0,configurable:!0})}consumeArray(){const t=[];this.consumeChar("["),this.skipWhitespace();let s=0;for(;this.pos<this.input.length&&"]"!==this.peek()&&"}"!==this.peek();){const i=this.pos;this.pathStack.push(s);try{const e=this.consumeValue();this.pos!==i&&(t.push(e),s++)}finally{this.pathStack.pop()}if(this.skipWhitespace(),","===this.peek()&&(this.consumeChar(","),this.skipWhitespace()),this.pos===i)break}return"]"===this.peek()&&this.consumeChar("]"),t}consumeKey(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();const s=this.matchDeclaredKey(this.pos,t);if(s)return this.pos+=s.length,s.key;let i="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)i+=this.next();return i}consumeGreedyString(){let t="";const s=[];let i=!1,e="";for(;this.pos<this.input.length;){const r=this.peek();if(0===s.length&&this.isAtDelimiter("greedy"))break;if(i){if(r===e){let t=0,s=this.pos-1;for(;s>=0&&"\\"===this.input[s];)t++,s--;t%2==0&&(i=!1)}}else if('"'===r||"'"===r)i=!0,e=r;else if("("===r||"["===r||"{"===r)s.push(r);else if(")"===r||"]"===r||"}"===r){const t=s[s.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&s.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],s=r[r.length-1];if(('"'===t||"'"===t)&&t===s){const s=r.slice(1,-1);let i=0;for(let e=0;e<s.length;e++)s[e]!==t||0!==e&&"\\"===s[e-1]||i++;if(i%2==1||0===i)return s}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new Map;cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(s){if(this.cachedPath&&this.cachedPath.length===s.length&&this.cachedPath.every((t,i)=>t===s[i]))return this.cachedDeclaredKeys;const i=!0===this.options.keyMatching,e=this.walker.declaredPropertyNames(s).filter(t=>/\s/.test(t.trim())).map(s=>{const e=`${i?"i":""}:${s}`;let r=t.declaredKeyPatterns.get(e);if(!r){const h=s.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");r=new RegExp(`^${h}(?=\\s*:)`,i?"i":""),t.declaredKeyPatterns.set(e,r)}return{name:s,pattern:r}}).sort((t,s)=>s.name.length-t.name.length);return this.cachedPath=[...s],this.cachedDeclaredKeys=e,e}matchDeclaredKey(s,i=this.pathStack){let e=s;for(;e<this.input.length&&this.isWhitespace(this.input[e]);)e++;if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const r=this.declaredMultiWordKeys(i);if(0===r.length)return null;const h=this.input.slice(e);let n=null;for(const{name:t,pattern:s}of r){const i=h.match(s);i&&(!n||i[0].length>n.length)&&(n={key:t,length:i[0].length})}return n}isAtDelimiter(t="greedy"){if(this.pos>=this.input.length)return!0;const s=this.peek();if("}"===s||"]"===s)return!0;const i="number"==typeof this.pathStack[this.pathStack.length-1];if(","===s){if(i)return!0;const s=this.input.slice(this.pos+1);return!!/^\s*[}\]]/.test(s)||(!!/^\s*$/.test(s)||this.isBoundaryAhead(this.pos+1,t))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const s=this.pos;this.skipWhitespace();const i=this.peek(),e="}"===i||"]"===i||","===i||this.isBoundaryAhead(this.pos,t);return this.pos=s,e}return!1}isLookingAtKey(t,s=this.pos){if(null!==this.matchDeclaredKey(s,t))return!0;const i=this.matchKey(s);return null!==i&&this.walker.isValidProperty(t,i)}matchKey(t=this.pos){const s=this.input.slice(t).match(/^\s*(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^\s"',:{}\[\]]+))\s*:/);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let e=s[1]??s[2]??s[3];return i&&(e=e.replace(/\\(["'\\])/g,"$1")),e}isBoundaryAhead(t,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(t,i))return!0;const e=this.matchKey(t);return null!==e&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,e):this.walker.isValidProperty(i,e))))}coerceValue(t,s,i){const e=Array.isArray(s.type)?s.type:s.type?[s.type]:[],r=String(t).trim();if(s.enum){const t=r.toLowerCase().replace(/[^a-z0-9]/g,"");for(const i of s.enum){if(t===String(i).toLowerCase().replace(/[^a-z0-9]/g,""))return i}}const h=null===t?"null":typeof t;if(e.length>0&&e.includes(h))return t;if(e.includes("string"))return null===t||"object"==typeof t||"string"==typeof t?t:void 0!==i?i.trim():String(t);if(e.includes("number")||e.includes("integer")){const t=r.replace(/(?<=\d)[,,](?=\d)/g,"").match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=t?parseFloat(t[0]):NaN;if(!isNaN(s))return e.includes("integer")?Math.round(s):s}if(e.includes("boolean")){const t=r.toLowerCase(),s=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(s.includes(t))return!1}return e.includes("null")&&"null"===r.toLowerCase()?null:t}consumeString(){const t=this.next();let s="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?(this.next(),this.pos<this.input.length&&(s+=this.next())):s+=this.next();return this.peek()===t&&this.next(),s}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const s=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return s?(this.pos+=s[0].length,parseFloat(s[0])):NaN}consumeBoolean(){const t=this.input.slice(this.pos);return t.startsWith("true")?(this.pos+=4,!0):!!t.startsWith("false")&&(this.pos+=5,!1)}consumeNull(){return this.pos+=4,null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}};async function r(t,s,r={}){const h=s instanceof i?s:await i.create(s,r);return new e(h,r).parse(t)}export{e as RepairParser,i as SchemaWalker,r as jsonRepair};
1
+ import{dereference as t}from"@apidevtools/json-schema-ref-parser";import{cloneDeep as e}from"lodash-es";var s=class{constructor(t){this.max=t}max;entries=new Map;compute(t,e){const s=this.entries.get(t);if(void 0!==s)return s;const i=e(t);return this.entries.set(t,i),this.entries.size>this.max&&this.entries.delete(this.entries.keys().next().value),i}get size(){return this.entries.size}},i=2e3;function r(t,e,s=e){return void 0===t?[...s]:"boolean"==typeof t?t?[...e]:[]:[...t]}var n=["js","python"],o=["line","block","hash"],h=[],c=[" ","\t","\n","\r","_","-","."];var u=new Map;function a(t,e){let s=t;if(e.separators){const t=e.separators.join("");let i=u.get(t);i||(i=new RegExp(`[${e.separators.map(t=>t.replace(/[\\\]^-]/g,"\\$&")).join("")}]`,"g"),u.set(t,i)),s=s.replace(i,"")}return e.foldCase?s.toLowerCase():s}var f=class n{dereferencedSchema;options;resolvedKeyMatching;constructor(t,e={}){this.dereferencedSchema=t,this.options=e}static async create(s,i={}){if(!s)return new n({},i);const r=await t(e(s));return new n(n.flatten(r),i)}static COMBINATORS=["allOf","anyOf","oneOf"];static SCHEMA_MAPS=["properties","patternProperties","$defs","definitions"];static SCHEMA_NODES=["items","additionalItems","additionalProperties","contains","not","propertyNames"];static SHARED_KEYWORDS=["type","properties","patternProperties","items","additionalItems","enum"];static flatten(t){return n.flattenNode(t,{nodes:new Map,merged:new Map})}static flattenMap(t,e){if(!t||"object"!=typeof t)return t;const s={};for(const[i,r]of Object.entries(t))s[i]=n.flattenNode(r,e);return s}static flattenNode(t,e){if(!t||"object"!=typeof t)return t;const s=e.nodes.get(t);if(s)return s;const i={};e.nodes.set(t,i);for(const[s,r]of Object.entries(t))n.COMBINATORS.includes(s)||(n.SCHEMA_MAPS.includes(s)?i[s]=n.flattenMap(r,e):n.SCHEMA_NODES.includes(s)?i[s]=Array.isArray(r)?r.map(t=>n.flattenNode(t,e)):n.flattenNode(r,e):i[s]=r);for(const s of n.COMBINATORS){const r=t[s];if(!Array.isArray(r))continue;const o="allOf"===s;for(const t of r){const s=n.flattenNode(t,e);s&&"object"==typeof s&&n.mergeInto(i,s,o,e)}}return i}static mergeInto(t,e,s,i){let r=i.merged.get(t);if(r||(r=new Set,i.merged.set(t,r)),!r.has(e)){r.add(e);for(const[r,o]of Object.entries(e))if(s||n.SHARED_KEYWORDS.includes(r))if("type"===r){const e=n.unique(t.type,o);t.type=1===e.length?e[0]:e}else if("enum"===r)t.enum=n.unique(t.enum,o);else if("required"===r)s&&(t.required=n.unique(t.required,o));else if("properties"===r||"patternProperties"===r){const e=t[r]??={};for(const[t,r]of Object.entries(o))e[t]?n.mergeInto(e[t],r,s,i):e[t]=r}else r in t||(t[r]=o)}}static unique(t,e){const s=Array.isArray(t)?t:void 0===t?[]:[t];for(const t of Array.isArray(e)?e:void 0===e?[]:[e])s.includes(t)||s.push(t);return s}getSchemaForPath(t){let e=this.dereferencedSchema;for(const s of t){if(!e)return;if("object"===e.type||e.properties||e.patternProperties)e=e.properties?.[s]??this.patternSchemaForNode(e,s)??this.valueSchemaOf(e);else{if("array"!==e.type&&!e.items)return 0===Object.keys(e).length?{}:void 0;e=Array.isArray(e.items)?e.items[s]||e.additionalItems:e.items}}return e}additionalPropertiesAt(t){return this.effectiveAdditionalProperties(this.getSchemaForPath(t))}effectiveAdditionalProperties(t){const e=t?.additionalProperties;return void 0!==e?e:this.options.additionalProperties??!0}valueSchemaOf(t){const e=this.effectiveAdditionalProperties(t);return"object"==typeof e&&null!==e?e:void 0}patternSchemaFor(t,e){return this.patternSchemaForNode(this.getSchemaForPath(t),e)}patternSchemaForNode(t,e){if("string"==typeof e)for(const[s,i]of n.patternEntries(t))if(n.patternOf(s)?.test(e))return i}matchesKeyPattern(t,e){const s=this.getSchemaForPath(t);return void 0!==this.patternSchemaForNode(s,e)||n.patternEntries(s).some(([t])=>null===n.patternOf(t))}hasKeyPatterns(t){return n.patternEntries(this.getSchemaForPath(t)).length>0}static patternEntries(t){const e=t?.patternProperties;return e&&"object"==typeof e?Object.entries(e):[]}static patterns=new s(i);static patternOf(t){return n.patterns.compute(t,t=>{try{return new RegExp(t)}catch{return null}})}isValidProperty(t,e){const s=this.getSchemaForPath(t);return!s||(0===Object.keys(s).length||(!s.type||"object"===s.type)&&this.allowsProperty(t,e))}allowsProperty(t,e){return null!==this.matchProperty(t,e)||(!!this.matchesKeyPattern(t,e)||(!1!==this.additionalPropertiesAt(t)||!(this.hasDeclaredProperties(t)||this.hasKeyPatterns(t))))}matchProperty(t,e){const s=this.declaredPropertyNames(t);if(s.includes(e))return e;const i=this.keyMatching;if(i.matcher){const t=i.matcher(e,s);return"string"==typeof t&&""!==t?t:null}if(0===s.length)return null;const r=a(e,i),n=i.foldCase||null!==i.separators;for(const[t,e]of Object.entries(i.aliases))if(s.includes(t)&&e.some(t=>a(t,i)===r))return t;return n?s.find(t=>a(t,i)===r)??null:null}get keyMatching(){return this.resolvedKeyMatching||(this.resolvedKeyMatching=function(t){if("function"==typeof t)return{foldCase:!1,separators:null,aliases:{},matcher:t};if(void 0===t||!1===t)return{foldCase:!1,separators:null,aliases:{},matcher:null};const e=!0===t?{}:t,s=r(e.forms,["case","separators"]);return{foldCase:s.includes("case"),separators:s.includes("separators")?e.separators??c:null,aliases:e.aliases??{},matcher:null}}(this.options.keyMatching)),this.resolvedKeyMatching}declaredPropertyNames(t){const e=this.getSchemaForPath(t)?.properties;return e?Object.keys(e):[]}isDeclaredProperty(t,e){const s=this.getSchemaForPath(t);return!!s?.properties&&Object.prototype.hasOwnProperty.call(s.properties,e)}hasDeclaredProperties(t){const e=this.getSchemaForPath(t);return!!e?.properties&&Object.keys(e.properties).length>0}getExpectedTypes(t,e){const s=this.getSchemaForPath(t),i=s?.properties?.[e]??this.patternSchemaForNode(s,e)??this.valueSchemaOf(s);return i?Array.isArray(i.type)?i.type:i.type?[i.type]:[]:[]}},l=512,d=new RegExp(String.raw`^\s*(?:"((?:\\.|[^"\\]){0,${l}})"|'((?:\\.|[^'\\]){0,${l}})'|([^\s"',:{}\[\]]{1,${l}}))\s*:`),p=class t{input="";pos=0;pathStack=[];walker;options;readFlags=new Set;dropped=[];commentStyles;literalDialects;constructor(t,e={}){this.walker=t,this.options={coerceTypes:!0,...e},this.commentStyles=r(this.options.comments,o,h),this.literalDialects=r(this.options.literals,n,n)}get consumed(){return this.pos}get droppedText(){return this.dropped}get flags(){return this.readFlags}get remainder(){return this.input.slice(this.pos)}parse(t){return this.input=t.trim(),this.pos=0,this.pathStack=[],this.cachedPath=null,this.cachedDeclaredKeys=[],this.readFlags.clear(),this.dropped=[],this.consumeValue()}consumeValue(){if(this.skipWhitespace(),this.pos>=this.input.length)return;const e=this.peek(),s=this.walker.getSchemaForPath(this.pathStack);if(this.pathStack.length>=t.MAX_NESTING&&("["===e||"{"===e||!1!==this.options.wrapArrays&&t.declaresArray(s)&&this.isLookingAtKey([...this.pathStack,0])||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack)))return void this.readFlags.add("nesting-limited");if("["===e)return this.consumeArray();if(!1!==this.options.wrapArrays&&t.declaresArray(s)&&("{"===e||this.isLookingAtKey([...this.pathStack,0])))return this.consumeArray(!0);if("{"===e||t.declaresObject(s)&&this.isLookingAtKey(this.pathStack))return this.consumeObject();const i=this.pos,r=this.tryConsumeStrictValue(e);if(r.ok)return this.options.coerceTypes&&s?this.coerceValue(r.value,s,r.raw):r.value;this.pos=i;const n=this.consumeUnterminatedString()??this.consumeGreedyString();this.swallowedComment(this.input.slice(i,this.pos))&&this.readFlags.add("comment-in-value");let o=t.guidesScalar(s)?void 0:this.dialectLiteral(n);if(!o&&s){const e=this.dialectLiteral(n);e&&t.allows(s,e.value)&&(o=e)}return o?(this.readFlags.add("non-json-literal"),o.value):this.options.coerceTypes&&s?this.coerceValue(n,s):n}static allows(t,e){return t.enum?t.enum.some(t=>t===e):"const"in t&&t.const===e}static guidesScalar(t){return!!t&&(void 0!==t.type||void 0!==t.enum||void 0!==t.const)}dialectLiteral(e){return this.literalDialects.includes("python")&&t.PYTHON_LITERALS.has(e)?{value:t.PYTHON_LITERALS.get(e)}:this.literalDialects.includes("js")&&t.JS_LITERALS.has(e)?{value:t.JS_LITERALS.get(e)}:void 0}static PYTHON_LITERALS=new Map([["True",!0],["False",!1],["None",null]]);static JS_LITERALS=new Map([["undefined",null]]);consumeUnterminatedString(){const t=this.options.unescapedQuotes??"keep";if("keep"===t||'"'!==this.peek())return;const e="declared"===t;for(let t=this.pos+1;t<this.input.length;t++){if("\\"===this.input[t]){t++;continue}if('"'!==this.input[t]||!this.closesValueAt(t,e))continue;this.next();let s="";for(;this.pos<t;)s+="\\"===this.peek()&&this.pos+1<t?this.consumeEscape():this.next();return this.next(),this.readFlags.add("unescaped-quote-inferred"),s}}closesValueAt(t,e){const s=this.pos;this.pos=t+1;const i=this.isAtDelimiter("structural");if(this.pos=s,!i)return!1;if(!e)return!0;const r=this.nextMemberPos(t+1);if(r>=this.input.length)return!0;if("}"===this.input[r]||"]"===this.input[r])return!0;const n=this.pathStack.slice(0,-1),o=this.matchKey(r+(","===this.input[r]?1:0));return null!==o&&null!==this.walker.matchProperty(n,o)}skipMemberGap(){if(this.skipWhitespace(),0===this.commentStyles.length)return;let t=!1;for(;this.skipOneComment();)t=!0,this.skipWhitespace();t&&this.readFlags.add("comment-skipped")}skipOneComment(){const t=this.input.slice(this.pos,this.pos+2);if("/*"===t&&this.commentStyles.includes("block")){const t=this.input.indexOf("*/",this.pos+2);return-1!==t&&(this.pos=t+2,!0)}return("//"===t&&this.commentStyles.includes("line")||!("#"!==t[0]||!this.commentStyles.includes("hash")))&&this.skipToLineEnd()}static COMMENT_GAP=/[\s{[,]/;swallowedComment(e){let s=null,i=!1;for(let r=0;r<e.length;r++){const n=e[r];if(s){i?i=!1:"\\"===n?i=!0:n===s&&(s=null);continue}if('"'===n||"'"===n){s=n;continue}if(0===r||!t.COMMENT_GAP.test(e[r-1]))continue;const o="#"===n?"hash":"/"===n&&"/"===e[r+1]?"line":"/"===n&&"*"===e[r+1]?"block":null;if(null!==o&&!this.commentStyles.includes(o))return!0}return!1}nextMemberPos(t){const e=this.pos;this.pos=t,this.skipMemberGap();const s=this.pos;return this.pos=e,s}skipToLineEnd(){const t=this.input.indexOf("\n",this.pos);return this.pos=-1===t?this.input.length:t,!0}tryConsumeStrictValue(e){const s=this.pos;let i=null;if('"'===e||"'"===e?i=()=>this.consumeString():this.isDigit(e)||"-"===e||"+"===e?i=()=>this.consumeNumber():"t"!==e&&"f"!==e&&"n"!==e||(i=()=>"n"===e?this.consumeNull():this.consumeBoolean()),!i)return{ok:!1,value:void 0};try{const r=i(),n=this.input.slice(s,this.pos);this.skipMemberGap();const o='"'!==e&&"'"!==e||t.closesString(n);if(this.isAtDelimiter("structural",o)||this.pos>=this.input.length)return{ok:!0,value:r,raw:n}}catch(t){}return this.pos=s,{ok:!1,value:void 0}}static MAX_NESTING=1e3;static declaresObject(t){return!!t&&(Array.isArray(t.type)?t.type.includes("object"):"object"===t.type||!!t.properties||!!t.patternProperties)}consumeObject(){const e={},s="{"===this.peek();for(s&&this.consumeChar("{"),this.skipMemberGap();this.pos<this.input.length&&"}"!==this.peek();){this.skipMemberGap();const i=this.danglingTail();if(i){this.dropped.push(i.text),this.readFlags.add("dangling-dropped"),this.pos=i.end;break}const r=this.pos;if(!s&&("]"===this.peek()||","===this.peek()&&!this.isLookingAtKey(this.pathStack.slice(0,-1),this.pos+1)))break;const n=this.consumeKey(this.pathStack);if(null===n)break;const o=[...this.pathStack],h=this.walker.matchProperty(o,n)??n;if(!s&&Object.prototype.hasOwnProperty.call(e,h)){this.pos=r;break}this.skipWhitespace(),":"===this.peek()&&this.consumeChar(":"),this.pathStack.push(h);try{const s=this.consumeValue();(this.pos!==r||void 0!==s&&""!==s)&&(this.walker.allowsProperty(o,h)?t.setOwn(e,h,s):(this.dropped.push(this.input.slice(r,this.pos).trim()),this.readFlags.add("undeclared-keys-dropped")))}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()){const t=this.nextMemberPos(this.pos+1);if(this.isLookingAtKey(this.pathStack,t)||s&&"}"===this.input[t])this.consumeChar(","),this.skipMemberGap();else{if(!s)break;this.consumeChar(","),this.skipMemberGap()}}else"}"!==this.peek()&&this.isLookingAtKey(this.pathStack)&&this.skipWhitespace();if(this.pos===r)break}return s&&"}"===this.peek()&&this.consumeChar("}"),e}static setOwn(t,e,s){Object.defineProperty(t,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}static declaresArray(t){return!!t&&(Array.isArray(t.type)?t.type.includes("array"):"array"===t.type||!!t.items)}consumeArray(t=!1){const e=[];t||this.consumeChar("["),this.skipMemberGap();let s=0;for(;this.pos<this.input.length;){if(this.skipMemberGap(),"]"===this.peek()){if(this.consumeChar("]"),this.skipWhitespace(),!this.startsAnotherRecord())break;continue}if("}"===this.peek())break;const t=this.pos;this.pathStack.push(s);try{const i=this.consumeValue();this.pos!==t&&(e.push(i),s++)}finally{this.pathStack.pop()}if(this.skipMemberGap(),","===this.peek()&&(this.consumeChar(","),this.skipMemberGap()),this.pos===t)break}return e}startsAnotherRecord(){const t=[...this.pathStack,0],e=this.walker.getSchemaForPath(t);if(!e)return!1;if("object"!==e.type&&!e.properties)return!1;if("{"===this.peek())return!0;if(this.matchDeclaredKey(this.pos,t))return!0;const s=this.matchKey(this.pos);return null!==s&&null!==this.walker.matchProperty(t,s)}consumeKey(t=this.pathStack){if(this.skipWhitespace(),this.pos>=this.input.length)return null;if('"'===this.peek()||"'"===this.peek())return this.consumeString();if("{"===this.peek()||"["===this.peek())return null;const e=this.matchDeclaredKey(this.pos,t);if(e)return this.pos+=e.length,e.key;let s="";for(;this.pos<this.input.length&&!this.isWhitespace(this.peek())&&":"!==this.peek()&&","!==this.peek()&&"}"!==this.peek()&&"]"!==this.peek()&&'"'!==this.peek()&&"'"!==this.peek();)s+=this.next();return s}consumeGreedyString(){let t="";const e=[];let s=!1,i="";for(;this.pos<this.input.length;){const r=this.peek();if(0===e.length&&this.isAtDelimiter("greedy",!s))break;if(s){if(r===i){let t=0,e=this.pos-1;for(;e>=0&&"\\"===this.input[e];)t++,e--;t%2==0&&(s=!1)}}else if('"'===r||"'"===r)s=!0,i=r;else if("("===r||"["===r||"{"===r)e.push(r);else if(")"===r||"]"===r||"}"===r){const t=e[e.length-1];(")"===r&&"("===t||"]"===r&&"["===t||"}"===r&&"{"===t)&&e.pop()}t+=this.next()}let r=t.trim();if(r.length>=2){const t=r[0],e=r[r.length-1];if(('"'===t||"'"===t)&&t===e){const e=r.slice(1,-1);let s=0;for(let i=0;i<e.length;i++)e[i]!==t||0!==i&&"\\"===e[i-1]||s++;if(s%2==1||0===s)return e}}return r}static WORD_CHAR=/[\p{L}\p{N}_]/u;static declaredKeyPatterns=new s(i);cachedPath=null;cachedDeclaredKeys=[];declaredMultiWordKeys(e){if(this.cachedPath&&this.cachedPath.length===e.length&&this.cachedPath.every((t,s)=>t===e[s]))return this.cachedDeclaredKeys;const s=this.walker.keyMatching,i=this.walker.declaredPropertyNames(e),r=[...i,...Object.entries(s.aliases).filter(([t])=>i.includes(t)).flatMap(([,t])=>t)].filter(t=>/\s/.test(t.trim())).map(e=>{const i=`${s.foldCase?"i":""}:${e}`,r=t.declaredKeyPatterns.compute(i,()=>{const t=e.trim().replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\s+/g,"\\s+");return new RegExp(`^${t}(?=\\s*:)`,s.foldCase?"i":"")});return{name:e,pattern:r}}).sort((t,e)=>e.name.length-t.name.length);return this.cachedPath=[...e],this.cachedDeclaredKeys=r,r}matchDeclaredKey(e,s=this.pathStack){let i=e;for(;i<this.input.length&&this.isWhitespace(this.input[i]);)i++;if(i>0&&t.WORD_CHAR.test(this.input[i-1]))return null;const r=this.declaredMultiWordKeys(s);if(0===r.length)return null;const n=this.input.slice(i);let o=null;for(const{name:t,pattern:e}of r){const s=n.match(e);s&&(!o||s[0].length>o.length)&&(o={key:t,length:s[0].length})}return o}isAtDelimiter(t="greedy",e=!0){if(this.pos>=this.input.length)return!0;const s=this.peek();if("}"===s||"]"===s)return!0;const i="number"==typeof this.pathStack[this.pathStack.length-1];if(","===s){if(i)return!0;const s=this.nextMemberPos(this.pos+1),r=this.input.slice(s);return!!/^[}\]]/.test(r)||(""===r.trimEnd()||(!(!e||!this.isDanglingTail(s))||this.isBoundaryAhead(s,t)))}if(this.isBoundaryAhead(this.pos,t))return!0;if(this.isWhitespace(s)){const e=this.pos;this.skipMemberGap();const s=this.peek(),i="}"===s||"]"===s||","===s||this.isBoundaryAhead(this.pos,t);return this.pos=e,i}return!1}isLookingAtKey(t,e=this.pos){if(null!==this.matchDeclaredKey(e,t))return!0;const s=this.matchKey(e);return null!==s&&this.walker.isValidProperty(t,s)}matchKey(e=this.pos){if(e>0&&t.WORD_CHAR.test(this.input[e-1]))return null;const s=this.input.slice(e).match(d);if(!s)return null;const i=void 0!==s[1]||void 0!==s[2];let r=s[1]??s[2]??s[3];return i&&(r=r.replace(/\\(["'\\])/g,"$1")),r}static DANGLING_TAIL=new RegExp(String.raw`^\s*("(?:\\.|[^"\\]){0,${l}}"?|'(?:\\.|[^'\\]){0,${l}}'?|[^\s"',:{}\[\]]{1,${l}})\s*[}\]]*\s*(?:\{|\[|$)`);danglingTail(e=this.pos){if(!1===this.options.dangling)return;const s=this.input.slice(e),i=t.DANGLING_TAIL.exec(s);if(!i)return;const r=i[1];return'"'!==r[0]&&"'"!==r[0]&&/^[\d.+-]+$/.test(r)?void 0:{text:r,end:e+i.index+r.length}}isDanglingTail(t=this.pos){return void 0!==this.danglingTail(t)}static closesString(t){const e=t[0];if(t.length<2||t[t.length-1]!==e)return!1;let s=0;for(let e=t.length-2;e>=0&&"\\"===t[e];e--)s++;return s%2==0}static PATH_NOT_KEY=/^\s*[^\s"',:{}\[\]]+:[/\\]/;isBoundaryAhead(e,s){const i=this.pathStack.slice(0,-1);if(null!==this.matchDeclaredKey(e,i))return!0;const r=this.matchKey(e);return null!==r&&(!t.PATH_NOT_KEY.test(this.input.slice(e))&&("structural"===s||("conservative"===this.options.stringCaptureStrategy||(this.walker.hasDeclaredProperties(i)?null!==this.walker.matchProperty(i,r)||void 0!==this.walker.patternSchemaFor(i,r):this.walker.isValidProperty(i,r)))))}coerceValue(e,s,i){const r=Array.isArray(s.type)?s.type:s.type?[s.type]:[],n=String(e).trim();if(s.enum){const i=t.enumSpelling(e);if(null!==i)for(const e of s.enum)if(t.enumSpelling(e)===i)return e}const o=null===e?"null":typeof e;if(r.length>0&&r.includes(o))return e;if(r.includes("string"))return null===e||"object"==typeof e||"string"==typeof e?e:void 0!==i?i.trim():String(e);if(r.includes("number")||r.includes("integer")){const t=n.replace(/(?<=\d)[,,](?=\d)/g,""),e=t.match(/-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?/),s=e?parseFloat(e[0]):NaN;if(!isNaN(s))return e&&this.reportNumberCoercion(t,e),r.includes("integer")?Math.round(s):s}if(r.includes("boolean")){const t=n.toLowerCase(),e=["false","no","off","0","取消","否","n","f"];if(["true","yes","on","1","ok","确定","是","y","t"].includes(t))return!0;if(e.includes(t))return!1}return r.includes("null")&&"null"===n.toLowerCase()?null:e}reportNumberCoercion(e,s){const i=s.index??0,r=(e.slice(0,i)+e.slice(i+s[0].length)).replace(t.COERCED_EDGE,"");""!==r&&(this.readFlags.add("coerced-text-dropped"),(r.split(/\s+/).length>=3||r.length>=20)&&this.dropped.push(r))}static COERCED_EDGE=/^[\s,]+|[\s,]+$/g;static enumSpelling(t){if("string"!=typeof t&&"number"!=typeof t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]/g,"");return""===e?null:e}static ESCAPE_MAP={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:"\n",r:"\r",t:"\t"};consumeEscape(){const e=this.options.escapes??"json5";if(this.next(),this.pos>=this.input.length)return"\\";const s=this.next(),i=t.ESCAPE_MAP[s],r="raw"===e||void 0!==i?0:"u"===s?4:"x"===s&&"json5"===e?2:0,n=r>0?this.readHex(r):null;return void 0!==i||null!==n&&"u"===s||this.readFlags.add("invalid-escape"),"raw"===e?`\\${s}`:void 0!==i?i:null!==n?String.fromCharCode(n):0===r&&"json5"===e?s:`\\${s}`}readHex(t){let e=0;for(let s=0;s<t;s++){const t=parseInt(this.input[this.pos+s],16);if(Number.isNaN(t))return null;e=16*e+t}return this.pos+=t,e}consumeString(){const t=this.next();let e="";for(;this.pos<this.input.length&&this.peek()!==t;)"\\"===this.peek()?e+=this.consumeEscape():e+=this.next();return this.peek()===t&&this.next(),e}static NUMBER_PATTERN=/^[+-]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][+-]?\d+)?/;consumeNumber(){const e=this.input.slice(this.pos).match(t.NUMBER_PATTERN);return e?(this.pos+=e[0].length,parseFloat(e[0])):NaN}consumeKeyword(e){const s=this.pos+e.length;if(this.input.slice(this.pos,s)!==e)return!1;const i=this.input[s];return(void 0===i||!t.WORD_CHAR.test(i))&&(this.pos=s,!0)}consumeBoolean(){return!!this.consumeKeyword("true")||(this.consumeKeyword("false"),!1)}consumeNull(){return this.consumeKeyword("null"),null}peek(){return this.input[this.pos]}next(){return this.input[this.pos++]}consumeChar(t){this.peek()===t&&this.next()}isWhitespace(t){return/\s/.test(t)}isDigit(t){return/[0-9]/.test(t)}skipWhitespace(){for(;this.pos<this.input.length&&this.isWhitespace(this.peek());)this.pos++}},m=/(?:```|~~~)[ \t]*[A-Za-z0-9+_-]*\s*$/,y=/^\s*(?:```|~~~)/;function g(t){const e=t.getSchemaForPath([]);return!!e&&(Array.isArray(e.type)?e.type.includes("array"):"array"===e.type||!!e.items)}function b(t,e){const s=function(t){const e=[];let s=0,i=-1,r=!1,n=!1;for(let o=0;o<t.length;o++){const h=t[o];r?n?n=!1:"\\"===h?n=!0:('"'===h||"\n"===h)&&(r=!1):'"'!==h?"{"!==h&&"["!==h?("}"===h||"]"===h)&&s>0&&(s--,0===s&&(e.push(w(t,i,o+1)),i=-1)):(0===s&&(i=o),s++):r=!0}s>0&&i>=0&&e.push(w(t,i,t.length,["truncated-candidate"]));return e}(t),i=e?v(t,e):void 0;if(i&&(0===s.length||i.start<s[0].start)){const e=s.filter(t=>t.end>i.end||t.start<i.start);return[i,...e].map(e=>S(t,e))}const r=e&&g(e)&&function(t){const e=t.getSchemaForPath([0]);return!(!e||"object"!==e.type&&!e.properties)}(e)?function(t,e){const s=[];for(const i of e){const e=s[s.length-1];e&&/^[\s,]*$/.test(t.slice(e.end,i.start))?s[s.length-1]=w(t,e.start,i.end,[...e.flags.filter(t=>"truncated-candidate"!==t),...i.flags,"sibling-objects-merged"]):s.push(i)}return s}(t,s):s;return r.map(e=>S(t,e))}function v(t,e){const s=[...e.declaredPropertyNames([]),...g(e)?e.declaredPropertyNames([0]):[]];if(0===s.length)return;let i;for(const e of s){const s=O(e).exec(t),r=s?.indices?.[1]?.[0];void 0!==r&&(void 0===i||r<i)&&(i=r)}return void 0!==i?w(t,i,t.length,["implicit-structure"]):void 0}var $=new s(i);function O(t){return $.compute(t,()=>{return new RegExp(`(?:^|[{[,\\s])(${e=t,e.replace(/[.*+?^${}()|[\\]\\]/g,"\\$&")})\\s*:`,"id");var e})}function w(t,e,s,i=[]){return{start:e,end:s,text:t.slice(e,s),flags:i}}function S(t,e){const s=[...e.flags],i=t.slice(0,e.start),r=t.slice(e.end);return!m.test(i)||!y.test(r)&&r.trim()||s.unshift("markdown-fence"),{...e,flags:s}}function j(t,e,s){const i=s.map(t=>t.text),r=[e,...s].sort((t,e)=>t.start-e.start),n=[];let o=0;for(const e of r){const s=t.slice(o,e.start).trim();s&&n.push({text:s,start:o}),o=Math.max(o,e.end)}const h=t.slice(o).trim();return h&&n.push({text:h,start:o}),{prose:n,fragments:i}}function A(t,e){const s={errors:0,requiredCovered:0,declaredCovered:0,undeclaredKeys:0,schemaEchoKeys:0},i=new Set;let r=0;const n=(t,o)=>{const h=e.getSchemaForPath(o);if(h){if(null!==t&&"object"==typeof t&&!Array.isArray(t)){const c=h.properties,u=new Set(Array.isArray(h.required)?h.required:[]);if(c)for(const e of Object.keys(c))Object.hasOwn(t,e)&&void 0!==t[e]&&(k(t[e],c[e])?(s.declaredCovered++,u.has(e)&&s.requiredCovered++):u.has(e)&&"string"==typeof t[e]&&""===t[e].trim()&&i.add("empty-required"));for(const i of Object.keys(t)){const h=e.declaredPropertyNames(o);!c&&!e.hasKeyPatterns(o)||h.includes(i)||void 0!==e.patternSchemaFor(o,i)||(s.undeclaredKeys++,M.has(i)&&(s.schemaEchoKeys++,r++)),n(t[i],[...o,i])}return}Array.isArray(t)&&t.forEach((e,s)=>n(t[s],[...o,s]))}};return n(t,[]),r>=2&&i.add("schema-echo-detected"),{score:s,flags:[...i]}}function N(t){return"string"==typeof t?(t.match(E)?.length??0)>=2:!(!t||"object"!=typeof t||Array.isArray(t))&&Object.keys(t).filter(t=>x.has(t)).length>=2}var E=/(?:^|[{,]\s*)["']?(?:\$schema|\$id|\$ref|\$defs|additionalProperties|properties|required|definitions|enum|anyOf|allOf|oneOf|items)["']?\s*:/g,x=new Set("$schema $id $ref $defs additionalProperties properties required definitions enum anyOf allOf oneOf items".split(" "));function k(t,e){if(void 0===t)return!1;if(null===t){return(Array.isArray(e?.type)?e.type:e?.type?[e.type]:[]).includes("null")}return"string"!=typeof t||""!==t.trim()}function P(t,e){return t.errors-e.errors||e.requiredCovered-t.requiredCovered||e.declaredCovered-t.declaredCovered||t.schemaEchoKeys-e.schemaEchoKeys}var M=new Set(["type","properties","required","additionalProperties","items","enum","allOf","anyOf","oneOf","not","format","pattern","minimum","maximum","minLength","maxLength","minItems","maxItems","definitions","$defs","$schema","$id","$ref","title","description","default"]);function C(t,e){const s=[];return T(t,[],e,s),s}function R(t,e=6){return t.slice(0,e).map(t=>{return`- ${e=t.path,0===e.length?"<root>":e.join(".")}: ${t.message}`;var e}).join("\n")}function T(t,e,s,i){const r=s.getSchemaForPath(e);if(r&&0!==Object.keys(r).length)if(function(t,e,s,i){const r=function(t){return null===t?"null":Array.isArray(t)?"array":void 0===t?"undefined":typeof t}(t);if(void 0!==e.type){const n=Array.isArray(e.type)?e.type:[e.type];n.some(e=>function(t,e,s){return e===s||"integer"===e&&("number"===s&&Number.isInteger(t))}(t,e,r))||i.push({path:s,message:`expected ${n.join(" or ")}, got ${r}`})}"const"in e&&!_(t,e.const)&&i.push({path:s,message:`expected the constant ${JSON.stringify(e.const)}`});if(Array.isArray(e.enum)){e.enum.some(e=>_(t,e))||i.push({path:s,message:`expected one of ${e.enum.map(t=>JSON.stringify(t)).join(", ")}, got ${JSON.stringify(t)}`})}"string"==typeof t&&("string"!=typeof e.pattern||function(t,e){try{return new RegExp(e).test(t)}catch{return!0}}(t,e.pattern)||i.push({path:s,message:`does not match pattern ${e.pattern}`}),"string"!=typeof e.format||function(t,e){const s=K[e];return!s||s.test(t)}(t,e.format)||i.push({path:s,message:`does not match format ${e.format}`}),"number"==typeof e.minLength&&t.length<e.minLength&&i.push({path:s,message:`shorter than minLength ${e.minLength}`}),"number"==typeof e.maxLength&&t.length>e.maxLength&&i.push({path:s,message:`longer than maxLength ${e.maxLength}`}));"number"==typeof t&&("number"==typeof e.minimum&&t<e.minimum&&i.push({path:s,message:`below minimum ${e.minimum}`}),"number"==typeof e.maximum&&t>e.maximum&&i.push({path:s,message:`above maximum ${e.maximum}`}),!0===e.exclusiveMinimum&&"number"==typeof e.minimum&&t===e.minimum&&i.push({path:s,message:`must be above minimum ${e.minimum}`}),!0===e.exclusiveMaximum&&"number"==typeof e.maximum&&t===e.maximum&&i.push({path:s,message:`must be below maximum ${e.maximum}`}));Array.isArray(t)&&("number"==typeof e.minItems&&t.length<e.minItems&&i.push({path:s,message:`fewer than minItems ${e.minItems}`}),"number"==typeof e.maxItems&&t.length>e.maxItems&&i.push({path:s,message:`more than maxItems ${e.maxItems}`}))}(t,r,e,i),Array.isArray(t))r.items&&t.forEach((r,n)=>T(t[n],[...e,n],s,i));else if(null!==t&&"object"==typeof t){const n=Array.isArray(r.required)?r.required:[];for(const s of n)Object.hasOwn(t,s)&&void 0!==t[s]||i.push({path:[...e,s],message:"missing required property"});for(const r of function(t){return Object.keys(t)}(t))s.allowsProperty(e,r)||i.push({path:[...e,r],message:"property is not declared by the Schema"}),T(t[r],[...e,r],s,i)}}function _(t,e){return function(t,e){if(t===e)return!0;if(null===t||null===e)return!1;if("object"!=typeof t||"object"!=typeof e)return!1;try{return JSON.stringify(t)===JSON.stringify(e)}catch{return!1}}(t,e)||function(t,e){const s=D(t),i=D(e);return null!==s&&null!==i&&s===i}(t,e)}function D(t){if("number"==typeof t)return Number.isFinite(t)?String(t):null;if("string"!=typeof t)return null;const e=t.trim();if(!/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(e))return null;const s=Number(e);return Number.isFinite(s)?String(s):null}var K={date:/^\d{4}-\d{2}-\d{2}$/,"date-time":/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/,time:/^\d{2}:\d{2}(:\d{2}(\.\d+)?)?$/,email:/^[^@\s]+@[^@\s]+\.[^@\s]+$/,uri:/^[a-z][a-z0-9+.-]*:\S*/i,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i};async function I(t,e,s={}){return(await L(t,e,s)).value}async function L(t,e,s={}){const i=e instanceof f?e:await f.create(e,s),r=t.trim();if(!1===s.locate||function(t){try{return JSON.parse(t),!0}catch{return!1}}(r)){const t=J(r,i,s),e=[...t.dropped,...t.leftover?[t.leftover]:[]];q(e,s);const n=[...t.flags];return N(t.value)&&n.push("schema-echo-detected"),{value:t.value,flags:n,errors:C(t.value,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:e}}const n=b(r,i);if(0===n.length){const t=new p(i,s),e=t.parse(r),n=new Set(t.flags),o=[];null!==e&&"object"==typeof e&&n.add("implicit-structure");const h=t.remainder.trim();return h&&(n.add("trailing-chatter"),o.push(h)),q(o,s),{value:e,flags:[...n],errors:C(e,i),candidates:[],discarded:"ignore"===s.onDiscard?[]:o}}const o=n.map(t=>{const e=J(t.text,i,s),{score:r,flags:n}=A(e.value,i),o=C(e.value,i);return r.errors=o.length,N(t.text)&&n.push("schema-echo-detected"),{region:{...t,score:r},value:e.value,errors:o,read:e.flags,leftover:[...e.dropped,...e.leftover?[e.leftover]:[]],suspicion:n}}),{ordered:h,duplicates:c}=function(t,e){const s=new Set;if(t.length>1){const e=new Map;for(const s of t)e.set(F(s.value),s);for(const i of t)e.get(F(i.value))!==i&&s.add(i.region);t=t.filter(t=>!s.has(t.region))}if(t.length>1&&"throw"===e)throw new Error(`Found ${t.length} JSON candidates where one was expected: ${t.map((t,e)=>`#${e+1} ${JSON.stringify(t.region.text.slice(0,60))} {errors: ${t.region.score.errors}, requiredCovered: ${t.region.score.requiredCovered}}`).join("; ")}`);if("last"===e)return{ordered:[...t].sort((t,e)=>e.region.start-t.region.start),duplicates:s};if("first"===e)return{ordered:[...t].sort((t,e)=>t.region.start-e.region.start),duplicates:s};const i=[...t].sort((t,e)=>P(t.region.score,e.region.score)||e.region.start-t.region.start);return{ordered:i,duplicates:s}}(o,s.onMultiple??"best"),u=h[0],a=h.slice(1),l="best"===(s.onMultiple??"best")&&a.length>0&&0===P(u.region.score,a[0].region.score),{prose:d,fragments:m}=j(r,u.region,o.filter(t=>t!==u).map(t=>t.region)),y=new Set([...u.region.flags,...u.read]);d.some(t=>t.start<u.region.start)&&y.add("prose-prefix"),d.some(t=>t.start>=u.region.end)&&y.add("trailing-chatter"),a.length>0&&y.add("extra-fragments-dropped"),c.size>0&&y.add("duplicate-candidates"),l&&y.add("ambiguous-candidates");for(const t of o)for(const e of t.suspicion)y.add(e);const g=[...d.map(t=>t.text),...m,...u.leftover];return q(g,s),{value:u.value,flags:[...y],errors:u.errors,candidates:o.map(t=>t.region),discarded:"ignore"===s.onDiscard?[]:g}}function J(t,e,s){const i=new p(e,s);let r=i.parse(t);!1!==s.wrapArrays&&g(e)&&void 0!==r&&!Array.isArray(r)&&(r=[r]);const n=i.remainder.trim(),o=[...i.flags];return n&&!o.includes("dangling-dropped")&&o.push("unparsed-tail"),{value:r,flags:o,dropped:[...i.droppedText],leftover:n}}function q(t,e){if("throw"===e.onDiscard&&0!==t.length)throw new Error(`Repair discarded ${t.length} piece(s) of the input: ${JSON.stringify(t)}`)}function F(t){return JSON.stringify(t)??String(t)}export{c as KEY_SEPARATORS,p as RepairParser,f as SchemaWalker,P as compareScores,j as discardedText,g as expectsArrayRoot,v as findImplicitRecordRegion,I as jsonRepair,L as jsonRepairResult,b as locateJsonCandidates,N as looksLikeSchemaEcho,R as renderValidatorErrors,A as scoreCandidate,C as validateValue};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@isdk/json-repair",
3
- "version": "0.1.3",
3
+ "version": "0.3.0",
4
4
  "description": "A powerful, schema-guided JSON repair library for fixing broken JSON generated by LLMs, featuring semantic coercion and fuzzy matching.",
5
5
  "keywords": [
6
6
  "json",
@@ -20,15 +20,26 @@
20
20
  "homepage": "https://github.com/isdk/json-repair.js",
21
21
  "repository": {
22
22
  "type": "git",
23
- "url": "https://github.com/isdk/json-repair.js"
23
+ "url": "git+https://github.com/isdk/json-repair.js.git"
24
24
  },
25
- "bugs": "https://github.com/@isdk/json-repair.js/issues",
25
+ "bugs": "https://github.com/isdk/json-repair.js/issues",
26
26
  "license": "MIT",
27
- "main": "dist/index.js",
28
- "types": "dist/index.d.ts",
29
27
  "type": "module",
28
+ "main": "./dist/index.cjs",
29
+ "module": "./dist/index.js",
30
+ "types": "./dist/index.d.ts",
30
31
  "exports": {
31
- ".": "./dist/index.js"
32
+ ".": {
33
+ "import": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "require": {
38
+ "types": "./dist/index.d.cts",
39
+ "default": "./dist/index.cjs"
40
+ }
41
+ },
42
+ "./package.json": "./package.json"
32
43
  },
33
44
  "dependencies": {
34
45
  "@apidevtools/json-schema-ref-parser": "^15.1.3",
@@ -43,6 +54,7 @@
43
54
  "eslint-config-prettier": "^10.1.8",
44
55
  "eslint-plugin-tsdoc": "^0.5.0",
45
56
  "prettier": "^3.8.1",
57
+ "prettier-plugin-markdown-table-layout": "^0.2.1",
46
58
  "terser": "^5.46.0",
47
59
  "tsup": "^8.5.1",
48
60
  "tsx": "^4.21.0",
@@ -53,6 +65,16 @@
53
65
  "vite-tsconfig-paths": "^6.0.5",
54
66
  "vitest": "^4.0.18"
55
67
  },
68
+ "files": [
69
+ "dist",
70
+ "README.cn.md",
71
+ "CHANGELOG.md",
72
+ "LICENSE-MIT"
73
+ ],
74
+ "engines": {
75
+ "node": ">=20.19"
76
+ },
77
+ "sideEffects": false,
56
78
  "scripts": {
57
79
  "build-fast": "tsup",
58
80
  "build": "pnpm run build-fast --dts-resolve --dts && pnpm run doc:md",
@@ -67,7 +89,8 @@
67
89
  "style:fix": "pnpm run format:fix && pnpm run lint:fix",
68
90
  "test": "vitest run",
69
91
  "typecheck": "tsc -p tsconfig.json",
70
- "release": "pnpm run clean && pnpm run build && git add -f docs && git ci -m 'docs: update API docs' && pnpm dlx commit-and-tag-version -s",
92
+ "release": "pnpm run style && pnpm run typecheck && pnpm test && pnpm run clean && pnpm run build && git add -f docs && (git diff --cached --quiet || git commit -m 'docs: update API docs') && pnpm dlx commit-and-tag-version -s",
93
+ "release.links": "grep -q 'github.com///' CHANGELOG.md && { sed -i 's|github.com///|github.com/isdk/json-repair.js/|g' CHANGELOG.md; git add CHANGELOG.md; git commit -m 'docs(changelog): repair the links the release tool wrote'; } || true",
71
94
  "release.alpha": "pnpm run release -- --prerelease alpha"
72
95
  }
73
96
  }
package/.prettierignore DELETED
@@ -1,12 +0,0 @@
1
- node_modules
2
- dist
3
- web
4
- docs
5
- .cache
6
-
7
- # 由 commit-and-tag-version 生成
8
- CHANGELOG.md
9
-
10
- # 本地编辑器配置 / 包管理器配置
11
- .vscode
12
- .npmrc
package/.prettierrc DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "singleQuote": true,
3
- "arrowParens": "always",
4
- "semi": false,
5
- "bracketSpacing": true,
6
- "trailingComma": "es5",
7
- "printWidth": 80
8
- }
package/.versionrc DELETED
@@ -1,36 +0,0 @@
1
- {
2
- "types": [
3
- {
4
- "type": "feat",
5
- "section": "Features"
6
- },
7
- {
8
- "type": "fix",
9
- "section": "Bug Fixes"
10
- },
11
- {
12
- "type": "chore",
13
- "hidden": true
14
- },
15
- {
16
- "type": "docs",
17
- "hidden": true
18
- },
19
- {
20
- "type": "style",
21
- "hidden": true
22
- },
23
- {
24
- "type": "refactor",
25
- "section": "Refactor"
26
- },
27
- {
28
- "type": "perf",
29
- "section": "Performance"
30
- },
31
- {
32
- "type": "test",
33
- "hidden": true
34
- }
35
- ]
36
- }
package/TODO DELETED
File without changes
package/docs/README.md DELETED
@@ -1,246 +0,0 @@
1
- **@isdk/json-repair**
2
-
3
- ***
4
-
5
- # @isdk/json-repair
6
-
7
- > 【English|[中文](_media/README.cn.md)】
8
-
9
- ---
10
-
11
- A powerful, schema-guided JSON repair library specifically designed to fix "broken" JSON generated by LLMs (Large Language Models).
12
-
13
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
14
- [![npm version](https://badge.fury.io/js/@isdk%2Fjson-repair.svg)](https://www.npmjs.com/package/@isdk/json-repair)
15
-
16
- ## 🚀 Why this library?
17
-
18
- LLMs often output JSON that is syntactically invalid or semantically "noisy". Common issues include:
19
-
20
- - Missing quotes around keys or values.
21
- - Unescaped quotes inside strings (e.g., `"a"b"`).
22
- - Missing commas or closing braces.
23
- - Natural language mixed into values (e.g., `"age": "about 30 years old"`).
24
- - Implicit structures (e.g., an array of objects without curly braces).
25
-
26
- Standard `json-repair` libraries only fix syntax. **@isdk/json-repair** uses your **JSON Schema** as a map to intelligently navigate, repair, and coerce the output into valid, structured data.
27
-
28
- ## ✨ Key Features
29
-
30
- - **Schema-Guided Repair**: Uses your Schema to resolve ambiguities (e.g., knowing if a colon marks a new key or is part of a string).
31
- - **Greedy String Capture**: Intelligently captures unquoted or broken strings until the next valid Schema key.
32
- - **Balanced Delimiter Tracking**: Correctly handles structural markers (commas, colons) inside parentheses, brackets, or braces within DSL-like strings (e.g., `@func(a, b)`).
33
- - **The "Parity Rule"**: Solves nested quote ambiguity (e.g., correctly distinguishing between `"A" OR "B"` and `"a"b"`).
34
- - **Semantic Coercion**:
35
- - **Fuzzy Enum Matching**: Matches "Processing!" to `"processing"` if defined in Schema enums.
36
- - **Noisy Number Extraction**: Extracts `1200.5` from `"Approx. 1,200.50 USD"`.
37
- - **Boolean Variants**: Recognizes `yes/no`, `on/off`, `1/0`, `确定/取消` as booleans.
38
- - **Declared Strings Stay Text**: `{ Population: 12 }` against `{ type: 'string' }` yields `"12"`, and the digits are taken from the document, so `{ id: 01234 }` yields `"01234"`.
39
- - **Implicit Structure Support**: Automatically repairs missing braces in objects and arrays.
40
- - **Robust Property Boundaries**: quoted keys may contain spaces and punctuation (`"Official language": "Italian"`), and a multi-word key the Schema declares is recognised even when the document leaves it unquoted; a value that parses cleanly is never re-tokenized, so valid JSON round-trips exactly like `JSON.parse`.
41
- - **Fuzzy Key Matching**: `user_name`, `userName` and `USER NAME` resolve to the property your Schema declares, and the output carries the declared name.
42
- - **Prototype-Safe Output**: keys such as `__proto__` or `constructor` are stored as own data properties, exactly as `JSON.parse` leaves them.
43
- - **Performance**: Support for reusing `SchemaWalker` instances for high-throughput batch processing.
44
-
45
- ## 📦 Installation
46
-
47
- ```bash
48
- npm install @isdk/json-repair @apidevtools/json-schema-ref-parser
49
- # or
50
- pnpm add @isdk/json-repair @apidevtools/json-schema-ref-parser
51
- ```
52
-
53
- ## 🛠 Usage
54
-
55
- ### 1. Schema-Guided Repair (Recommended)
56
-
57
- This is the most powerful way to use the library. Providing a schema enables advanced features like semantic coercion, greedy capture, and accurate disambiguation.
58
-
59
- ```typescript
60
- import { jsonRepair } from '@isdk/json-repair'
61
-
62
- const schema = {
63
- type: 'object',
64
- properties: {
65
- query: { type: 'string' },
66
- status: { enum: ['success', 'error'] },
67
- },
68
- }
69
-
70
- const brokenJson = '{ query: "python" OR "js", status: Success! }'
71
-
72
- const result = await jsonRepair(brokenJson, schema)
73
- console.log(result)
74
- // Output: { query: '"python" OR "js"', status: 'success' }
75
-
76
- // A multi-word key the Schema declares is found even when the document leaves it unquoted.
77
- const countrySchema = {
78
- type: 'object',
79
- properties: {
80
- Capital: { type: 'string' },
81
- 'Official language': { type: 'string' },
82
- },
83
- }
84
-
85
- console.log(
86
- await jsonRepair(
87
- '{ Capital: Berlin, Official language: Italian }',
88
- countrySchema
89
- )
90
- )
91
- // Output: { Capital: 'Berlin', 'Official language': 'Italian' }
92
- ```
93
-
94
- ### 2. Simple Usage (Without Schema)
95
-
96
- For basic syntax repair where schema guidance isn't required:
97
-
98
- ```typescript
99
- import { jsonRepair } from '@isdk/json-repair'
100
-
101
- const result = await jsonRepair('{ name: John, age: 30 }')
102
- console.log(result) // { name: 'John', age: 30 }
103
-
104
- // Quoted keys may contain spaces and punctuation; valid JSON round-trips untouched.
105
- const country = await jsonRepair(
106
- '{ "Capital": "Berlin", "Official language": "Italian" }'
107
- )
108
- console.log(country) // { Capital: 'Berlin', 'Official language': 'Italian' }
109
- ```
110
-
111
- ### Advanced: Reusing SchemaWalker (Batch Processing)
112
-
113
- For better performance when processing many items with the same schema:
114
-
115
- ```typescript
116
- import { jsonRepair, SchemaWalker } from '@isdk/json-repair'
117
-
118
- // Options that concern the Schema itself (`keyMatching`) belong to the walker.
119
- const walker = await SchemaWalker.create(mySchema, { keyMatching: true })
120
-
121
- for (const item of brokenItems) {
122
- const result = await jsonRepair(item, walker)
123
- // ...
124
- }
125
- ```
126
-
127
- ## 🧭 How Property Boundaries Are Detected
128
-
129
- While repairing a value, the parser must decide at every position whether an upcoming
130
- `"foo":` starts the **next property** or is just part of the **current value**. It uses two modes:
131
-
132
- 1. **Structural mode** — applies right after a value was parsed by the strict JSON path
133
- (a balanced `"string"`, a well-formed number, `true`/`false`/`null`).
134
- Any key-shaped token followed by `:` counts as the next property, _including quoted keys
135
- that contain whitespace or punctuation_ (`"Official language":`, `"a, b":`, `"a: b":`).
136
- A successful strict parse is **never** discarded, which is why valid JSON always yields
137
- exactly what `JSON.parse` would return.
138
- 2. **Greedy mode** — applies when the value could not be parsed strictly (unquoted text,
139
- unescaped inner quotes, `"A" OR "B"` expressions, DSL snippets such as `@func(a="x, y")`).
140
- - If the Schema declares property names for the current level, capture stops **only at a
141
- declared key**. Text that merely looks like a key stays inside the value:
142
- `{ "query": he said "hello there": loudly, "intent": "x" }` keeps
143
- `query = 'he said "hello there": loudly'`.
144
- - If the Schema declares no property names for that level (no schema, `type: "object"`
145
- without `properties`, or only `additionalProperties`), the parser falls back to
146
- “the first key-shaped token ends the value”.
147
- - A **declared** name is additionally searched for literally, so it is a breakpoint (and a key)
148
- even when the document left it unquoted and it contains whitespace. The generic key scanner
149
- cannot see a bare `Official language:` as one key — the Schema can:
150
- `{ Capital: Berlin, Official language: Italian }` yields
151
- `{ Capital: 'Berlin', 'Official language': 'Italian' }`. Under `keyMatching`, separator and
152
- case variants of a declared key (`user_name` for `userName`) end a value too.
153
-
154
- Set `stringCaptureStrategy: 'conservative'` to make greedy mode stop at _any_ key-shaped
155
- token, whatever the Schema declares (see [Repair Options](#-repair-options)).
156
-
157
- ### Thinking about the heuristic
158
-
159
- Ambiguity is missing information, not magic: `{ "note": see "foo bar": baz here, "b": 2 }`
160
- cannot be decided without a schema, because both readings are plausible. The principles the
161
- parser follows are:
162
-
163
- - A **cleanly parsed** value is trusted; whatever follows it is assumed to be structure.
164
- - A **messy** value is preserved as text whenever the Schema can name the real anchors.
165
- - A name the Schema **declares** is matched literally, so a multi-word key does not need quotes in the document to be recognised; a multi-word name the Schema does not declare is never treated as a key.
166
- - Consequently, **declaring the `properties` of the current level is the single most effective
167
- way to steer the repair** — declared keys act as breakpoints for greedy capture, and
168
- declared `type`/`enum` enable semantic coercion.
169
- - A level counts as an object when the Schema declares `properties` or `type: 'object'`, so
170
- omitting `type: 'object'` does not degrade a brace-less document into a scalar value.
171
- - If a value may legitimately contain `word:` or `"phrase":`, prefer having the model emit
172
- properly escaped JSON (then the strict parse wins outright), or declare that level's
173
- properties in the Schema.
174
- - If a value looks truncated right at something key-shaped, that level is probably missing
175
- `properties` in your Schema — add them and re-run.
176
-
177
- Numeric literals support scientific notation (`1e5`, `-2E2`) as well as the lax LLM forms
178
- `+5`, `.5` and `5.`. A partial literal such as `1.2.3` is kept as a string and then coerced
179
- according to the Schema.
180
-
181
- A declared `type: 'string'` is honoured in the other direction too: `12` becomes `"12"`, and
182
- because the text comes from the document rather than the parsed number, a leading zero
183
- survives (`{ id: 01234 }` → `"01234"`). `null` and structures are never stringified.
184
-
185
- ## ⚠️ Known Limitations & Disambiguation
186
-
187
- - **The "Parity Rule"**: When a string is wrapped in quotes and contains internal quotes, we count the internal ones.
188
- - Odd count (e.g., `"a"b"`): We assume the outer quotes are delimiters -> `a"b`.
189
- - Even count (e.g., `"A" OR "B"`): We assume the outer quotes are part of the expression -> `"A" OR "B"`.
190
- - **Limitation**: Highly unusual patterns like `"a"b"c"` might remain ambiguous.
191
- - **Key-shaped text inside a broken value (no schema guidance)**: when the Schema declares no property names for the current level, the first key-shaped token ends the value.
192
- `{ "note": see "foo bar": baz here, "b": 2 }` without a schema is therefore read as `{ note: 'see', 'foo bar': 'baz here', b: 2 }`. Declaring that level's `properties` makes greedy capture stop only at real keys and restores `{ note: 'see "foo bar": baz here', b: 2 }` (see [Thinking about the heuristic](#thinking-about-the-heuristic)).
193
- - **Unquoted multi-word keys need a declaration.** `{ Capital: Berlin, Official language: Italian }` becomes two properties because the Schema declares `Official language`. A spaced key that is _not_ declared is not a key: `{ Capital: Berlin, Official Lang: Italian }` keeps the whole text in `Capital` under the default `'aggressive'` strategy, and splits at the space (`{ Capital: 'Berlin, Official', Lang: 'Italian' }`) under `'conservative'`.
194
- - **Prose that repeats a declared key is cut there.** Declared keys are breakpoints, so `{ summary: the Official language: Italian is wrong, Official language: Italian }` reads `summary = 'the'`. If a value may legitimately repeat a declared key, have the model quote its keys or pick a less colliding property name.
195
- - **Markdown Blocks**: This library focuses on the JSON content. Please strip `json ...` markers before passing the string if your LLM includes them.
196
-
197
- ## ⚙️ Repair Options
198
-
199
- `jsonRepair(input, schema, options)` takes a fourth argument of type `RepairOptions`:
200
-
201
- | Option | Default | What it does |
202
- | ----------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
203
- | `coerceTypes` | `true` | Converts a value to the type the Schema declares: `"Approx. 1,200.50 USD"` → `1200.5`, `"yes"` → `true`, `"Processing!"` → `"processing"` when the enum says so, `12` → `"12"` under `type: 'string'` (the digits come from the document, so `{ id: 01234 }` → `"01234"`). `null` and structures are never stringified. |
204
- | `keyMatching` | `false` | Resolves incoming keys to the names the Schema declares. `true` ignores case and separators, so `user_name`, `userName` and `USER NAME` all match `userName`; a function `(key, properties) => string \| undefined` decides itself (`undefined` keeps the key as it is). A match renames the key in the output, which also re-enables coercion for that subtree. With `true` it also decides where greedy capture stops: `user_name:` ends a value when the Schema declares `userName`. |
205
- | `additionalProperties` | `'keep'` | `'remove'` drops keys the Schema does not declare. Applied only at levels that do declare `properties` — a free-form level has no “extra” keys and is left untouched. Independent of the JSON Schema keyword `additionalProperties: false`, which is honoured on its own. |
206
- | `stringCaptureStrategy` | `'aggressive'` | `'conservative'` ends greedy capture at any key-shaped token instead of only at declared Schema keys: less risk of one broken value swallowing the rest of the document, at the cost of cutting values short. |
207
-
208
- ```typescript
209
- const schema = {
210
- type: 'object',
211
- properties: {
212
- userName: { type: 'string' },
213
- userAge: { type: 'number' },
214
- },
215
- }
216
-
217
- await jsonRepair('{ user_name: "Ada", user_age: "36" }', schema, {
218
- keyMatching: true,
219
- coerceTypes: true,
220
- })
221
- // { userName: 'Ada', userAge: 36 }
222
-
223
- await jsonRepair('{ userName: "Ada", reasoning: "let me think…" }', schema, {
224
- additionalProperties: 'remove',
225
- })
226
- // { userName: 'Ada' }
227
-
228
- const querySchema = {
229
- type: 'object',
230
- properties: { query: { type: 'string' }, intent: { type: 'string' } },
231
- }
232
-
233
- await jsonRepair(
234
- '{ "query": he said "hello there": loudly, "intent": "x" }',
235
- querySchema,
236
- { stringCaptureStrategy: 'conservative' }
237
- )
238
- // { query: 'he said', 'hello there': 'loudly', intent: 'x' }
239
- ```
240
-
241
- `keyMatching` is read from the options passed to `SchemaWalker.create()` when you reuse a
242
- walker; the other options are read on every `jsonRepair()` call.
243
-
244
- ## 📄 License
245
-
246
- MIT © Riceball LEE